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