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