]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/treesocket2.cpp
e715fdffc0c1a61c916cb8cc131ff1c05aebbf8e
[user/henk/code/inspircd.git] / src / modules / m_spanningtree / treesocket2.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2007 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include "inspircd.h"
15 #include "configreader.h"
16 #include "users.h"
17 #include "channels.h"
18 #include "modules.h"
19 #include "commands/cmd_whois.h"
20 #include "commands/cmd_stats.h"
21 #include "socket.h"
22 #include "wildcard.h"
23 #include "xline.h"
24 #include "transport.h"
25 #include "socketengine.h"
26
27 #include "m_spanningtree/main.h"
28 #include "m_spanningtree/utils.h"
29 #include "m_spanningtree/treeserver.h"
30 #include "m_spanningtree/link.h"
31 #include "m_spanningtree/treesocket.h"
32 #include "m_spanningtree/resolvers.h"
33 #include "m_spanningtree/handshaketimer.h"
34
35 /* $ModDep: m_spanningtree/timesynctimer.h m_spanningtree/resolvers.h m_spanningtree/main.h m_spanningtree/utils.h m_spanningtree/treeserver.h m_spanningtree/link.h m_spanningtree/treesocket.h */
36
37 static std::map<std::string, std::string> warned;       /* Server names that have had protocol violation warnings displayed for them */
38
39 int TreeSocket::WriteLine(std::string line)
40 {
41         Instance->Log(DEBUG, "S[%d] -> %s", this->GetFd(), line.c_str());
42         line.append("\r\n");
43         return this->Write(line);
44 }
45
46
47 /* Handle ERROR command */
48 bool TreeSocket::Error(std::deque<std::string> &params)
49 {
50         if (params.size() < 1)
51                 return false;
52         this->Instance->SNO->WriteToSnoMask('l',"ERROR from %s: %s",(InboundServerName != "" ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
53         /* we will return false to cause the socket to close. */
54         return false;
55 }
56
57 bool TreeSocket::Modules(const std::string &prefix, std::deque<std::string> &params)
58 {
59         if (params.empty())
60                 return true;
61
62         if (!this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
63         {
64                 /* Pass it on, not for us */
65                 Utils->DoOneToOne(prefix, "MODULES", params, params[0]);
66                 return true;
67         }
68
69         char strbuf[MAXBUF];
70         std::deque<std::string> par;
71         par.push_back(prefix);
72         par.push_back("");
73
74         userrec* source = this->Instance->FindNick(prefix);
75         if (!source)
76                 return true;
77
78         for (unsigned int i = 0; i < Instance->Config->module_names.size(); i++)
79         {
80                 Version V = Instance->modules[i]->GetVersion();
81                 char modulename[MAXBUF];
82                 char flagstate[MAXBUF];
83                 *flagstate = 0;
84                 if (V.Flags & VF_STATIC)
85                         strlcat(flagstate,", static",MAXBUF);
86                 if (V.Flags & VF_VENDOR)
87                         strlcat(flagstate,", vendor",MAXBUF);
88                 if (V.Flags & VF_COMMON)
89                         strlcat(flagstate,", common",MAXBUF);
90                 if (V.Flags & VF_SERVICEPROVIDER)
91                         strlcat(flagstate,", service provider",MAXBUF);
92                 if (!flagstate[0])
93                         strcpy(flagstate,"  <no flags>");
94                 strlcpy(modulename,Instance->Config->module_names[i].c_str(),256);
95                 if (*source->oper)
96                 {
97                         snprintf(strbuf, MAXBUF, "::%s 900 %s :0x%08lx %d.%d.%d.%d %s (%s)",Instance->Config->ServerName,source->nick,(long unsigned int)Instance->modules[i],V.Major,V.Minor,V.Revision,V.Build,ServerConfig::CleanFilename(modulename),flagstate+2);
98                 }
99                 else
100                 {
101                         snprintf(strbuf, MAXBUF, "::%s 900 %s :%s",Instance->Config->ServerName,source->nick,ServerConfig::CleanFilename(modulename));
102                 }
103                 par[1] = strbuf;
104                 Utils->DoOneToOne(Instance->Config->ServerName, "PUSH", par, source->server);
105         }
106         snprintf(strbuf, MAXBUF, "::%s 901 %s :End of MODULES list", Instance->Config->ServerName, source->nick);
107         par[1] = strbuf;
108         Utils->DoOneToOne(Instance->Config->ServerName, "PUSH", par, source->server);
109         return true;
110 }
111
112 /** remote MOTD. leet, huh? */
113 bool TreeSocket::Motd(const std::string &prefix, std::deque<std::string> &params)
114 {
115         if (params.size() > 0)
116         {
117                 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
118                 {
119                         /* It's for our server */
120                         string_list results;
121                         userrec* source = this->Instance->FindNick(prefix);
122
123                         if (source)
124                         {
125                                 std::deque<std::string> par;
126                                 par.push_back(prefix);
127                                 par.push_back("");
128
129                                 if (!Instance->Config->MOTD.size())
130                                 {
131                                         par[1] = std::string("::")+Instance->Config->ServerName+" 422 "+source->nick+" :Message of the day file is missing.";
132                                         Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
133                                         return true;
134                                 }
135
136                                 par[1] = std::string("::")+Instance->Config->ServerName+" 375 "+source->nick+" :"+Instance->Config->ServerName+" message of the day";
137                                 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
138
139                                 for (unsigned int i = 0; i < Instance->Config->MOTD.size(); i++)
140                                 {
141                                         par[1] = std::string("::")+Instance->Config->ServerName+" 372 "+source->nick+" :- "+Instance->Config->MOTD[i];
142                                         Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
143                                 }
144
145                                 par[1] = std::string("::")+Instance->Config->ServerName+" 376 "+source->nick+" End of message of the day.";
146                                 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
147                         }
148                 }
149                 else
150                 {
151                         /* Pass it on */
152                         userrec* source = this->Instance->FindNick(prefix);
153                         if (source)
154                                 Utils->DoOneToOne(prefix, "MOTD", params, params[0]);
155                 }
156         }
157         return true;
158 }
159
160 /** remote ADMIN. leet, huh? */
161 bool TreeSocket::Admin(const std::string &prefix, std::deque<std::string> &params)
162 {
163         if (params.size() > 0)
164         {
165                 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
166                 {
167                         /* It's for our server */
168                         string_list results;
169                         userrec* source = this->Instance->FindNick(prefix);
170                         if (source)
171                         {
172                                 std::deque<std::string> par;
173                                 par.push_back(prefix);
174                                 par.push_back("");
175                                 par[1] = std::string("::")+Instance->Config->ServerName+" 256 "+source->nick+" :Administrative info for "+Instance->Config->ServerName;
176                                 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
177                                 par[1] = std::string("::")+Instance->Config->ServerName+" 257 "+source->nick+" :Name     - "+Instance->Config->AdminName;
178                                 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
179                                 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :Nickname - "+Instance->Config->AdminNick;
180                                 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
181                                 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :E-Mail   - "+Instance->Config->AdminEmail;
182                                 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
183                         }
184                 }
185                 else
186                 {
187                         /* Pass it on */
188                         userrec* source = this->Instance->FindNick(prefix);
189                         if (source)
190                                 Utils->DoOneToOne(prefix, "ADMIN", params, params[0]);
191                 }
192         }
193         return true;
194 }
195
196 bool TreeSocket::Stats(const std::string &prefix, std::deque<std::string> &params)
197 {
198         /* Get the reply to a STATS query if it matches this servername,
199          * and send it back as a load of PUSH queries
200          */
201         if (params.size() > 1)
202         {
203                 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[1]))
204                 {
205                         /* It's for our server */
206                         string_list results;
207                         userrec* source = this->Instance->FindNick(prefix);
208                         if (source)
209                         {
210                                 std::deque<std::string> par;
211                                 par.push_back(prefix);
212                                 par.push_back("");
213                                 DoStats(this->Instance, *(params[0].c_str()), source, results);
214                                 for (size_t i = 0; i < results.size(); i++)
215                                 {
216                                         par[1] = "::" + results[i];
217                                         Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
218                                 }
219                         }
220                 }
221                 else
222                 {
223                         /* Pass it on */
224                         userrec* source = this->Instance->FindNick(prefix);
225                         if (source)
226                                 Utils->DoOneToOne(prefix, "STATS", params, params[1]);
227                 }
228         }
229         return true;
230 }
231
232
233 /** Because the core won't let users or even SERVERS set +o,
234  * we use the OPERTYPE command to do this.
235  */
236 bool TreeSocket::OperType(const std::string &prefix, std::deque<std::string> &params)
237 {
238         if (params.size() != 1)
239                 return true;
240         std::string opertype = params[0];
241         userrec* u = this->Instance->FindNick(prefix);
242         if (u)
243         {
244                 u->modes[UM_OPERATOR] = 1;
245                 this->Instance->all_opers.push_back(u);
246                 strlcpy(u->oper,opertype.c_str(),NICKMAX-1);
247                 Utils->DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
248                 this->Instance->SNO->WriteToSnoMask('o',"From %s: User %s (%s@%s) is now an IRC operator of type %s",u->server, u->nick,u->ident,u->host,irc::Spacify(opertype.c_str()));
249         }
250         return true;
251 }
252
253 /** Because Andy insists that services-compatible servers must
254  * implement SVSNICK and SVSJOIN, that's exactly what we do :p
255  */
256 bool TreeSocket::ForceNick(const std::string &prefix, std::deque<std::string> &params)
257 {
258         if (params.size() < 3)
259                 return true;
260
261         userrec* u = this->Instance->FindNick(params[0]);
262
263         if (u)
264         {
265                 Utils->DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
266                 if (IS_LOCAL(u))
267                 {
268                         std::deque<std::string> par;
269                         par.push_back(params[1]);
270                         if (!u->ForceNickChange(params[1].c_str()))
271                         {
272                                 userrec::QuitUser(this->Instance, u, "Nickname collision");
273                                 return true;
274                         }
275                         u->age = atoi(params[2].c_str());
276                 }
277         }
278         return true;
279 }
280
281 bool TreeSocket::OperQuit(const std::string &prefix, std::deque<std::string> &params)
282 {
283         if (params.size() < 1)
284                 return true;
285
286         userrec* u = this->Instance->FindNick(prefix);
287
288         if (u)
289         {
290                 u->SetOperQuit(params[0]);
291                 params[0] = ":" + params[0];
292                 Utils->DoOneToAllButSender(prefix,"OPERQUIT",params,prefix);
293         }
294         return true;
295 }
296
297 /*
298  * Remote SQUIT (RSQUIT). Routing works similar to SVSNICK: Route it to the server that the target is connected to locally,
299  * then let that server do the dirty work (squit it!). Example:
300  * A -> B -> C -> D: oper on A squits D, A routes to B, B routes to C, C notices D connected locally, kills it. -- w00t
301  */
302 bool TreeSocket::RemoteSquit(const std::string &prefix, std::deque<std::string> &params)
303 {
304         /* ok.. :w00t RSQUIT jupe.barafranca.com :reason here */
305         if (params.size() < 2)
306                 return true;
307
308         TreeServer* s = Utils->FindServerMask(params[0]);
309
310         if (s)
311         {
312                 if (s == Utils->TreeRoot)
313                 {
314                         this->Instance->SNO->WriteToSnoMask('l',"What the fuck, I recieved a remote SQUIT for myself? :< (from %s", prefix.c_str());
315                         return true;
316                 }
317
318                 TreeSocket* sock = s->GetSocket();
319
320                 if (sock)
321                 {
322                         /* it's locally connected, KILL IT! */
323                         Instance->SNO->WriteToSnoMask('l',"RSQUIT: Server \002%s\002 removed from network by %s: %s", params[0].c_str(), prefix.c_str(), params[1].c_str());
324                         sock->Squit(s,"Server quit by " + prefix + ": " + params[1]);
325                         Instance->SE->DelFd(sock);
326                         sock->Close();
327                         delete sock;
328                 }
329                 else
330                 {
331                         /* route the rsquit */
332                         params[1] = ":" + params[1];
333                         Utils->DoOneToOne(prefix, "RSQUIT", params, params[0]);
334                 }
335         }
336         else
337         {
338                 /* mother fucker! it doesn't exist */
339         }
340
341         return true;
342 }
343
344 bool TreeSocket::ServiceJoin(const std::string &prefix, std::deque<std::string> &params)
345 {
346         if (params.size() < 2)
347                 return true;
348
349         userrec* u = this->Instance->FindNick(params[0]);
350
351         if (u)
352         {
353                 /* only join if it's local, otherwise just pass it on! */
354                 if (IS_LOCAL(u))
355                         chanrec::JoinUser(this->Instance, u, params[1].c_str(), false, "", Instance->Time());
356                 Utils->DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
357         }
358         return true;
359 }
360
361 bool TreeSocket::RemoteRehash(const std::string &prefix, std::deque<std::string> &params)
362 {
363         if (params.size() < 1)
364                 return false;
365
366         std::string servermask = params[0];
367
368         if (this->Instance->MatchText(this->Instance->Config->ServerName,servermask))
369         {
370                 this->Instance->SNO->WriteToSnoMask('l',"Remote rehash initiated by \002"+prefix+"\002.");
371                 this->Instance->RehashServer();
372                 Utils->ReadConfiguration(false);
373                 InitializeDisabledCommands(Instance->Config->DisabledCommands, Instance);
374         }
375         Utils->DoOneToAllButSender(prefix,"REHASH",params,prefix);
376         return true;
377 }
378
379 bool TreeSocket::LocalPong(const std::string &prefix, std::deque<std::string> &params)
380 {
381         if (params.size() < 1)
382                 return true;
383
384         if (params.size() == 1)
385         {
386                 TreeServer* ServerSource = Utils->FindServer(prefix);
387                 if (ServerSource)
388                 {
389                         ServerSource->SetPingFlag();
390                         ServerSource->rtt = Instance->Time() - ServerSource->LastPing;
391                 }
392         }
393         else
394         {
395                 std::string forwardto = params[1];
396                 if (forwardto == this->Instance->Config->ServerName)
397                 {
398                         /*
399                          * this is a PONG for us
400                          * if the prefix is a user, check theyre local, and if they are,
401                          * dump the PONG reply back to their fd. If its a server, do nowt.
402                          * Services might want to send these s->s, but we dont need to yet.
403                          */
404                         userrec* u = this->Instance->FindNick(prefix);
405                         if (u)
406                         {
407                                 u->WriteServ("PONG %s %s",params[0].c_str(),params[1].c_str());
408                         }
409                 }
410                 else
411                 {
412                         // not for us, pass it on :)
413                         Utils->DoOneToOne(prefix,"PONG",params,forwardto);
414                 }
415         }
416
417         return true;
418 }
419
420 bool TreeSocket::MetaData(const std::string &prefix, std::deque<std::string> &params)
421 {
422         if (params.size() < 2)
423                 return true;
424         else if (params.size() < 3)
425                 params.push_back("");
426         TreeServer* ServerSource = Utils->FindServer(prefix);
427         if (ServerSource)
428         {
429                 Utils->SetRemoteBursting(ServerSource, false);
430
431                 if (params[0] == "*")
432                 {
433                         FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));
434                 }
435                 else if (*(params[0].c_str()) == '#')
436                 {
437                         chanrec* c = this->Instance->FindChan(params[0]);
438                         if (c)
439                         {
440                                 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
441                         }
442                 }
443                 else if (*(params[0].c_str()) != '#')
444                 {
445                         userrec* u = this->Instance->FindNick(params[0]);
446                         if (u)
447                         {
448                                 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
449                         }
450                 }
451         }
452
453         params[2] = ":" + params[2];
454         Utils->DoOneToAllButSender(prefix,"METADATA",params,prefix);
455         return true;
456 }
457
458 bool TreeSocket::ServerVersion(const std::string &prefix, std::deque<std::string> &params)
459 {
460         if (params.size() < 1)
461                 return true;
462
463         TreeServer* ServerSource = Utils->FindServer(prefix);
464
465         if (ServerSource)
466         {
467                 ServerSource->SetVersion(params[0]);
468         }
469         params[0] = ":" + params[0];
470         Utils->DoOneToAllButSender(prefix,"VERSION",params,prefix);
471         return true;
472 }
473
474 bool TreeSocket::ChangeHost(const std::string &prefix, std::deque<std::string> &params)
475 {
476         if (params.size() < 1)
477                 return true;
478         userrec* u = this->Instance->FindNick(prefix);
479
480         if (u)
481         {
482                 u->ChangeDisplayedHost(params[0].c_str());
483                 Utils->DoOneToAllButSender(prefix,"FHOST",params,u->server);
484         }
485         return true;
486 }
487
488 bool TreeSocket::AddLine(const std::string &prefix, std::deque<std::string> &params)
489 {
490         if (params.size() < 6)
491                 return true;
492         bool propogate = false;
493         if (!this->bursting)
494                 Utils->lines_to_apply = 0;
495         switch (*(params[0].c_str()))
496         {
497                 case 'Z':
498                         propogate = Instance->XLines->add_zline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
499                         Instance->XLines->zline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
500                         if (propogate)
501                                 Utils->lines_to_apply |= APPLY_ZLINES;
502                 break;
503                 case 'Q':
504                         propogate = Instance->XLines->add_qline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
505                         Instance->XLines->qline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
506                         if (propogate)
507                                 Utils->lines_to_apply |= APPLY_QLINES;
508                 break;
509                 case 'E':
510                         propogate = Instance->XLines->add_eline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
511                         Instance->XLines->eline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
512                 break;
513                 case 'G':
514                         propogate = Instance->XLines->add_gline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
515                         Instance->XLines->gline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
516                         if (propogate)
517                                 Utils->lines_to_apply |= APPLY_GLINES;
518                 break;
519                 case 'K':
520                         propogate = Instance->XLines->add_kline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
521                         if (propogate)
522                                 Utils->lines_to_apply |= APPLY_KLINES;
523                 break;
524                 default:
525                         /* Just in case... */
526                         this->Instance->SNO->WriteToSnoMask('x',"\2WARNING\2: Invalid xline type '"+params[0]+"' sent by server "+prefix+", ignored!");
527                         propogate = false;
528                 break;
529         }
530         /* Send it on its way */
531         if (propogate)
532         {
533                 if (atoi(params[4].c_str()))
534                 {
535                         time_t c_requires_crap = ConvToInt(params[4]) + Instance->Time();
536                         this->Instance->SNO->WriteToSnoMask('x',"%s Added %cLINE on %s to expire on %s (%s).",prefix.c_str(),*(params[0].c_str()),params[1].c_str(),Instance->TimeString(c_requires_crap).c_str(),params[5].c_str());
537                 }
538                 else
539                 {
540                         this->Instance->SNO->WriteToSnoMask('x',"%s Added permenant %cLINE on %s (%s).",prefix.c_str(),*(params[0].c_str()),params[1].c_str(),params[5].c_str());
541                 }
542                 params[5] = ":" + params[5];
543                 Utils->DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
544         }
545         if (!this->bursting)
546         {
547                 Instance->XLines->apply_lines(Utils->lines_to_apply);
548                 Utils->lines_to_apply = 0;
549         }
550         return true;
551 }
552
553 bool TreeSocket::ChangeName(const std::string &prefix, std::deque<std::string> &params)
554 {
555         if (params.size() < 1)
556                 return true;
557         userrec* u = this->Instance->FindNick(prefix);
558         if (u)
559         {
560                 u->ChangeName(params[0].c_str());
561                 params[0] = ":" + params[0];
562                 Utils->DoOneToAllButSender(prefix,"FNAME",params,u->server);
563         }
564         return true;
565 }
566
567 bool TreeSocket::Whois(const std::string &prefix, std::deque<std::string> &params)
568 {
569         if (params.size() < 1)
570                 return true;
571         userrec* u = this->Instance->FindNick(prefix);
572         if (u)
573         {
574                 // an incoming request
575                 if (params.size() == 1)
576                 {
577                         userrec* x = this->Instance->FindNick(params[0]);
578                         if ((x) && (IS_LOCAL(x)))
579                         {
580                                 userrec* x = this->Instance->FindNick(params[0]);
581                                 char signon[MAXBUF];
582                                 char idle[MAXBUF];
583                                 snprintf(signon, MAXBUF, "%lu", (unsigned long)x->signon);
584                                 snprintf(idle, MAXBUF, "%lu", (unsigned long)abs((x->idle_lastmsg) - Instance->Time(true)));
585                                 std::deque<std::string> par;
586                                 par.push_back(prefix);
587                                 par.push_back(signon);
588                                 par.push_back(idle);
589                                 // ours, we're done, pass it BACK
590                                 Utils->DoOneToOne(params[0], "IDLE", par, u->server);
591                         }
592                         else
593                         {
594                                 // not ours pass it on
595                                 if (x)
596                                         Utils->DoOneToOne(prefix, "IDLE", params, x->server);
597                         }
598                 }
599                 else if (params.size() == 3)
600                 {
601                         std::string who_did_the_whois = params[0];
602                         userrec* who_to_send_to = this->Instance->FindNick(who_did_the_whois);
603                         if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
604                         {
605                                 // an incoming reply to a whois we sent out
606                                 std::string nick_whoised = prefix;
607                                 unsigned long signon = atoi(params[1].c_str());
608                                 unsigned long idle = atoi(params[2].c_str());
609                                 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
610                                 {
611                                         do_whois(this->Instance, who_to_send_to, u, signon, idle, nick_whoised.c_str());
612                                 }
613                         }
614                         else
615                         {
616                                 // not ours, pass it on
617                                 if (who_to_send_to)
618                                         Utils->DoOneToOne(prefix, "IDLE", params, who_to_send_to->server);
619                         }
620                 }
621         }
622         return true;
623 }
624
625 bool TreeSocket::Push(const std::string &prefix, std::deque<std::string> &params)
626 {
627         if (params.size() < 2)
628                 return true;
629         userrec* u = this->Instance->FindNick(params[0]);
630         if (!u)
631                 return true;
632         if (IS_LOCAL(u))
633         {
634                 u->Write(params[1]);
635         }
636         else
637         {
638                 // continue the raw onwards
639                 params[1] = ":" + params[1];
640                 Utils->DoOneToOne(prefix,"PUSH",params,u->server);
641         }
642         return true;
643 }
644
645 bool TreeSocket::HandleSetTime(const std::string &prefix, std::deque<std::string> &params)
646 {
647         if (!params.size() || !Utils->EnableTimeSync)
648                 return true;
649
650         bool force = false;
651
652         if ((params.size() == 2) && (params[1] == "FORCE"))
653                 force = true;
654
655         time_t them = atoi(params[0].c_str());
656         time_t us = Instance->Time(false);
657
658         time_t diff = them - us;
659
660         Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
661
662         if (force || (them != us))
663         {
664                 time_t old = Instance->SetTimeDelta(diff);
665                 Instance->Log(DEBUG, "TS (diff %d) from %s applied (old delta was %d)", diff, prefix.c_str(), old);
666         }
667
668         return true;
669 }
670
671 bool TreeSocket::Time(const std::string &prefix, std::deque<std::string> &params)
672 {
673         // :source.server TIME remote.server sendernick
674         // :remote.server TIME source.server sendernick TS
675         if (params.size() == 2)
676         {
677                 // someone querying our time?
678                 if (this->Instance->Config->ServerName == params[0])
679                 {
680                         userrec* u = this->Instance->FindNick(params[1]);
681                         if (u)
682                         {
683                                 params.push_back(ConvToStr(Instance->Time(false)));
684                                 params[0] = prefix;
685                                 Utils->DoOneToOne(this->Instance->Config->ServerName,"TIME",params,params[0]);
686                         }
687                 }
688                 else
689                 {
690                         // not us, pass it on
691                         userrec* u = this->Instance->FindNick(params[1]);
692                         if (u)
693                                 Utils->DoOneToOne(prefix,"TIME",params,params[0]);
694                 }
695         }
696         else if (params.size() == 3)
697         {
698                 // a response to a previous TIME
699                 userrec* u = this->Instance->FindNick(params[1]);
700                 if ((u) && (IS_LOCAL(u)))
701                 {
702                         time_t rawtime = atol(params[2].c_str());
703                         struct tm * timeinfo;
704                         timeinfo = localtime(&rawtime);
705                         char tms[26];
706                         snprintf(tms,26,"%s",asctime(timeinfo));
707                         tms[24] = 0;
708                         u->WriteServ("391 %s %s :%s",u->nick,prefix.c_str(),tms);
709                 }
710                 else
711                 {
712                         if (u)
713                                 Utils->DoOneToOne(prefix,"TIME",params,u->server);
714                 }
715         }
716         return true;
717 }
718
719 bool TreeSocket::LocalPing(const std::string &prefix, std::deque<std::string> &params)
720 {
721         if (params.size() < 1)
722                 return true;
723         if (params.size() == 1)
724         {
725                 std::string stufftobounce = params[0];
726                 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" PONG "+stufftobounce);
727                 return true;
728         }
729         else
730         {
731                 std::string forwardto = params[1];
732                 if (forwardto == this->Instance->Config->ServerName)
733                 {
734                         // this is a ping for us, send back PONG to the requesting server
735                         params[1] = params[0];
736                         params[0] = forwardto;
737                         Utils->DoOneToOne(forwardto,"PONG",params,params[1]);
738                 }
739                 else
740                 {
741                         // not for us, pass it on :)
742                         Utils->DoOneToOne(prefix,"PING",params,forwardto);
743                 }
744                 return true;
745         }
746 }
747
748 /** TODO: This creates a total mess of output and needs to really use irc::modestacker.
749  */
750 bool TreeSocket::RemoveStatus(const std::string &prefix, std::deque<std::string> &params)
751 {
752         if (params.size() < 1)
753                 return true;
754         chanrec* c = Instance->FindChan(params[0]);
755         if (c)
756         {
757                 for (char modeletter = 'A'; modeletter <= 'z'; modeletter++)
758                 {
759                         ModeHandler* mh = Instance->Modes->FindMode(modeletter, MODETYPE_CHANNEL);
760                         if (mh)
761                                 mh->RemoveMode(c);
762                 }
763         }
764         return true;
765 }
766
767 bool TreeSocket::RemoteServer(const std::string &prefix, std::deque<std::string> &params)
768 {
769         if (params.size() < 4)
770                 return false;
771         std::string servername = params[0];
772         std::string password = params[1];
773         // hopcount is not used for a remote server, we calculate this ourselves
774         std::string description = params[3];
775         TreeServer* ParentOfThis = Utils->FindServer(prefix);
776         if (!ParentOfThis)
777         {
778                 this->SendError("Protocol error - Introduced remote server from unknown server "+prefix);
779                 return false;
780         }
781         TreeServer* CheckDupe = Utils->FindServer(servername);
782         if (CheckDupe)
783         {
784                 this->SendError("Server "+servername+" already exists!");
785                 this->Instance->SNO->WriteToSnoMask('l',"Server \2"+servername+"\2 being introduced from \2" + prefix + "\2 denied, already exists. Closing link with " + prefix);
786                 return false;
787         }
788         Link* lnk = Utils->FindLink(servername);
789         TreeServer* Node = new TreeServer(this->Utils,this->Instance,servername,description,ParentOfThis,NULL, lnk ? lnk->Hidden : false);
790         ParentOfThis->AddChild(Node);
791         params[3] = ":" + params[3];
792         Utils->SetRemoteBursting(Node, true);
793         Utils->DoOneToAllButSender(prefix,"SERVER",params,prefix);
794         this->Instance->SNO->WriteToSnoMask('l',"Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
795         return true;
796 }
797
798 bool TreeSocket::ComparePass(const std::string &ours, const std::string &theirs)
799 {
800         if ((!strncmp(ours.c_str(), "HMAC-SHA256:", 12)) || (!strncmp(theirs.c_str(), "HMAC-SHA256:", 12)))
801         {
802                 /* One or both of us specified hmac sha256, but we don't have sha256 module loaded!
803                  * We can't allow this password as valid.
804                  */
805                 if (!Instance->FindModule("m_sha256.so") || !Utils->ChallengeResponse)
806                                 return false;
807                 else
808                         /* Straight string compare of hashes */
809                         return ours == theirs;
810         }
811         else
812                 /* Straight string compare of plaintext */
813                 return ours == theirs;
814 }
815
816 bool TreeSocket::Outbound_Reply_Server(std::deque<std::string> &params)
817 {
818         if (params.size() < 4)
819                 return false;
820
821         irc::string servername = params[0].c_str();
822         std::string sname = params[0];
823         std::string password = params[1];
824         std::string description = params[3];
825         int hops = atoi(params[2].c_str());
826
827         this->InboundServerName = sname;
828         this->InboundDescription = description;
829
830         if (hops)
831         {
832                 this->SendError("Server too far away for authentication");
833                 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
834                 return false;
835         }
836
837         for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
838         {
839                 if ((x->Name == servername) && ((ComparePass(this->MakePass(x->RecvPass,this->GetOurChallenge()),password)) || (x->RecvPass == password && (this->GetTheirChallenge().empty()))))
840                 {
841                         TreeServer* CheckDupe = Utils->FindServer(sname);
842                         if (CheckDupe)
843                         {
844                                 this->SendError("Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
845                                 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
846                                 return false;
847                         }
848                         // Begin the sync here. this kickstarts the
849                         // other side, waiting in WAIT_AUTH_2 state,
850                         // into starting their burst, as it shows
851                         // that we're happy.
852                         this->LinkState = CONNECTED;
853                         // we should add the details of this server now
854                         // to the servers tree, as a child of the root
855                         // node.
856                         TreeServer* Node = new TreeServer(this->Utils,this->Instance,sname,description,Utils->TreeRoot,this,x->Hidden);
857                         Utils->TreeRoot->AddChild(Node);
858                         params[3] = ":" + params[3];
859                         Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,sname);
860                         this->bursting = true;
861                         this->DoBurst(Node);
862                         return true;
863                 }
864         }
865         this->SendError("Invalid credentials");
866         this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
867         return false;
868 }
869
870 bool TreeSocket::Inbound_Server(std::deque<std::string> &params)
871 {
872         if (params.size() < 4)
873                 return false;
874         irc::string servername = params[0].c_str();
875         std::string sname = params[0];
876         std::string password = params[1];
877         std::string description = params[3];
878         int hops = atoi(params[2].c_str());
879
880         this->InboundServerName = sname;
881         this->InboundDescription = description;
882
883         if (hops)
884         {
885                 this->SendError("Server too far away for authentication");
886                 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
887                 return false;
888         }
889
890         for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
891         {
892                 if ((x->Name == servername) && ((ComparePass(this->MakePass(x->RecvPass,this->GetOurChallenge()),password) || x->RecvPass == password && (this->GetTheirChallenge().empty()))))
893                 {
894                         /* First check for instances of the server that are waiting between the inbound and outbound SERVER command */
895                         TreeSocket* CheckDupeSocket = Utils->FindBurstingServer(sname);
896                         if (CheckDupeSocket)
897                         {
898                                 /* If we find one, we abort the link to prevent a race condition */
899                                 this->SendError("Negotiation collision");
900                                 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists in a negotiating state.");
901                                 CheckDupeSocket->SendError("Negotiation collision");
902                                 Instance->SE->DelFd(CheckDupeSocket);
903                                 CheckDupeSocket->Close();
904                                 delete CheckDupeSocket;
905                                 return false;
906                         }
907                         /* Now check for fully initialized instances of the server */
908                         TreeServer* CheckDupe = Utils->FindServer(sname);
909                         if (CheckDupe)
910                         {
911                                 this->SendError("Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
912                                 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
913                                 return false;
914                         }
915                         this->Instance->SNO->WriteToSnoMask('l',"Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
916                         if (this->Hook)
917                         {
918                                 std::string name = InspSocketNameRequest((Module*)Utils->Creator, this->Hook).Send();
919                                 this->Instance->SNO->WriteToSnoMask('l',"Connection from \2"+sname+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] using transport \2"+name+"\2");
920                         }
921
922                         Utils->AddBurstingServer(sname,this);
923
924                         // this is good. Send our details: Our server name and description and hopcount of 0,
925                         // along with the sendpass from this block.
926                         this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+this->MakePass(x->SendPass, this->GetTheirChallenge())+" 0 :"+this->Instance->Config->ServerDesc);
927                         // move to the next state, we are now waiting for THEM.
928                         this->LinkState = WAIT_AUTH_2;
929                         return true;
930                 }
931         }
932         this->SendError("Invalid credentials");
933         this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
934         return false;
935 }
936
937 void TreeSocket::Split(const std::string &line, std::deque<std::string> &n)
938 {
939         n.clear();
940         irc::tokenstream tokens(line);
941         std::string param;
942         while (tokens.GetToken(param))
943         {
944                 if (!param.empty())
945                         n.push_back(param);
946         }
947         return;
948 }
949
950 bool TreeSocket::ProcessLine(std::string &line)
951 {
952         std::deque<std::string> params;
953         irc::string command;
954         std::string prefix;
955
956         line = line.substr(0, line.find_first_of("\r\n"));
957
958         if (line.empty())
959                 return true;
960
961         Instance->Log(DEBUG, "S[%d] <- %s", this->GetFd(), line.c_str());
962
963         this->Split(line.c_str(),params);
964         
965         if (params.empty())
966                 return true;
967         
968         if ((params[0][0] == ':') && (params.size() > 1))
969         {
970                 prefix = params[0].substr(1);
971                 params.pop_front();
972         }
973         command = params[0].c_str();
974         params.pop_front();
975         switch (this->LinkState)
976         {
977                 TreeServer* Node;
978
979                 case WAIT_AUTH_1:
980                         // Waiting for SERVER command from remote server. Server initiating
981                         // the connection sends the first SERVER command, listening server
982                         // replies with theirs if its happy, then if the initiator is happy,
983                         // it starts to send its net sync, which starts the merge, otherwise
984                         // it sends an ERROR.
985                         if (command == "PASS")
986                         {
987                                 /* Silently ignored */
988                         }
989                         else if (command == "SERVER")
990                         {
991                                 return this->Inbound_Server(params);
992                         }
993                         else if (command == "ERROR")
994                         {
995                                 return this->Error(params);
996                         }
997                         else if (command == "USER")
998                         {
999                                 this->SendError("Client connections to this port are prohibited.");
1000                                 return false;
1001                         }
1002                         else if (command == "CAPAB")
1003                         {
1004                                 return this->Capab(params);
1005                         }
1006                         else if ((command == "U") || (command == "S"))
1007                         {
1008                                 this->SendError("Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
1009                                 return false;
1010                         }
1011                         else
1012                         {
1013                                 irc::string error = "Invalid command in negotiation phase: " + command;
1014                                 this->SendError(assign(error));
1015                                 return false;
1016                         }
1017                 break;
1018                 case WAIT_AUTH_2:
1019                         // Waiting for start of other side's netmerge to say they liked our
1020                         // password.
1021                         if (command == "SERVER")
1022                         {
1023                                 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1024                                 // silently ignore.
1025                                 return true;
1026                         }
1027                         else if ((command == "U") || (command == "S"))
1028                         {
1029                                 this->SendError("Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
1030                                 return false;
1031                         }
1032                         else if (command == "BURST")
1033                         {
1034                                 if (params.size() && Utils->EnableTimeSync)
1035                                 {
1036                                         bool we_have_delta = (Instance->Time(false) != Instance->Time(true));
1037                                         time_t them = atoi(params[0].c_str());
1038                                         time_t delta = them - Instance->Time(false);
1039                                         if ((delta < -300) || (delta > 300))
1040                                         {
1041                                                 Instance->SNO->WriteToSnoMask('l',"\2ERROR\2: Your clocks are out by %d seconds (this is more than five minutes). Link aborted, \2PLEASE SYNC YOUR CLOCKS!\2",abs(delta));
1042                                                 SendError("Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than five minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
1043                                                 return false;
1044                                         }
1045                                         else if ((delta < -30) || (delta > 30))
1046                                         {
1047                                                 Instance->SNO->WriteToSnoMask('l',"\2WARNING\2: Your clocks are out by %d seconds. Please consider synching your clocks.", abs(delta));
1048                                         }
1049
1050                                         if (!Utils->MasterTime && !we_have_delta)
1051                                         {
1052                                                 this->Instance->SetTimeDelta(delta);
1053                                                 // Send this new timestamp to any other servers
1054                                                 Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
1055                                         }
1056                                 }
1057                                 this->LinkState = CONNECTED;
1058                                 Link* lnk = Utils->FindLink(InboundServerName);
1059                                 Node = new TreeServer(this->Utils,this->Instance, InboundServerName, InboundDescription, Utils->TreeRoot, this, lnk ? lnk->Hidden : false);
1060                                 Utils->DelBurstingServer(this);
1061                                 Utils->TreeRoot->AddChild(Node);
1062                                 params.clear();
1063                                 params.push_back(InboundServerName);
1064                                 params.push_back("*");
1065                                 params.push_back("1");
1066                                 params.push_back(":"+InboundDescription);
1067                                 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,InboundServerName);
1068                                 this->bursting = true;
1069                                 this->DoBurst(Node);
1070                         }
1071                         else if (command == "ERROR")
1072                         {
1073                                 return this->Error(params);
1074                         }
1075                         else if (command == "CAPAB")
1076                         {
1077                                 return this->Capab(params);
1078                         }
1079
1080                 break;
1081                 case LISTENER:
1082                         this->SendError("Internal error -- listening socket accepted its own descriptor!!!");
1083                         return false;
1084                 break;
1085                 case CONNECTING:
1086                         if (command == "SERVER")
1087                         {
1088                                 // another server we connected to, which was in WAIT_AUTH_1 state,
1089                                 // has just sent us their credentials. If we get this far, theyre
1090                                 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1091                                 // if we're happy with this, we should send our netburst which
1092                                 // kickstarts the merge.
1093                                 return this->Outbound_Reply_Server(params);
1094                         }
1095                         else if (command == "ERROR")
1096                         {
1097                                 return this->Error(params);
1098                         }
1099                         else if (command == "CAPAB")
1100                         {
1101                                 return this->Capab(params);
1102                         }
1103                 break;
1104                 case CONNECTED:
1105                         // This is the 'authenticated' state, when all passwords
1106                         // have been exchanged and anything past this point is taken
1107                         // as gospel.
1108
1109                         if (!prefix.empty())
1110                         {
1111                                 std::string direction = prefix;
1112                                 userrec* t = this->Instance->FindNick(prefix);
1113                                 if (t)
1114                                 {
1115                                         direction = t->server;
1116                                 }
1117                                 TreeServer* route_back_again = Utils->BestRouteTo(direction);
1118                                 if ((!route_back_again) || (route_back_again->GetSocket() != this))
1119                                 {
1120                                         if (route_back_again)
1121                                                 Instance->Log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
1122                                         return true;
1123                                 }
1124                                 /* Fix by brain:
1125                                  * When there is activity on the socket, reset the ping counter so
1126                                  * that we're not wasting bandwidth pinging an active server.
1127                                  */
1128                                 route_back_again->SetNextPingTime(time(NULL) + 60);
1129                                 route_back_again->SetPingFlag();
1130                         }
1131                         else
1132                         {
1133                                 prefix = this->GetName();
1134                         }
1135
1136                         if ((command == "MODE") && (params.size() >= 2))
1137                         {
1138                                 chanrec* channel = Instance->FindChan(params[0]);
1139                                 if (channel)
1140                                 {
1141                                         userrec* x = Instance->FindNick(prefix);
1142                                         if (x)
1143                                         {
1144                                                 if (warned.find(x->server) == warned.end())
1145                                                 {
1146                                                         Instance->Log(DEFAULT,"WARNING: I revceived modes '%s' from another server '%s'. This is not compliant with InspIRCd. Please check that server for bugs.", params[1].c_str(), x->server);
1147                                                         Instance->SNO->WriteToSnoMask('d', "WARNING: The server %s is sending nonstandard modes: '%s MODE %s' where FMODE should be used, and may cause desyncs.", x->server, x->nick, params[1].c_str());
1148                                                         warned[x->server] = x->nick;
1149                                                 }
1150                                         }
1151                                 }
1152                         }
1153
1154                         if (command == "SVSMODE")
1155                         {
1156                                 /* Services expects us to implement
1157                                  * SVSMODE. In inspircd its the same as
1158                                  * MODE anyway.
1159                                  */
1160                                 command = "MODE";
1161                         }
1162                         std::string target = "";
1163                         /* Yes, know, this is a mess. Its reasonably fast though as we're
1164                          * working with std::string here.
1165                          */
1166                         if ((command == "NICK") && (params.size() >= 8))
1167                         {
1168                                 return this->IntroduceClient(prefix,params);
1169                         }
1170                         else if (command == "FJOIN")
1171                         {
1172                                 TreeServer* ServerSource = Utils->FindServer(prefix);
1173                                 if (ServerSource)
1174                                         Utils->SetRemoteBursting(ServerSource, false);
1175                                 return this->ForceJoin(prefix,params);
1176                         }
1177                         else if (command == "STATS")
1178                         {
1179                                 return this->Stats(prefix, params);
1180                         }
1181                         else if (command == "MOTD")
1182                         {
1183                                 return this->Motd(prefix, params);
1184                         }
1185                         else if (command == "MODULES")
1186                         {
1187                                 return this->Modules(prefix, params);
1188                         }
1189                         else if (command == "ADMIN")
1190                         {
1191                                 return this->Admin(prefix, params);
1192                         }
1193                         else if (command == "SERVER")
1194                         {
1195                                 return this->RemoteServer(prefix,params);
1196                         }
1197                         else if (command == "ERROR")
1198                         {
1199                                 return this->Error(params);
1200                         }
1201                         else if (command == "OPERTYPE")
1202                         {
1203                                 return this->OperType(prefix,params);
1204                         }
1205                         else if (command == "FMODE")
1206                         {
1207                                 TreeServer* ServerSource = Utils->FindServer(prefix);
1208                                 if (ServerSource)
1209                                         Utils->SetRemoteBursting(ServerSource, false);
1210                                 return this->ForceMode(prefix,params);
1211                         }
1212                         else if (command == "FTOPIC")
1213                         {
1214                                 return this->ForceTopic(prefix,params);
1215                         }
1216                         else if (command == "REHASH")
1217                         {
1218                                 return this->RemoteRehash(prefix,params);
1219                         }
1220                         else if (command == "METADATA")
1221                         {
1222                                 return this->MetaData(prefix,params);
1223                         }
1224                         else if (command == "REMSTATUS")
1225                         {
1226                                 return this->RemoveStatus(prefix,params);
1227                         }
1228                         else if (command == "PING")
1229                         {
1230                                 if (prefix == "")
1231                                         prefix = this->GetName();
1232                                 /*
1233                                  * We just got a ping from a server that's bursting.
1234                                  * This can't be right, so set them to not bursting, and
1235                                  * apply their lines.
1236                                  */
1237                                 TreeServer* ServerSource = Utils->FindServer(prefix);
1238                                 if (ServerSource)
1239                                         Utils->SetRemoteBursting(ServerSource, false);
1240
1241                                 if (this->bursting)
1242                                 {
1243                                         this->bursting = false;
1244                                         Instance->XLines->apply_lines(Utils->lines_to_apply);
1245                                         Utils->lines_to_apply = 0;
1246                                 }
1247
1248                                 return this->LocalPing(prefix,params);
1249                         }
1250                         else if (command == "PONG")
1251                         {
1252                                 if (prefix == "")
1253                                         prefix = this->GetName();
1254                                 /*
1255                                  * We just got a pong from a server that's bursting.
1256                                  * This can't be right, so set them to not bursting, and
1257                                  * apply their lines.
1258                                  */
1259                                 TreeServer* ServerSource = Utils->FindServer(prefix);
1260                                 if (ServerSource)
1261                                         Utils->SetRemoteBursting(ServerSource, false);
1262
1263                                 if (this->bursting)
1264                                 {
1265                                         this->bursting = false;
1266                                         Instance->XLines->apply_lines(Utils->lines_to_apply);
1267                                         Utils->lines_to_apply = 0;
1268                                 }
1269
1270                                 return this->LocalPong(prefix,params);
1271                         }
1272                         else if (command == "VERSION")
1273                         {
1274                                 return this->ServerVersion(prefix,params);
1275                         }
1276                         else if (command == "FHOST")
1277                         {
1278                                 return this->ChangeHost(prefix,params);
1279                         }
1280                         else if (command == "FNAME")
1281                         {
1282                                 return this->ChangeName(prefix,params);
1283                         }
1284                         else if (command == "ADDLINE")
1285                         {
1286                                 TreeServer* ServerSource = Utils->FindServer(prefix);
1287                                 if (ServerSource)
1288                                         Utils->SetRemoteBursting(ServerSource, false);
1289                                 return this->AddLine(prefix,params);
1290                         }
1291                         else if (command == "SVSNICK")
1292                         {
1293                                 if (prefix == "")
1294                                 {
1295                                         prefix = this->GetName();
1296                                 }
1297                                 return this->ForceNick(prefix,params);
1298                         }
1299                         else if (command == "OPERQUIT")
1300                         {
1301                                 return this->OperQuit(prefix,params);
1302                         }
1303                         else if (command == "RSQUIT")
1304                         {
1305                                 return this->RemoteSquit(prefix, params);
1306                         }
1307                         else if (command == "IDLE")
1308                         {
1309                                 return this->Whois(prefix,params);
1310                         }
1311                         else if (command == "PUSH")
1312                         {
1313                                 return this->Push(prefix,params);
1314                         }
1315                         else if (command == "TIMESET")
1316                         {
1317                                 return this->HandleSetTime(prefix, params);
1318                         }
1319                         else if (command == "TIME")
1320                         {
1321                                 return this->Time(prefix,params);
1322                         }
1323                         else if ((command == "KICK") && (Utils->IsServer(prefix)))
1324                         {
1325                                 std::string sourceserv = this->myhost;
1326                                 if (params.size() == 3)
1327                                 {
1328                                         userrec* user = this->Instance->FindNick(params[1]);
1329                                         chanrec* chan = this->Instance->FindChan(params[0]);
1330                                         if (user && chan)
1331                                         {
1332                                                 if (!chan->ServerKickUser(user, params[2].c_str(), false))
1333                                                         /* Yikes, the channels gone! */
1334                                                         delete chan;
1335                                         }
1336                                 }
1337                                 if (this->InboundServerName != "")
1338                                 {
1339                                         sourceserv = this->InboundServerName;
1340                                 }
1341                                 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1342                         }
1343                         else if (command == "SVSJOIN")
1344                         {
1345                                 if (prefix == "")
1346                                 {
1347                                         prefix = this->GetName();
1348                                 }
1349                                 return this->ServiceJoin(prefix,params);
1350                         }
1351                         else if (command == "SQUIT")
1352                         {
1353                                 if (params.size() == 2)
1354                                 {
1355                                         this->Squit(Utils->FindServer(params[0]),params[1]);
1356                                 }
1357                                 return true;
1358                         }
1359                         else if (command == "OPERNOTICE")
1360                         {
1361                                 std::string sourceserv = this->myhost;
1362                                 if (this->InboundServerName != "")
1363                                         sourceserv = this->InboundServerName;
1364                                 if (params.size() >= 1)
1365                                         Instance->WriteOpers("*** From " + sourceserv + ": " + params[0]);
1366                                 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1367                         }
1368                         else if (command == "MODENOTICE")
1369                         {
1370                                 std::string sourceserv = this->myhost;
1371                                 if (this->InboundServerName != "")
1372                                         sourceserv = this->InboundServerName;
1373                                 if (params.size() >= 2)
1374                                 {
1375                                         Instance->WriteMode(params[0].c_str(), WM_AND, "*** From %s: %s", sourceserv.c_str(), params[1].c_str());
1376                                 }
1377                                 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1378                         }
1379                         else if (command == "SNONOTICE")
1380                         {
1381                                 std::string sourceserv = this->myhost;
1382                                 if (this->InboundServerName != "")
1383                                         sourceserv = this->InboundServerName;
1384                                 if (params.size() >= 2)
1385                                 {
1386                                         Instance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + sourceserv + ": "+ params[1]);
1387                                 }
1388                                 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1389                         }
1390                         else if (command == "ENDBURST")
1391                         {
1392                                 this->bursting = false;
1393                                 Instance->XLines->apply_lines(Utils->lines_to_apply);
1394                                 Utils->lines_to_apply = 0;
1395                                 std::string sourceserv = this->myhost;
1396                                 if (this->InboundServerName != "")
1397                                 {
1398                                         sourceserv = this->InboundServerName;
1399                                 }
1400                                 this->Instance->SNO->WriteToSnoMask('l',"Received end of netburst from \2%s\2",sourceserv.c_str());
1401
1402                                 Event rmode((char*)sourceserv.c_str(), (Module*)Utils->Creator, "new_server");
1403                                 rmode.Send(Instance);
1404
1405                                 return true;
1406                         }
1407                         else
1408                         {
1409                                 // not a special inter-server command.
1410                                 // Emulate the actual user doing the command,
1411                                 // this saves us having a huge ugly parser.
1412                                 userrec* who = this->Instance->FindNick(prefix);
1413                                 std::string sourceserv = this->myhost;
1414                                 if (this->InboundServerName != "")
1415                                 {
1416                                         sourceserv = this->InboundServerName;
1417                                 }
1418                                 if ((!who) && (command == "MODE"))
1419                                 {
1420                                         if (Utils->IsServer(prefix))
1421                                         {
1422                                                 const char* modelist[127];
1423                                                 for (size_t i = 0; i < params.size(); i++)
1424                                                         modelist[i] = params[i].c_str();
1425                                                 userrec* fake = new userrec(Instance);
1426                                                 fake->SetFd(FD_MAGIC_NUMBER);
1427                                                 this->Instance->SendMode(modelist, params.size(), fake);
1428
1429                                                 delete fake;
1430                                                 /* Hot potato! pass it on! */
1431                                                 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1432                                         }
1433                                 }
1434                                 if (who)
1435                                 {
1436                                         if ((command == "NICK") && (params.size() > 0))
1437                                         {
1438                                                 /* On nick messages, check that the nick doesnt
1439                                                  * already exist here. If it does, kill their copy,
1440                                                  * and our copy.
1441                                                  */
1442                                                 userrec* x = this->Instance->FindNick(params[0]);
1443                                                 if ((x) && (x != who))
1444                                                 {
1445                                                         std::deque<std::string> p;
1446                                                         p.push_back(params[0]);
1447                                                         p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
1448                                                         Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
1449                                                         p.clear();
1450                                                         p.push_back(prefix);
1451                                                         p.push_back("Nickname collision");
1452                                                         Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
1453                                                         userrec::QuitUser(this->Instance,x,"Nickname collision ("+prefix+" -> "+params[0]+")");
1454                                                         userrec* y = this->Instance->FindNick(prefix);
1455                                                         if (y)
1456                                                         {
1457                                                                 userrec::QuitUser(this->Instance,y,"Nickname collision");
1458                                                         }
1459                                                         return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1460                                                 }
1461                                         }
1462                                         // its a user
1463                                         target = who->server;
1464                                         const char* strparams[127];
1465                                         for (unsigned int q = 0; q < params.size(); q++)
1466                                         {
1467                                                 strparams[q] = params[q].c_str();
1468                                         }
1469                                         switch (this->Instance->CallCommandHandler(command.c_str(), strparams, params.size(), who))
1470                                         {
1471                                                 case CMD_INVALID:
1472                                                         this->SendError("Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
1473                                                         return false;
1474                                                 break;
1475                                                 case CMD_FAILURE:
1476                                                         return true;
1477                                                 break;
1478                                                 default:
1479                                                         /* CMD_SUCCESS and CMD_USER_DELETED fall through here */
1480                                                 break;
1481                                         }
1482                                 }
1483                                 else
1484                                 {
1485                                         // its not a user. Its either a server, or somethings screwed up.
1486                                         if (Utils->IsServer(prefix))
1487                                                 target = this->Instance->Config->ServerName;
1488                                         else
1489                                                 return true;
1490                                 }
1491                                 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1492
1493                         }
1494                         return true;
1495                 break;
1496         }
1497         return true;
1498 }
1499
1500 std::string TreeSocket::GetName()
1501 {
1502         std::string sourceserv = this->myhost;
1503         if (this->InboundServerName != "")
1504         {
1505                 sourceserv = this->InboundServerName;
1506         }
1507         return sourceserv;
1508 }
1509
1510 void TreeSocket::OnTimeout()
1511 {
1512         if (this->LinkState == CONNECTING)
1513         {
1514                 this->Instance->SNO->WriteToSnoMask('l',"CONNECT: Connection to \002"+myhost+"\002 timed out.");
1515                 Link* MyLink = Utils->FindLink(myhost);
1516                 if (MyLink)
1517                         Utils->DoFailOver(MyLink);
1518         }
1519 }
1520
1521 void TreeSocket::OnClose()
1522 {
1523         // Connection closed.
1524         // If the connection is fully up (state CONNECTED)
1525         // then propogate a netsplit to all peers.
1526         std::string quitserver = this->myhost;
1527         if (this->InboundServerName != "")
1528         {
1529                 quitserver = this->InboundServerName;
1530         }
1531         TreeServer* s = Utils->FindServer(quitserver);
1532         if (s)
1533         {
1534                 Squit(s,"Remote host closed the connection");
1535         }
1536
1537         if (quitserver != "")
1538         {
1539                 this->Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' failed.",quitserver.c_str());
1540                 time_t server_uptime = Instance->Time() - this->age;    
1541                 if (server_uptime)
1542                         Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' was established for %s", quitserver.c_str(), Utils->Creator->TimeToStr(server_uptime).c_str());
1543         }
1544 }
1545
1546 int TreeSocket::OnIncomingConnection(int newsock, char* ip)
1547 {
1548         /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
1549          * or discovering if this port is the server port, we don't allow connections from any
1550          * IPs for which we don't have a link block.
1551          */
1552         bool found = false;
1553
1554         found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), ip) != Utils->ValidIPs.end());
1555         if (!found)
1556         {
1557                 for (vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
1558                         if (irc::sockets::MatchCIDR(ip, (*i).c_str()))
1559                                 found = true;
1560
1561                 if (!found)
1562                 {
1563                         this->Instance->SNO->WriteToSnoMask('l',"Server connection from %s denied (no link blocks with that IP address)", ip);
1564                         close(newsock);
1565                         return false;
1566                 }
1567         }
1568
1569         TreeSocket* s = new TreeSocket(this->Utils, this->Instance, newsock, ip, this->Hook);
1570         s = s; /* Whinge whinge whinge, thats all GCC ever does. */
1571         return true;
1572 }