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