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