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