]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/treesocket2.cpp
2172940216149fbeef60add7967631092f7f3f2d
[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                         time_t c_requires_crap = ConvToInt(params[4]) + Instance->Time();
547                         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());
548                 }
549                 else
550                 {
551                         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());
552                 }
553                 params[5] = ":" + params[5];
554                 Utils->DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
555         }
556         if (!this->bursting)
557         {
558                 Instance->XLines->apply_lines(Utils->lines_to_apply);
559                 Utils->lines_to_apply = 0;
560         }
561         return true;
562 }
563
564 bool TreeSocket::ChangeName(const std::string &prefix, std::deque<std::string> &params)
565 {
566         if (params.size() < 1)
567                 return true;
568         userrec* u = this->Instance->FindNick(prefix);
569         if (u)
570         {
571                 u->ChangeName(params[0].c_str());
572                 params[0] = ":" + params[0];
573                 Utils->DoOneToAllButSender(prefix,"FNAME",params,u->server);
574         }
575         return true;
576 }
577
578 bool TreeSocket::Whois(const std::string &prefix, std::deque<std::string> &params)
579 {
580         if (params.size() < 1)
581                 return true;
582         userrec* u = this->Instance->FindNick(prefix);
583         if (u)
584         {
585                 // an incoming request
586                 if (params.size() == 1)
587                 {
588                         userrec* x = this->Instance->FindNick(params[0]);
589                         if ((x) && (IS_LOCAL(x)))
590                         {
591                                 userrec* x = this->Instance->FindNick(params[0]);
592                                 char signon[MAXBUF];
593                                 char idle[MAXBUF];
594                                 snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
595                                 snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-Instance->Time(true)));
596                                 std::deque<std::string> par;
597                                 par.push_back(prefix);
598                                 par.push_back(signon);
599                                 par.push_back(idle);
600                                 // ours, we're done, pass it BACK
601                                 Utils->DoOneToOne(params[0],"IDLE",par,u->server);
602                         }
603                         else
604                         {
605                                 // not ours pass it on
606                                 Utils->DoOneToOne(prefix,"IDLE",params,x->server);
607                         }
608                 }
609                 else if (params.size() == 3)
610                 {
611                         std::string who_did_the_whois = params[0];
612                         userrec* who_to_send_to = this->Instance->FindNick(who_did_the_whois);
613                         if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
614                         {
615                                 // an incoming reply to a whois we sent out
616                                 std::string nick_whoised = prefix;
617                                 unsigned long signon = atoi(params[1].c_str());
618                                 unsigned long idle = atoi(params[2].c_str());
619                                 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
620                                         do_whois(this->Instance,who_to_send_to,u,signon,idle,nick_whoised.c_str());
621                         }
622                         else
623                         {
624                                 // not ours, pass it on
625                                 Utils->DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
626                         }
627                 }
628         }
629         return true;
630 }
631
632 bool TreeSocket::Push(const std::string &prefix, std::deque<std::string> &params)
633 {
634         if (params.size() < 2)
635                 return true;
636         userrec* u = this->Instance->FindNick(params[0]);
637         if (!u)
638                 return true;
639         if (IS_LOCAL(u))
640         {
641                 u->Write(params[1]);
642         }
643         else
644         {
645                 // continue the raw onwards
646                 params[1] = ":" + params[1];
647                 Utils->DoOneToOne(prefix,"PUSH",params,u->server);
648         }
649         return true;
650 }
651
652 bool TreeSocket::HandleSetTime(const std::string &prefix, std::deque<std::string> &params)
653 {
654         if (!params.size() || !Utils->EnableTimeSync)
655                 return true;
656
657         bool force = false;
658
659         if ((params.size() == 2) && (params[1] == "FORCE"))
660                 force = true;
661
662         time_t them = atoi(params[0].c_str());
663         time_t us = Instance->Time(false);
664
665         time_t diff = them - us;
666
667         Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
668
669         if (force || (them != us))
670         {
671                 time_t old = Instance->SetTimeDelta(diff);
672                 Instance->Log(DEBUG, "TS (diff %d) from %s applied (old delta was %d)", diff, prefix.c_str(), old);
673         }
674
675         return true;
676 }
677
678 bool TreeSocket::Time(const std::string &prefix, std::deque<std::string> &params)
679 {
680         // :source.server TIME remote.server sendernick
681         // :remote.server TIME source.server sendernick TS
682         if (params.size() == 2)
683         {
684                 // someone querying our time?
685                 if (this->Instance->Config->ServerName == params[0])
686                 {
687                         userrec* u = this->Instance->FindNick(params[1]);
688                         if (u)
689                         {
690                                 params.push_back(ConvToStr(Instance->Time(false)));
691                                 params[0] = prefix;
692                                 Utils->DoOneToOne(this->Instance->Config->ServerName,"TIME",params,params[0]);
693                         }
694                 }
695                 else
696                 {
697                         // not us, pass it on
698                         userrec* u = this->Instance->FindNick(params[1]);
699                         if (u)
700                                 Utils->DoOneToOne(prefix,"TIME",params,params[0]);
701                 }
702         }
703         else if (params.size() == 3)
704         {
705                 // a response to a previous TIME
706                 userrec* u = this->Instance->FindNick(params[1]);
707                 if ((u) && (IS_LOCAL(u)))
708                 {
709                         time_t rawtime = atol(params[2].c_str());
710                         struct tm * timeinfo;
711                         timeinfo = localtime(&rawtime);
712                         char tms[26];
713                         snprintf(tms,26,"%s",asctime(timeinfo));
714                         tms[24] = 0;
715                         u->WriteServ("391 %s %s :%s",u->nick,prefix.c_str(),tms);
716                 }
717                 else
718                 {
719                         if (u)
720                                 Utils->DoOneToOne(prefix,"TIME",params,u->server);
721                 }
722         }
723         return true;
724 }
725
726 bool TreeSocket::LocalPing(const std::string &prefix, std::deque<std::string> &params)
727 {
728         if (params.size() < 1)
729                 return true;
730         if (params.size() == 1)
731         {
732                 std::string stufftobounce = params[0];
733                 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" PONG "+stufftobounce);
734                 return true;
735         }
736         else
737         {
738                 std::string forwardto = params[1];
739                 if (forwardto == this->Instance->Config->ServerName)
740                 {
741                         // this is a ping for us, send back PONG to the requesting server
742                         params[1] = params[0];
743                         params[0] = forwardto;
744                         Utils->DoOneToOne(forwardto,"PONG",params,params[1]);
745                 }
746                 else
747                 {
748                         // not for us, pass it on :)
749                         Utils->DoOneToOne(prefix,"PING",params,forwardto);
750                 }
751                 return true;
752         }
753 }
754
755 /** TODO: This creates a total mess of output and needs to really use irc::modestacker.
756  */
757 bool TreeSocket::RemoveStatus(const std::string &prefix, std::deque<std::string> &params)
758 {
759         if (params.size() < 1)
760                 return true;
761         chanrec* c = Instance->FindChan(params[0]);
762         if (c)
763         {
764                 for (char modeletter = 'A'; modeletter <= 'z'; modeletter++)
765                 {
766                         ModeHandler* mh = Instance->Modes->FindMode(modeletter, MODETYPE_CHANNEL);
767                         if (mh)
768                                 mh->RemoveMode(c);
769                 }
770         }
771         return true;
772 }
773
774 bool TreeSocket::RemoteServer(const std::string &prefix, std::deque<std::string> &params)
775 {
776         if (params.size() < 4)
777                 return false;
778         std::string servername = params[0];
779         std::string password = params[1];
780         // hopcount is not used for a remote server, we calculate this ourselves
781         std::string description = params[3];
782         TreeServer* ParentOfThis = Utils->FindServer(prefix);
783         if (!ParentOfThis)
784         {
785                 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
786                 return false;
787         }
788         TreeServer* CheckDupe = Utils->FindServer(servername);
789         if (CheckDupe)
790         {
791                 this->WriteLine("ERROR :Server "+servername+" already exists!");
792                 this->Instance->SNO->WriteToSnoMask('l',"Server \2"+servername+"\2 being introduced from \2" + prefix + "\2 denied, already exists. Closing link with " + prefix);
793                 return false;
794         }
795         Link* lnk = Utils->FindLink(servername);
796         TreeServer* Node = new TreeServer(this->Utils,this->Instance,servername,description,ParentOfThis,NULL, lnk ? lnk->Hidden : false);
797         ParentOfThis->AddChild(Node);
798         params[3] = ":" + params[3];
799         Utils->DoOneToAllButSender(prefix,"SERVER",params,prefix);
800         this->Instance->SNO->WriteToSnoMask('l',"Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
801         return true;
802 }
803
804 bool TreeSocket::Outbound_Reply_Server(std::deque<std::string> &params)
805 {
806         if (params.size() < 4)
807                 return false;
808
809         irc::string servername = params[0].c_str();
810         std::string sname = params[0];
811         std::string password = params[1];
812         int hops = atoi(params[2].c_str());
813
814         if (hops)
815         {
816                 this->WriteLine("ERROR :Server too far away for authentication");
817                 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
818                 return false;
819         }
820         std::string description = params[3];
821         for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
822         {
823                 if ((x->Name == servername) && (x->RecvPass == password))
824                 {
825                         TreeServer* CheckDupe = Utils->FindServer(sname);
826                         if (CheckDupe)
827                         {
828                                 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
829                                 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
830                                 return false;
831                         }
832                         // Begin the sync here. this kickstarts the
833                         // other side, waiting in WAIT_AUTH_2 state,
834                         // into starting their burst, as it shows
835                         // that we're happy.
836                         this->LinkState = CONNECTED;
837                         // we should add the details of this server now
838                         // to the servers tree, as a child of the root
839                         // node.
840                         TreeServer* Node = new TreeServer(this->Utils,this->Instance,sname,description,Utils->TreeRoot,this,x->Hidden);
841                         Utils->TreeRoot->AddChild(Node);
842                         params[3] = ":" + params[3];
843                         Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,sname);
844                         this->bursting = true;
845                         this->DoBurst(Node);
846                         return true;
847                 }
848         }
849         this->WriteLine("ERROR :Invalid credentials");
850         this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
851         return false;
852 }
853
854 bool TreeSocket::Inbound_Server(std::deque<std::string> &params)
855 {
856         if (params.size() < 4)
857                 return false;
858         irc::string servername = params[0].c_str();
859         std::string sname = params[0];
860         std::string password = params[1];
861         int hops = atoi(params[2].c_str());
862
863         if (hops)
864         {
865                 this->WriteLine("ERROR :Server too far away for authentication");
866                 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
867                 return false;
868         }
869         std::string description = params[3];
870         for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
871         {
872                 if ((x->Name == servername) && (x->RecvPass == password))
873                 {
874                         TreeServer* CheckDupe = Utils->FindServer(sname);
875                         if (CheckDupe)
876                         {
877                                 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
878                                 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
879                                 return false;
880                         }
881                         this->Instance->SNO->WriteToSnoMask('l',"Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
882                         if (this->Hook)
883                         {
884                                 std::string name = InspSocketNameRequest((Module*)Utils->Creator, this->Hook).Send();
885                                 this->Instance->SNO->WriteToSnoMask('l',"Connection from \2"+sname+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] using transport \2"+name+"\2");
886                         }
887
888                         this->InboundServerName = sname;
889                         this->InboundDescription = description;
890                         // this is good. Send our details: Our server name and description and hopcount of 0,
891                         // along with the sendpass from this block.
892                         this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+x->SendPass+" 0 :"+this->Instance->Config->ServerDesc);
893                         // move to the next state, we are now waiting for THEM.
894                         this->LinkState = WAIT_AUTH_2;
895                         return true;
896                 }
897         }
898         this->WriteLine("ERROR :Invalid credentials");
899         this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
900         return false;
901 }
902
903 void TreeSocket::Split(const std::string &line, std::deque<std::string> &n)
904 {
905         n.clear();
906         irc::tokenstream tokens(line);
907         std::string param;
908         while (tokens.GetToken(param))
909                 n.push_back(param);
910         return;
911 }
912
913 bool TreeSocket::ProcessLine(std::string &line)
914 {
915         std::deque<std::string> params;
916         irc::string command;
917         std::string prefix;
918
919         line = line.substr(0, line.find_first_of("\r\n"));
920
921         if (line.empty())
922                 return true;
923
924         Instance->Log(DEBUG, "<- %s", line.c_str());
925
926         this->Split(line.c_str(),params);
927
928         if ((params[0][0] == ':') && (params.size() > 1))
929         {
930                 prefix = params[0].substr(1);
931                 params.pop_front();
932         }
933         command = params[0].c_str();
934         params.pop_front();
935         switch (this->LinkState)
936         {
937                 TreeServer* Node;
938
939                 case WAIT_AUTH_1:
940                         // Waiting for SERVER command from remote server. Server initiating
941                         // the connection sends the first SERVER command, listening server
942                         // replies with theirs if its happy, then if the initiator is happy,
943                         // it starts to send its net sync, which starts the merge, otherwise
944                         // it sends an ERROR.
945                         if (command == "PASS")
946                         {
947                                 /* Silently ignored */
948                         }
949                         else if (command == "SERVER")
950                         {
951                                 return this->Inbound_Server(params);
952                         }
953                         else if (command == "ERROR")
954                         {
955                                 return this->Error(params);
956                         }
957                         else if (command == "USER")
958                         {
959                                 this->WriteLine("ERROR :Client connections to this port are prohibited.");
960                                 return false;
961                         }
962                         else if (command == "CAPAB")
963                         {
964                                 return this->Capab(params);
965                         }
966                         else if ((command == "U") || (command == "S"))
967                         {
968                                 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
969                                 return false;
970                         }
971                         else
972                         {
973                                 std::string error("ERROR :Invalid command in negotiation phase: ");
974                                 error.append(command.c_str());
975                                 this->WriteLine(error);
976                                 return false;
977                         }
978                 break;
979                 case WAIT_AUTH_2:
980                         // Waiting for start of other side's netmerge to say they liked our
981                         // password.
982                         if (command == "SERVER")
983                         {
984                                 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
985                                 // silently ignore.
986                                 return true;
987                         }
988                         else if ((command == "U") || (command == "S"))
989                         {
990                                 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
991                                 return false;
992                         }
993                         else if (command == "BURST")
994                         {
995                                 if (params.size() && Utils->EnableTimeSync)
996                                 {
997                                         bool we_have_delta = (Instance->Time(false) != Instance->Time(true));
998                                         time_t them = atoi(params[0].c_str());
999                                         time_t delta = them - Instance->Time(false);
1000                                         if ((delta < -300) || (delta > 300))
1001                                         {
1002                                                 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));
1003                                                 WriteLine("ERROR :Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than ten minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
1004                                                 return false;
1005                                         }
1006                                         else if ((delta < -30) || (delta > 30))
1007                                         {
1008                                                 Instance->SNO->WriteToSnoMask('l',"\2WARNING\2: Your clocks are out by %d seconds. Please consider synching your clocks.", abs(delta));
1009                                         }
1010
1011                                         if (!Utils->MasterTime && !we_have_delta)
1012                                         {
1013                                                 this->Instance->SetTimeDelta(delta);
1014                                                 // Send this new timestamp to any other servers
1015                                                 Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
1016                                         }
1017                                 }
1018                                 this->LinkState = CONNECTED;
1019                                 Link* lnk = Utils->FindLink(InboundServerName);
1020                                 Node = new TreeServer(this->Utils,this->Instance, InboundServerName, InboundDescription, Utils->TreeRoot, this, lnk ? lnk->Hidden : false);
1021                                 Utils->TreeRoot->AddChild(Node);
1022                                 params.clear();
1023                                 params.push_back(InboundServerName);
1024                                 params.push_back("*");
1025                                 params.push_back("1");
1026                                 params.push_back(":"+InboundDescription);
1027                                 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,InboundServerName);
1028                                 this->bursting = true;
1029                                 this->DoBurst(Node);
1030                         }
1031                         else if (command == "ERROR")
1032                         {
1033                                 return this->Error(params);
1034                         }
1035                         else if (command == "CAPAB")
1036                         {
1037                                 return this->Capab(params);
1038                         }
1039
1040                 break;
1041                 case LISTENER:
1042                         this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
1043                         return false;
1044                 break;
1045                 case CONNECTING:
1046                         if (command == "SERVER")
1047                         {
1048                                 // another server we connected to, which was in WAIT_AUTH_1 state,
1049                                 // has just sent us their credentials. If we get this far, theyre
1050                                 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1051                                 // if we're happy with this, we should send our netburst which
1052                                 // kickstarts the merge.
1053                                 return this->Outbound_Reply_Server(params);
1054                         }
1055                         else if (command == "ERROR")
1056                         {
1057                                 return this->Error(params);
1058                         }
1059                 break;
1060                 case CONNECTED:
1061                         // This is the 'authenticated' state, when all passwords
1062                         // have been exchanged and anything past this point is taken
1063                         // as gospel.
1064
1065                         if (prefix != "")
1066                         {
1067                                 std::string direction = prefix;
1068                                 userrec* t = this->Instance->FindNick(prefix);
1069                                 if (t)
1070                                 {
1071                                         direction = t->server;
1072                                 }
1073                                 TreeServer* route_back_again = Utils->BestRouteTo(direction);
1074                                 if ((!route_back_again) || (route_back_again->GetSocket() != this))
1075                                 {
1076                                         if (route_back_again)
1077                                                 Instance->Log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
1078                                         return true;
1079                                 }
1080                                 /* Fix by brain:
1081                                  * When there is activity on the socket, reset the ping counter so
1082                                  * that we're not wasting bandwidth pinging an active server.
1083                                  */
1084                                 route_back_again->SetNextPingTime(time(NULL) + 60);
1085                                 route_back_again->SetPingFlag();
1086                         }
1087
1088                         if (command == "SVSMODE")
1089                         {
1090                                 /* Services expects us to implement
1091                                  * SVSMODE. In inspircd its the same as
1092                                  * MODE anyway.
1093                                  */
1094                                 command = "MODE";
1095                         }
1096                         std::string target = "";
1097                         /* Yes, know, this is a mess. Its reasonably fast though as we're
1098                          * working with std::string here.
1099                          */
1100                         if ((command == "NICK") && (params.size() >= 8))
1101                         {
1102                                 return this->IntroduceClient(prefix,params);
1103                         }
1104                         else if (command == "FJOIN")
1105                         {
1106                                 return this->ForceJoin(prefix,params);
1107                         }
1108                         else if (command == "STATS")
1109                         {
1110                                 return this->Stats(prefix, params);
1111                         }
1112                         else if (command == "MOTD")
1113                         {
1114                                 return this->Motd(prefix, params);
1115                         }
1116                         else if (command == "MODULES")
1117                         {
1118                                 return this->Modules(prefix, params);
1119                         }
1120                         else if (command == "ADMIN")
1121                         {
1122                                 return this->Admin(prefix, params);
1123                         }
1124                         else if (command == "SERVER")
1125                         {
1126                                 return this->RemoteServer(prefix,params);
1127                         }
1128                         else if (command == "ERROR")
1129                         {
1130                                 return this->Error(params);
1131                         }
1132                         else if (command == "OPERTYPE")
1133                         {
1134                                 return this->OperType(prefix,params);
1135                         }
1136                         else if (command == "FMODE")
1137                         {
1138                                 return this->ForceMode(prefix,params);
1139                         }
1140                         else if (command == "KILL")
1141                         {
1142                                 return this->RemoteKill(prefix,params);
1143                         }
1144                         else if (command == "FTOPIC")
1145                         {
1146                                 return this->ForceTopic(prefix,params);
1147                         }
1148                         else if (command == "REHASH")
1149                         {
1150                                 return this->RemoteRehash(prefix,params);
1151                         }
1152                         else if (command == "METADATA")
1153                         {
1154                                 return this->MetaData(prefix,params);
1155                         }
1156                         else if (command == "REMSTATUS")
1157                         {
1158                                 return this->RemoveStatus(prefix,params);
1159                         }
1160                         else if (command == "PING")
1161                         {
1162                                 /*
1163                                  * We just got a ping from a server that's bursting.
1164                                  * This can't be right, so set them to not bursting, and
1165                                  * apply their lines.
1166                                  */
1167                                 if (this->bursting)
1168                                 {
1169                                         this->bursting = false;
1170                                         Instance->XLines->apply_lines(Utils->lines_to_apply);
1171                                         Utils->lines_to_apply = 0;
1172                                 }
1173                                 if (prefix == "")
1174                                 {
1175                                         prefix = this->GetName();
1176                                 }
1177                                 return this->LocalPing(prefix,params);
1178                         }
1179                         else if (command == "PONG")
1180                         {
1181                                 /*
1182                                  * We just got a pong from a server that's bursting.
1183                                  * This can't be right, so set them to not bursting, and
1184                                  * apply their lines.
1185                                  */
1186                                 if (this->bursting)
1187                                 {
1188                                         this->bursting = false;
1189                                         Instance->XLines->apply_lines(Utils->lines_to_apply);
1190                                         Utils->lines_to_apply = 0;
1191                                 }
1192                                 if (prefix == "")
1193                                 {
1194                                         prefix = this->GetName();
1195                                 }
1196                                 return this->LocalPong(prefix,params);
1197                         }
1198                         else if (command == "VERSION")
1199                         {
1200                                 return this->ServerVersion(prefix,params);
1201                         }
1202                         else if (command == "FHOST")
1203                         {
1204                                 return this->ChangeHost(prefix,params);
1205                         }
1206                         else if (command == "FNAME")
1207                         {
1208                                 return this->ChangeName(prefix,params);
1209                         }
1210                         else if (command == "ADDLINE")
1211                         {
1212                                 return this->AddLine(prefix,params);
1213                         }
1214                         else if (command == "SVSNICK")
1215                         {
1216                                 if (prefix == "")
1217                                 {
1218                                         prefix = this->GetName();
1219                                 }
1220                                 return this->ForceNick(prefix,params);
1221                         }
1222                         else if (command == "OPERQUIT")
1223                         {
1224                                 return this->OperQuit(prefix,params);
1225                         }
1226                         else if (command == "RSQUIT")
1227                         {
1228                                 return this->RemoteSquit(prefix, params);
1229                         }
1230                         else if (command == "IDLE")
1231                         {
1232                                 return this->Whois(prefix,params);
1233                         }
1234                         else if (command == "PUSH")
1235                         {
1236                                 return this->Push(prefix,params);
1237                         }
1238                         else if (command == "TIMESET")
1239                         {
1240                                 return this->HandleSetTime(prefix, params);
1241                         }
1242                         else if (command == "TIME")
1243                         {
1244                                 return this->Time(prefix,params);
1245                         }
1246                         else if ((command == "KICK") && (Utils->IsServer(prefix)))
1247                         {
1248                                 std::string sourceserv = this->myhost;
1249                                 if (params.size() == 3)
1250                                 {
1251                                         userrec* user = this->Instance->FindNick(params[1]);
1252                                         chanrec* chan = this->Instance->FindChan(params[0]);
1253                                         if (user && chan)
1254                                         {
1255                                                 if (!chan->ServerKickUser(user, params[2].c_str(), false))
1256                                                         /* Yikes, the channels gone! */
1257                                                         delete chan;
1258                                         }
1259                                 }
1260                                 if (this->InboundServerName != "")
1261                                 {
1262                                         sourceserv = this->InboundServerName;
1263                                 }
1264                                 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1265                         }
1266                         else if (command == "SVSJOIN")
1267                         {
1268                                 if (prefix == "")
1269                                 {
1270                                         prefix = this->GetName();
1271                                 }
1272                                 return this->ServiceJoin(prefix,params);
1273                         }
1274                         else if (command == "SQUIT")
1275                         {
1276                                 if (params.size() == 2)
1277                                 {
1278                                         this->Squit(Utils->FindServer(params[0]),params[1]);
1279                                 }
1280                                 return true;
1281                         }
1282                         else if (command == "OPERNOTICE")
1283                         {
1284                                 std::string sourceserv = this->myhost;
1285                                 if (this->InboundServerName != "")
1286                                         sourceserv = this->InboundServerName;
1287                                 if (params.size() >= 1)
1288                                         Instance->WriteOpers("*** From " + sourceserv + ": " + params[0]);
1289                                 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1290                         }
1291                         else if (command == "MODENOTICE")
1292                         {
1293                                 std::string sourceserv = this->myhost;
1294                                 if (this->InboundServerName != "")
1295                                         sourceserv = this->InboundServerName;
1296                                 if (params.size() >= 2)
1297                                 {
1298                                         Instance->WriteMode(params[0].c_str(), WM_AND, "*** From %s: %s", sourceserv.c_str(), params[1].c_str());
1299                                 }
1300                                 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1301                         }
1302                         else if (command == "SNONOTICE")
1303                         {
1304                                 std::string sourceserv = this->myhost;
1305                                 if (this->InboundServerName != "")
1306                                         sourceserv = this->InboundServerName;
1307                                 if (params.size() >= 2)
1308                                 {
1309                                         Instance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + sourceserv + ": "+ params[1]);
1310                                 }
1311                                 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1312                         }
1313                         else if (command == "ENDBURST")
1314                         {
1315                                 this->bursting = false;
1316                                 Instance->XLines->apply_lines(Utils->lines_to_apply);
1317                                 Utils->lines_to_apply = 0;
1318                                 std::string sourceserv = this->myhost;
1319                                 if (this->InboundServerName != "")
1320                                 {
1321                                         sourceserv = this->InboundServerName;
1322                                 }
1323                                 this->Instance->SNO->WriteToSnoMask('l',"Received end of netburst from \2%s\2",sourceserv.c_str());
1324
1325                                 Event rmode((char*)sourceserv.c_str(), (Module*)Utils->Creator, "new_server");
1326                                 rmode.Send(Instance);
1327
1328                                 return true;
1329                         }
1330                         else
1331                         {
1332                                 // not a special inter-server command.
1333                                 // Emulate the actual user doing the command,
1334                                 // this saves us having a huge ugly parser.
1335                                 userrec* who = this->Instance->FindNick(prefix);
1336                                 std::string sourceserv = this->myhost;
1337                                 if (this->InboundServerName != "")
1338                                 {
1339                                         sourceserv = this->InboundServerName;
1340                                 }
1341                                 if ((!who) && (command == "MODE"))
1342                                 {
1343                                         if (Utils->IsServer(prefix))
1344                                         {
1345                                                 const char* modelist[127];
1346                                                 for (size_t i = 0; i < params.size(); i++)
1347                                                         modelist[i] = params[i].c_str();
1348                                                 userrec* fake = new userrec(Instance);
1349                                                 fake->SetFd(FD_MAGIC_NUMBER);
1350                                                 this->Instance->SendMode(modelist, params.size(), fake);
1351
1352                                                 delete fake;
1353                                                 /* Hot potato! pass it on! */
1354                                                 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1355                                         }
1356                                 }
1357                                 if (who)
1358                                 {
1359                                         if ((command == "NICK") && (params.size() > 0))
1360                                         {
1361                                                 /* On nick messages, check that the nick doesnt
1362                                                  * already exist here. If it does, kill their copy,
1363                                                  * and our copy.
1364                                                  */
1365                                                 userrec* x = this->Instance->FindNick(params[0]);
1366                                                 if ((x) && (x != who))
1367                                                 {
1368                                                         std::deque<std::string> p;
1369                                                         p.push_back(params[0]);
1370                                                         p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
1371                                                         Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
1372                                                         p.clear();
1373                                                         p.push_back(prefix);
1374                                                         p.push_back("Nickname collision");
1375                                                         Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
1376                                                         userrec::QuitUser(this->Instance,x,"Nickname collision ("+prefix+" -> "+params[0]+")");
1377                                                         userrec* y = this->Instance->FindNick(prefix);
1378                                                         if (y)
1379                                                         {
1380                                                                 userrec::QuitUser(this->Instance,y,"Nickname collision");
1381                                                         }
1382                                                         return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1383                                                 }
1384                                         }
1385                                         // its a user
1386                                         target = who->server;
1387                                         const char* strparams[127];
1388                                         for (unsigned int q = 0; q < params.size(); q++)
1389                                         {
1390                                                 strparams[q] = params[q].c_str();
1391                                         }
1392                                         switch (this->Instance->CallCommandHandler(command.c_str(), strparams, params.size(), who))
1393                                         {
1394                                                 case CMD_INVALID:
1395                                                         this->WriteLine("ERROR :Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
1396                                                         return false;
1397                                                 break;
1398                                                 case CMD_FAILURE:
1399                                                         return true;
1400                                                 break;
1401                                                 default:
1402                                                         /* CMD_SUCCESS and CMD_USER_DELETED fall through here */
1403                                                 break;
1404                                         }
1405                                 }
1406                                 else
1407                                 {
1408                                         // its not a user. Its either a server, or somethings screwed up.
1409                                         if (Utils->IsServer(prefix))
1410                                                 target = this->Instance->Config->ServerName;
1411                                         else
1412                                                 return true;
1413                                 }
1414                                 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1415
1416                         }
1417                         return true;
1418                 break;
1419         }
1420         return true;
1421 }
1422
1423 std::string TreeSocket::GetName()
1424 {
1425         std::string sourceserv = this->myhost;
1426         if (this->InboundServerName != "")
1427         {
1428                 sourceserv = this->InboundServerName;
1429         }
1430         return sourceserv;
1431 }
1432
1433 void TreeSocket::OnTimeout()
1434 {
1435         if (this->LinkState == CONNECTING)
1436         {
1437                 this->Instance->SNO->WriteToSnoMask('l',"CONNECT: Connection to \002"+myhost+"\002 timed out.");
1438                 Link* MyLink = Utils->FindLink(myhost);
1439                 if (MyLink)
1440                         Utils->DoFailOver(MyLink);
1441         }
1442 }
1443
1444 void TreeSocket::OnClose()
1445 {
1446         // Connection closed.
1447         // If the connection is fully up (state CONNECTED)
1448         // then propogate a netsplit to all peers.
1449         std::string quitserver = this->myhost;
1450         if (this->InboundServerName != "")
1451         {
1452                 quitserver = this->InboundServerName;
1453         }
1454         TreeServer* s = Utils->FindServer(quitserver);
1455         if (s)
1456         {
1457                 Squit(s,"Remote host closed the connection");
1458         }
1459
1460         if (quitserver != "")
1461                 this->Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' failed.",quitserver.c_str());
1462 }
1463
1464 int TreeSocket::OnIncomingConnection(int newsock, char* ip)
1465 {
1466         /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
1467          * or discovering if this port is the server port, we don't allow connections from any
1468          * IPs for which we don't have a link block.
1469          */
1470         bool found = false;
1471
1472         found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), ip) != Utils->ValidIPs.end());
1473         if (!found)
1474         {
1475                 for (vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
1476                         if (irc::sockets::MatchCIDR(ip, (*i).c_str()))
1477                                 found = true;
1478
1479                 if (!found)
1480                 {
1481                         this->Instance->SNO->WriteToSnoMask('l',"Server connection from %s denied (no link blocks with that IP address)", ip);
1482                         close(newsock);
1483                         return false;
1484                 }
1485         }
1486
1487         TreeSocket* s = new TreeSocket(this->Utils, this->Instance, newsock, ip, this->Hook);
1488         s = s; /* Whinge whinge whinge, thats all GCC ever does. */
1489         return true;
1490 }