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