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