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