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