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