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