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