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