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