]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/treesocket2.cpp
527c0122b414730e8c1e0f088a1739669f130268
[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 #ifndef WIN32
369                         timeval t;
370                         gettimeofday(&t, NULL);
371                         long ts = (t.tv_sec * 1000) + (t.tv_usec / 1000);
372                         ServerSource->rtt = ts - ServerSource->LastPingMsec;
373 #else
374                         ServerSource->rtt = Instance->Time() - ServerSource->LastPing;
375 #endif
376                 }
377         }
378         else
379         {
380                 std::string forwardto = params[1];
381                 if (forwardto == this->Instance->Config->ServerName)
382                 {
383                         /*
384                          * this is a PONG for us
385                          * if the prefix is a user, check theyre local, and if they are,
386                          * dump the PONG reply back to their fd. If its a server, do nowt.
387                          * Services might want to send these s->s, but we dont need to yet.
388                          */
389                         userrec* u = this->Instance->FindNick(prefix);
390                         if (u)
391                         {
392                                 u->WriteServ("PONG %s %s",params[0].c_str(),params[1].c_str());
393                         }
394                 }
395                 else
396                 {
397                         // not for us, pass it on :)
398                         Utils->DoOneToOne(prefix,"PONG",params,forwardto);
399                 }
400         }
401
402         return true;
403 }
404
405 bool TreeSocket::MetaData(const std::string &prefix, std::deque<std::string> &params)
406 {
407         if (params.size() < 2)
408                 return true;
409         else if (params.size() < 3)
410                 params.push_back("");
411         TreeServer* ServerSource = Utils->FindServer(prefix);
412         if (ServerSource)
413         {
414                 Utils->SetRemoteBursting(ServerSource, false);
415
416                 if (params[0] == "*")
417                 {
418                         FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));
419                 }
420                 else if (*(params[0].c_str()) == '#')
421                 {
422                         chanrec* c = this->Instance->FindChan(params[0]);
423                         if (c)
424                         {
425                                 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
426                         }
427                 }
428                 else if (*(params[0].c_str()) != '#')
429                 {
430                         userrec* u = this->Instance->FindNick(params[0]);
431                         if (u)
432                         {
433                                 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
434                         }
435                 }
436         }
437
438         params[2] = ":" + params[2];
439         Utils->DoOneToAllButSender(prefix,"METADATA",params,prefix);
440         return true;
441 }
442
443 bool TreeSocket::ServerVersion(const std::string &prefix, std::deque<std::string> &params)
444 {
445         if (params.size() < 1)
446                 return true;
447
448         TreeServer* ServerSource = Utils->FindServer(prefix);
449
450         if (ServerSource)
451         {
452                 ServerSource->SetVersion(params[0]);
453         }
454         params[0] = ":" + params[0];
455         Utils->DoOneToAllButSender(prefix,"VERSION",params,prefix);
456         return true;
457 }
458
459 bool TreeSocket::ChangeHost(const std::string &prefix, std::deque<std::string> &params)
460 {
461         if (params.size() < 1)
462                 return true;
463         userrec* u = this->Instance->FindNick(prefix);
464
465         if (u)
466         {
467                 u->ChangeDisplayedHost(params[0].c_str());
468                 Utils->DoOneToAllButSender(prefix,"FHOST",params,u->server);
469         }
470         return true;
471 }
472
473 bool TreeSocket::AddLine(const std::string &prefix, std::deque<std::string> &params)
474 {
475         if (params.size() < 6)
476                 return true;
477         bool propogate = false;
478         if (!this->bursting)
479                 Utils->lines_to_apply = 0;
480         switch (*(params[0].c_str()))
481         {
482                 case 'Z':
483                         propogate = Instance->XLines->add_zline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
484                         Instance->XLines->zline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
485                         if (propogate)
486                                 Utils->lines_to_apply |= APPLY_ZLINES;
487                 break;
488                 case 'Q':
489                         propogate = Instance->XLines->add_qline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
490                         Instance->XLines->qline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
491                         if (propogate)
492                                 Utils->lines_to_apply |= APPLY_QLINES;
493                 break;
494                 case 'E':
495                         propogate = Instance->XLines->add_eline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
496                         Instance->XLines->eline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
497                 break;
498                 case 'G':
499                         propogate = Instance->XLines->add_gline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
500                         Instance->XLines->gline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
501                         if (propogate)
502                                 Utils->lines_to_apply |= APPLY_GLINES;
503                 break;
504                 case 'K':
505                         propogate = Instance->XLines->add_kline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
506                         if (propogate)
507                                 Utils->lines_to_apply |= APPLY_KLINES;
508                 break;
509                 default:
510                         /* Just in case... */
511                         this->Instance->SNO->WriteToSnoMask('x',"\2WARNING\2: Invalid xline type '"+params[0]+"' sent by server "+prefix+", ignored!");
512                         propogate = false;
513                 break;
514         }
515         /* Send it on its way */
516         if (propogate)
517         {
518                 if (atoi(params[4].c_str()))
519                 {
520                         time_t c_requires_crap = ConvToInt(params[4]) + Instance->Time();
521                         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());
522                 }
523                 else
524                 {
525                         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());
526                 }
527                 params[5] = ":" + params[5];
528                 Utils->DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
529         }
530         if (!this->bursting)
531         {
532                 Instance->XLines->apply_lines(Utils->lines_to_apply);
533                 Utils->lines_to_apply = 0;
534         }
535         return true;
536 }
537
538 bool TreeSocket::ChangeName(const std::string &prefix, std::deque<std::string> &params)
539 {
540         if (params.size() < 1)
541                 return true;
542         userrec* u = this->Instance->FindNick(prefix);
543         if (u)
544         {
545                 u->ChangeName(params[0].c_str());
546                 params[0] = ":" + params[0];
547                 Utils->DoOneToAllButSender(prefix,"FNAME",params,u->server);
548         }
549         return true;
550 }
551
552 bool TreeSocket::Whois(const std::string &prefix, std::deque<std::string> &params)
553 {
554         if (params.size() < 1)
555                 return true;
556         userrec* u = this->Instance->FindNick(prefix);
557         if (u)
558         {
559                 // an incoming request
560                 if (params.size() == 1)
561                 {
562                         userrec* x = this->Instance->FindNick(params[0]);
563                         if ((x) && (IS_LOCAL(x)))
564                         {
565                                 userrec* x = this->Instance->FindNick(params[0]);
566                                 char signon[MAXBUF];
567                                 char idle[MAXBUF];
568                                 snprintf(signon, MAXBUF, "%lu", (unsigned long)x->signon);
569                                 snprintf(idle, MAXBUF, "%lu", (unsigned long)abs((x->idle_lastmsg) - Instance->Time(true)));
570                                 std::deque<std::string> par;
571                                 par.push_back(prefix);
572                                 par.push_back(signon);
573                                 par.push_back(idle);
574                                 // ours, we're done, pass it BACK
575                                 Utils->DoOneToOne(params[0], "IDLE", par, u->server);
576                         }
577                         else
578                         {
579                                 // not ours pass it on
580                                 if (x)
581                                         Utils->DoOneToOne(prefix, "IDLE", params, x->server);
582                         }
583                 }
584                 else if (params.size() == 3)
585                 {
586                         std::string who_did_the_whois = params[0];
587                         userrec* who_to_send_to = this->Instance->FindNick(who_did_the_whois);
588                         if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
589                         {
590                                 // an incoming reply to a whois we sent out
591                                 std::string nick_whoised = prefix;
592                                 unsigned long signon = atoi(params[1].c_str());
593                                 unsigned long idle = atoi(params[2].c_str());
594                                 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
595                                 {
596                                         do_whois(this->Instance, who_to_send_to, u, signon, idle, nick_whoised.c_str());
597                                 }
598                         }
599                         else
600                         {
601                                 // not ours, pass it on
602                                 if (who_to_send_to)
603                                         Utils->DoOneToOne(prefix, "IDLE", params, who_to_send_to->server);
604                         }
605                 }
606         }
607         return true;
608 }
609
610 bool TreeSocket::Push(const std::string &prefix, std::deque<std::string> &params)
611 {
612         if (params.size() < 2)
613                 return true;
614         userrec* u = this->Instance->FindNick(params[0]);
615         if (!u)
616                 return true;
617         if (IS_LOCAL(u))
618         {
619                 u->Write(params[1]);
620         }
621         else
622         {
623                 // continue the raw onwards
624                 params[1] = ":" + params[1];
625                 Utils->DoOneToOne(prefix,"PUSH",params,u->server);
626         }
627         return true;
628 }
629
630 bool TreeSocket::HandleSetTime(const std::string &prefix, std::deque<std::string> &params)
631 {
632         if (!params.size() || !Utils->EnableTimeSync)
633                 return true;
634
635         bool force = false;
636
637         if ((params.size() == 2) && (params[1] == "FORCE"))
638                 force = true;
639
640         time_t them = atoi(params[0].c_str());
641         time_t us = Instance->Time(false);
642
643         time_t diff = them - us;
644
645         Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
646
647         if (force || (them != us))
648         {
649                 time_t old = Instance->SetTimeDelta(diff);
650                 Instance->Log(DEBUG, "TS (diff %d) from %s applied (old delta was %d)", diff, prefix.c_str(), old);
651         }
652
653         return true;
654 }
655
656 bool TreeSocket::Time(const std::string &prefix, std::deque<std::string> &params)
657 {
658         // :source.server TIME remote.server sendernick
659         // :remote.server TIME source.server sendernick TS
660         if (params.size() == 2)
661         {
662                 // someone querying our time?
663                 if (this->Instance->Config->ServerName == params[0])
664                 {
665                         userrec* u = this->Instance->FindNick(params[1]);
666                         if (u)
667                         {
668                                 params.push_back(ConvToStr(Instance->Time(false)));
669                                 params[0] = prefix;
670                                 Utils->DoOneToOne(this->Instance->Config->ServerName,"TIME",params,params[0]);
671                         }
672                 }
673                 else
674                 {
675                         // not us, pass it on
676                         userrec* u = this->Instance->FindNick(params[1]);
677                         if (u)
678                                 Utils->DoOneToOne(prefix,"TIME",params,params[0]);
679                 }
680         }
681         else if (params.size() == 3)
682         {
683                 // a response to a previous TIME
684                 userrec* u = this->Instance->FindNick(params[1]);
685                 if ((u) && (IS_LOCAL(u)))
686                 {
687                         time_t rawtime = atol(params[2].c_str());
688                         struct tm * timeinfo;
689                         timeinfo = localtime(&rawtime);
690                         char tms[26];
691                         snprintf(tms,26,"%s",asctime(timeinfo));
692                         tms[24] = 0;
693                         u->WriteServ("391 %s %s :%s",u->nick,prefix.c_str(),tms);
694                 }
695                 else
696                 {
697                         if (u)
698                                 Utils->DoOneToOne(prefix,"TIME",params,u->server);
699                 }
700         }
701         return true;
702 }
703
704 bool TreeSocket::LocalPing(const std::string &prefix, std::deque<std::string> &params)
705 {
706         if (params.size() < 1)
707                 return true;
708         if (params.size() == 1)
709         {
710                 std::string stufftobounce = params[0];
711                 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" PONG "+stufftobounce);
712                 return true;
713         }
714         else
715         {
716                 std::string forwardto = params[1];
717                 if (forwardto == this->Instance->Config->ServerName)
718                 {
719                         // this is a ping for us, send back PONG to the requesting server
720                         params[1] = params[0];
721                         params[0] = forwardto;
722                         Utils->DoOneToOne(forwardto,"PONG",params,params[1]);
723                 }
724                 else
725                 {
726                         // not for us, pass it on :)
727                         Utils->DoOneToOne(prefix,"PING",params,forwardto);
728                 }
729                 return true;
730         }
731 }
732
733 /** TODO: This creates a total mess of output and needs to really use irc::modestacker.
734  */
735 bool TreeSocket::RemoveStatus(const std::string &prefix, std::deque<std::string> &params)
736 {
737         if (params.size() < 1)
738                 return true;
739         chanrec* c = Instance->FindChan(params[0]);
740         if (c)
741         {
742                 for (char modeletter = 'A'; modeletter <= 'z'; modeletter++)
743                 {
744                         ModeHandler* mh = Instance->Modes->FindMode(modeletter, MODETYPE_CHANNEL);
745                         if (mh)
746                                 mh->RemoveMode(c);
747                 }
748         }
749         return true;
750 }
751
752 bool TreeSocket::RemoteServer(const std::string &prefix, std::deque<std::string> &params)
753 {
754         if (params.size() < 4)
755                 return false;
756         std::string servername = params[0];
757         std::string password = params[1];
758         // hopcount is not used for a remote server, we calculate this ourselves
759         std::string description = params[3];
760         TreeServer* ParentOfThis = Utils->FindServer(prefix);
761         if (!ParentOfThis)
762         {
763                 this->SendError("Protocol error - Introduced remote server from unknown server "+prefix);
764                 return false;
765         }
766         TreeServer* CheckDupe = Utils->FindServer(servername);
767         if (CheckDupe)
768         {
769                 this->SendError("Server "+servername+" already exists!");
770                 this->Instance->SNO->WriteToSnoMask('l',"Server \2"+servername+"\2 being introduced from \2" + prefix + "\2 denied, already exists. Closing link with " + prefix);
771                 return false;
772         }
773         Link* lnk = Utils->FindLink(servername);
774         TreeServer* Node = new TreeServer(this->Utils,this->Instance,servername,description,ParentOfThis,NULL, lnk ? lnk->Hidden : false);
775         ParentOfThis->AddChild(Node);
776         params[3] = ":" + params[3];
777         Utils->SetRemoteBursting(Node, true);
778         Utils->DoOneToAllButSender(prefix,"SERVER",params,prefix);
779         this->Instance->SNO->WriteToSnoMask('l',"Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
780         return true;
781 }
782
783 bool TreeSocket::ComparePass(const std::string &ours, const std::string &theirs)
784 {
785         if ((!strncmp(ours.c_str(), "HMAC-SHA256:", 12)) || (!strncmp(theirs.c_str(), "HMAC-SHA256:", 12)))
786         {
787                 /* One or both of us specified hmac sha256, but we don't have sha256 module loaded!
788                  * We can't allow this password as valid.
789                  */
790                 if (!Instance->FindModule("m_sha256.so") || !Utils->ChallengeResponse)
791                                 return false;
792                 else
793                         /* Straight string compare of hashes */
794                         return ours == theirs;
795         }
796         else
797                 /* Straight string compare of plaintext */
798                 return ours == theirs;
799 }
800
801 bool TreeSocket::Outbound_Reply_Server(std::deque<std::string> &params)
802 {
803         if (params.size() < 4)
804                 return false;
805
806         irc::string servername = params[0].c_str();
807         std::string sname = params[0];
808         std::string password = params[1];
809         std::string description = params[3];
810         int hops = atoi(params[2].c_str());
811
812         this->InboundServerName = sname;
813         this->InboundDescription = description;
814
815         if (!sentcapab)
816                 this->SendCapabilities();
817
818         if (hops)
819         {
820                 this->SendError("Server too far away for authentication");
821                 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
822                 return false;
823         }
824
825         for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
826         {
827                 if ((x->Name == servername) && ((ComparePass(this->MakePass(x->RecvPass,this->GetOurChallenge()),password)) || (x->RecvPass == password && (this->GetTheirChallenge().empty()))))
828                 {
829                         TreeServer* CheckDupe = Utils->FindServer(sname);
830                         if (CheckDupe)
831                         {
832                                 this->SendError("Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
833                                 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
834                                 return false;
835                         }
836                         // Begin the sync here. this kickstarts the
837                         // other side, waiting in WAIT_AUTH_2 state,
838                         // into starting their burst, as it shows
839                         // that we're happy.
840                         this->LinkState = CONNECTED;
841                         // we should add the details of this server now
842                         // to the servers tree, as a child of the root
843                         // node.
844                         TreeServer* Node = new TreeServer(this->Utils,this->Instance,sname,description,Utils->TreeRoot,this,x->Hidden);
845                         Utils->TreeRoot->AddChild(Node);
846                         params[3] = ":" + params[3];
847                         Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,sname);
848                         this->bursting = true;
849                         this->DoBurst(Node);
850                         return true;
851                 }
852         }
853         this->SendError("Invalid credentials");
854         this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
855         return false;
856 }
857
858 bool TreeSocket::Inbound_Server(std::deque<std::string> &params)
859 {
860         if (params.size() < 4)
861                 return false;
862         irc::string servername = params[0].c_str();
863         std::string sname = params[0];
864         std::string password = params[1];
865         std::string description = params[3];
866         int hops = atoi(params[2].c_str());
867
868         this->InboundServerName = sname;
869         this->InboundDescription = description;
870
871         if (!sentcapab)
872                 this->SendCapabilities();
873
874         if (hops)
875         {
876                 this->SendError("Server too far away for authentication");
877                 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
878                 return false;
879         }
880
881         for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
882         {
883                 if ((x->Name == servername) && ((ComparePass(this->MakePass(x->RecvPass,this->GetOurChallenge()),password) || x->RecvPass == password && (this->GetTheirChallenge().empty()))))
884                 {
885                         /* First check for instances of the server that are waiting between the inbound and outbound SERVER command */
886                         TreeSocket* CheckDupeSocket = Utils->FindBurstingServer(sname);
887                         if (CheckDupeSocket)
888                         {
889                                 /* If we find one, we abort the link to prevent a race condition */
890                                 this->SendError("Negotiation collision");
891                                 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists in a negotiating state.");
892                                 CheckDupeSocket->SendError("Negotiation collision");
893                                 Instance->SE->DelFd(CheckDupeSocket);
894                                 CheckDupeSocket->Close();
895                                 return false;
896                         }
897                         /* Now check for fully initialized instances of the server */
898                         TreeServer* CheckDupe = Utils->FindServer(sname);
899                         if (CheckDupe)
900                         {
901                                 this->SendError("Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
902                                 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
903                                 return false;
904                         }
905                         this->Instance->SNO->WriteToSnoMask('l',"Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
906                         if (this->Hook)
907                         {
908                                 std::string name = InspSocketNameRequest((Module*)Utils->Creator, this->Hook).Send();
909                                 this->Instance->SNO->WriteToSnoMask('l',"Connection from \2"+sname+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] using transport \2"+name+"\2");
910                         }
911
912                         Utils->AddBurstingServer(sname,this);
913
914                         // this is good. Send our details: Our server name and description and hopcount of 0,
915                         // along with the sendpass from this block.
916                         this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+this->MakePass(x->SendPass, this->GetTheirChallenge())+" 0 :"+this->Instance->Config->ServerDesc);
917                         // move to the next state, we are now waiting for THEM.
918                         this->LinkState = WAIT_AUTH_2;
919                         return true;
920                 }
921         }
922         this->SendError("Invalid credentials");
923         this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
924         return false;
925 }
926
927 void TreeSocket::Split(const std::string &line, std::deque<std::string> &n)
928 {
929         n.clear();
930         irc::tokenstream tokens(line);
931         std::string param;
932         while (tokens.GetToken(param))
933         {
934                 if (!param.empty())
935                         n.push_back(param);
936         }
937         return;
938 }
939
940 bool TreeSocket::ProcessLine(std::string &line)
941 {
942         std::deque<std::string> params;
943         irc::string command;
944         std::string prefix;
945
946         line = line.substr(0, line.find_first_of("\r\n"));
947
948         if (line.empty())
949                 return true;
950
951         Instance->Log(DEBUG, "S[%d] <- %s", this->GetFd(), line.c_str());
952
953         this->Split(line.c_str(),params);
954         
955         if (params.empty())
956                 return true;
957         
958         if ((params[0][0] == ':') && (params.size() > 1))
959         {
960                 prefix = params[0].substr(1);
961                 params.pop_front();
962         }
963         command = params[0].c_str();
964         params.pop_front();
965         switch (this->LinkState)
966         {
967                 TreeServer* Node;
968
969                 case WAIT_AUTH_1:
970                         // Waiting for SERVER command from remote server. Server initiating
971                         // the connection sends the first SERVER command, listening server
972                         // replies with theirs if its happy, then if the initiator is happy,
973                         // it starts to send its net sync, which starts the merge, otherwise
974                         // it sends an ERROR.
975                         if (command == "PASS")
976                         {
977                                 /* Silently ignored */
978                         }
979                         else if (command == "SERVER")
980                         {
981                                 return this->Inbound_Server(params);
982                         }
983                         else if (command == "ERROR")
984                         {
985                                 return this->Error(params);
986                         }
987                         else if (command == "USER")
988                         {
989                                 this->SendError("Client connections to this port are prohibited.");
990                                 return false;
991                         }
992                         else if (command == "CAPAB")
993                         {
994                                 return this->Capab(params);
995                         }
996                         else if ((command == "U") || (command == "S"))
997                         {
998                                 this->SendError("Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
999                                 return false;
1000                         }
1001                         else
1002                         {
1003                                 irc::string error = "Invalid command in negotiation phase: " + command;
1004                                 this->SendError(assign(error));
1005                                 return false;
1006                         }
1007                 break;
1008                 case WAIT_AUTH_2:
1009                         // Waiting for start of other side's netmerge to say they liked our
1010                         // password.
1011                         if (command == "SERVER")
1012                         {
1013                                 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1014                                 // silently ignore.
1015                                 return true;
1016                         }
1017                         else if ((command == "U") || (command == "S"))
1018                         {
1019                                 this->SendError("Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
1020                                 return false;
1021                         }
1022                         else if (command == "BURST")
1023                         {
1024                                 if (params.size() && Utils->EnableTimeSync)
1025                                 {
1026                                         bool we_have_delta = (Instance->Time(false) != Instance->Time(true));
1027                                         time_t them = atoi(params[0].c_str());
1028                                         time_t delta = them - Instance->Time(false);
1029                                         if ((delta < -300) || (delta > 300))
1030                                         {
1031                                                 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));
1032                                                 SendError("Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than five minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
1033                                                 return false;
1034                                         }
1035                                         else if ((delta < -30) || (delta > 30))
1036                                         {
1037                                                 Instance->SNO->WriteToSnoMask('l',"\2WARNING\2: Your clocks are out by %d seconds. Please consider synching your clocks.", abs(delta));
1038                                         }
1039
1040                                         if (!Utils->MasterTime && !we_have_delta)
1041                                         {
1042                                                 this->Instance->SetTimeDelta(delta);
1043                                                 // Send this new timestamp to any other servers
1044                                                 Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
1045                                         }
1046                                 }
1047                                 this->LinkState = CONNECTED;
1048                                 Link* lnk = Utils->FindLink(InboundServerName);
1049                                 Node = new TreeServer(this->Utils,this->Instance, InboundServerName, InboundDescription, Utils->TreeRoot, this, lnk ? lnk->Hidden : false);
1050                                 Utils->DelBurstingServer(this);
1051                                 Utils->TreeRoot->AddChild(Node);
1052                                 params.clear();
1053                                 params.push_back(InboundServerName);
1054                                 params.push_back("*");
1055                                 params.push_back("1");
1056                                 params.push_back(":"+InboundDescription);
1057                                 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,InboundServerName);
1058                                 this->bursting = true;
1059                                 this->DoBurst(Node);
1060                         }
1061                         else if (command == "ERROR")
1062                         {
1063                                 return this->Error(params);
1064                         }
1065                         else if (command == "CAPAB")
1066                         {
1067                                 return this->Capab(params);
1068                         }
1069
1070                 break;
1071                 case LISTENER:
1072                         this->SendError("Internal error -- listening socket accepted its own descriptor!!!");
1073                         return false;
1074                 break;
1075                 case CONNECTING:
1076                         if (command == "SERVER")
1077                         {
1078                                 // another server we connected to, which was in WAIT_AUTH_1 state,
1079                                 // has just sent us their credentials. If we get this far, theyre
1080                                 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1081                                 // if we're happy with this, we should send our netburst which
1082                                 // kickstarts the merge.
1083                                 return this->Outbound_Reply_Server(params);
1084                         }
1085                         else if (command == "ERROR")
1086                         {
1087                                 return this->Error(params);
1088                         }
1089                         else if (command == "CAPAB")
1090                         {
1091                                 return this->Capab(params);
1092                         }
1093                 break;
1094                 case CONNECTED:
1095                         // This is the 'authenticated' state, when all passwords
1096                         // have been exchanged and anything past this point is taken
1097                         // as gospel.
1098
1099                         if (!prefix.empty())
1100                         {
1101                                 std::string direction = prefix;
1102                                 userrec* t = this->Instance->FindNick(prefix);
1103                                 if (t)
1104                                 {
1105                                         direction = t->server;
1106                                 }
1107                                 TreeServer* route_back_again = Utils->BestRouteTo(direction);
1108                                 if ((!route_back_again) || (route_back_again->GetSocket() != this))
1109                                 {
1110                                         if (route_back_again)
1111                                                 Instance->Log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
1112                                         return true;
1113                                 }
1114                                 /* Fix by brain:
1115                                  * When there is activity on the socket, reset the ping counter so
1116                                  * that we're not wasting bandwidth pinging an active server.
1117                                  */
1118                                 route_back_again->SetNextPingTime(time(NULL) + Utils->PingFreq);
1119                                 route_back_again->SetPingFlag();
1120                         }
1121                         else
1122                         {
1123                                 prefix = this->GetName();
1124                         }
1125
1126                         if ((command == "MODE") && (params.size() >= 2))
1127                         {
1128                                 chanrec* channel = Instance->FindChan(params[0]);
1129                                 if (channel)
1130                                 {
1131                                         userrec* x = Instance->FindNick(prefix);
1132                                         if (x)
1133                                         {
1134                                                 if (warned.find(x->server) == warned.end())
1135                                                 {
1136                                                         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);
1137                                                         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());
1138                                                         warned[x->server] = x->nick;
1139                                                 }
1140                                         }
1141                                 }
1142                         }
1143
1144                         if (command == "SVSMODE")
1145                         {
1146                                 /* Services expects us to implement
1147                                  * SVSMODE. In inspircd its the same as
1148                                  * MODE anyway.
1149                                  */
1150                                 command = "MODE";
1151                         }
1152                         std::string target;
1153                         /* Yes, know, this is a mess. Its reasonably fast though as we're
1154                          * working with std::string here.
1155                          */
1156                         if ((command == "NICK") && (params.size() >= 8))
1157                         {
1158                                 return this->IntroduceClient(prefix,params);
1159                         }
1160                         else if (command == "FJOIN")
1161                         {
1162                                 TreeServer* ServerSource = Utils->FindServer(prefix);
1163                                 if (ServerSource)
1164                                         Utils->SetRemoteBursting(ServerSource, false);
1165                                 return this->ForceJoin(prefix,params);
1166                         }
1167                         else if (command == "STATS")
1168                         {
1169                                 return this->Stats(prefix, params);
1170                         }
1171                         else if (command == "MOTD")
1172                         {
1173                                 return this->Motd(prefix, params);
1174                         }
1175                         else if (command == "KILL" && Utils->IsServer(prefix))
1176                         {
1177                                 return this->RemoteKill(prefix,params);
1178                         }
1179                         else if (command == "MODULES")
1180                         {
1181                                 return this->Modules(prefix, params);
1182                         }
1183                         else if (command == "ADMIN")
1184                         {
1185                                 return this->Admin(prefix, params);
1186                         }
1187                         else if (command == "SERVER")
1188                         {
1189                                 return this->RemoteServer(prefix,params);
1190                         }
1191                         else if (command == "ERROR")
1192                         {
1193                                 return this->Error(params);
1194                         }
1195                         else if (command == "OPERTYPE")
1196                         {
1197                                 return this->OperType(prefix,params);
1198                         }
1199                         else if (command == "FMODE")
1200                         {
1201                                 TreeServer* ServerSource = Utils->FindServer(prefix);
1202                                 if (ServerSource)
1203                                         Utils->SetRemoteBursting(ServerSource, false);
1204                                 return this->ForceMode(prefix,params);
1205                         }
1206                         else if (command == "FTOPIC")
1207                         {
1208                                 return this->ForceTopic(prefix,params);
1209                         }
1210                         else if (command == "REHASH")
1211                         {
1212                                 return this->RemoteRehash(prefix,params);
1213                         }
1214                         else if (command == "METADATA")
1215                         {
1216                                 return this->MetaData(prefix,params);
1217                         }
1218                         else if (command == "REMSTATUS")
1219                         {
1220                                 return this->RemoveStatus(prefix,params);
1221                         }
1222                         else if (command == "PING")
1223                         {
1224                                 if (prefix.empty())
1225                                         prefix = this->GetName();
1226                                 /*
1227                                  * We just got a ping from a server that's bursting.
1228                                  * This can't be right, so set them to not bursting, and
1229                                  * apply their lines.
1230                                  */
1231                                 TreeServer* ServerSource = Utils->FindServer(prefix);
1232                                 if (ServerSource)
1233                                         Utils->SetRemoteBursting(ServerSource, false);
1234
1235                                 if (this->bursting)
1236                                 {
1237                                         this->bursting = false;
1238                                         Instance->XLines->apply_lines(Utils->lines_to_apply);
1239                                         Utils->lines_to_apply = 0;
1240                                 }
1241
1242                                 return this->LocalPing(prefix,params);
1243                         }
1244                         else if (command == "PONG")
1245                         {
1246                                 if (prefix.empty())
1247                                         prefix = this->GetName();
1248                                 /*
1249                                  * We just got a pong from a server that's bursting.
1250                                  * This can't be right, so set them to not bursting, and
1251                                  * apply their lines.
1252                                  */
1253                                 TreeServer* ServerSource = Utils->FindServer(prefix);
1254                                 if (ServerSource)
1255                                         Utils->SetRemoteBursting(ServerSource, false);
1256
1257                                 if (this->bursting)
1258                                 {
1259                                         this->bursting = false;
1260                                         Instance->XLines->apply_lines(Utils->lines_to_apply);
1261                                         Utils->lines_to_apply = 0;
1262                                 }
1263
1264                                 return this->LocalPong(prefix,params);
1265                         }
1266                         else if (command == "VERSION")
1267                         {
1268                                 return this->ServerVersion(prefix,params);
1269                         }
1270                         else if (command == "FHOST")
1271                         {
1272                                 return this->ChangeHost(prefix,params);
1273                         }
1274                         else if (command == "FNAME")
1275                         {
1276                                 return this->ChangeName(prefix,params);
1277                         }
1278                         else if (command == "ADDLINE")
1279                         {
1280                                 TreeServer* ServerSource = Utils->FindServer(prefix);
1281                                 if (ServerSource)
1282                                         Utils->SetRemoteBursting(ServerSource, false);
1283                                 return this->AddLine(prefix,params);
1284                         }
1285                         else if (command == "SVSNICK")
1286                         {
1287                                 if (prefix.empty())
1288                                 {
1289                                         prefix = this->GetName();
1290                                 }
1291                                 return this->ForceNick(prefix,params);
1292                         }
1293                         else if (command == "OPERQUIT")
1294                         {
1295                                 return this->OperQuit(prefix,params);
1296                         }
1297                         else if (command == "IDLE")
1298                         {
1299                                 return this->Whois(prefix,params);
1300                         }
1301                         else if (command == "PUSH")
1302                         {
1303                                 return this->Push(prefix,params);
1304                         }
1305                         else if (command == "TIMESET")
1306                         {
1307                                 return this->HandleSetTime(prefix, params);
1308                         }
1309                         else if (command == "TIME")
1310                         {
1311                                 return this->Time(prefix,params);
1312                         }
1313                         else if ((command == "KICK") && (Utils->IsServer(prefix)))
1314                         {
1315                                 std::string sourceserv = this->myhost;
1316                                 if (params.size() == 3)
1317                                 {
1318                                         userrec* user = this->Instance->FindNick(params[1]);
1319                                         chanrec* chan = this->Instance->FindChan(params[0]);
1320                                         if (user && chan)
1321                                         {
1322                                                 if (!chan->ServerKickUser(user, params[2].c_str(), false))
1323                                                         /* Yikes, the channels gone! */
1324                                                         delete chan;
1325                                         }
1326                                 }
1327                                 if (!this->InboundServerName.empty())
1328                                 {
1329                                         sourceserv = this->InboundServerName;
1330                                 }
1331                                 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1332                         }
1333                         else if (command == "SVSJOIN")
1334                         {
1335                                 if (prefix.empty())
1336                                 {
1337                                         prefix = this->GetName();
1338                                 }
1339                                 return this->ServiceJoin(prefix,params);
1340                         }
1341                         else if (command == "SQUIT")
1342                         {
1343                                 if (params.size() == 2)
1344                                 {
1345                                         this->Squit(Utils->FindServer(params[0]),params[1]);
1346                                 }
1347                                 return true;
1348                         }
1349                         else if (command == "OPERNOTICE")
1350                         {
1351                                 std::string sourceserv = this->myhost;
1352                                 if (!this->InboundServerName.empty())
1353                                         sourceserv = this->InboundServerName;
1354                                 if (params.size() >= 1)
1355                                         Instance->WriteOpers("*** From " + sourceserv + ": " + params[0]);
1356                                 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1357                         }
1358                         else if (command == "MODENOTICE")
1359                         {
1360                                 std::string sourceserv = this->myhost;
1361                                 if (!this->InboundServerName.empty())
1362                                         sourceserv = this->InboundServerName;
1363                                 if (params.size() >= 2)
1364                                 {
1365                                         Instance->WriteMode(params[0].c_str(), WM_AND, "*** From %s: %s", sourceserv.c_str(), params[1].c_str());
1366                                 }
1367                                 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1368                         }
1369                         else if (command == "SNONOTICE")
1370                         {
1371                                 std::string sourceserv = this->myhost;
1372                                 if (!this->InboundServerName.empty())
1373                                         sourceserv = this->InboundServerName;
1374                                 if (params.size() >= 2)
1375                                 {
1376                                         Instance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + sourceserv + ": "+ params[1]);
1377                                 }
1378                                 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1379                         }
1380                         else if (command == "ENDBURST")
1381                         {
1382                                 this->bursting = false;
1383                                 Instance->XLines->apply_lines(Utils->lines_to_apply);
1384                                 Utils->lines_to_apply = 0;
1385                                 std::string sourceserv = this->myhost;
1386                                 if (!this->InboundServerName.empty())
1387                                         sourceserv = this->InboundServerName;
1388                                 this->Instance->SNO->WriteToSnoMask('l',"Received end of netburst from \2%s\2",sourceserv.c_str());
1389
1390                                 Event rmode((char*)sourceserv.c_str(), (Module*)Utils->Creator, "new_server");
1391                                 rmode.Send(Instance);
1392
1393                                 return true;
1394                         }
1395                         else
1396                         {
1397                                 // not a special inter-server command.
1398                                 // Emulate the actual user doing the command,
1399                                 // this saves us having a huge ugly parser.
1400                                 userrec* who = this->Instance->FindNick(prefix);
1401                                 std::string sourceserv = this->myhost;
1402                                 if (!this->InboundServerName.empty())
1403                                 {
1404                                         sourceserv = this->InboundServerName;
1405                                 }
1406                                 if ((!who) && (command == "MODE"))
1407                                 {
1408                                         if (Utils->IsServer(prefix))
1409                                         {
1410                                                 const char* modelist[MAXPARAMETERS];
1411                                                 for (size_t i = 0; i < params.size(); i++)
1412                                                         modelist[i] = params[i].c_str();
1413                                                 userrec* fake = new userrec(Instance);
1414                                                 fake->SetFd(FD_MAGIC_NUMBER);
1415                                                 this->Instance->SendMode(modelist, params.size(), fake);
1416
1417                                                 delete fake;
1418                                                 /* Hot potato! pass it on! */
1419                                                 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1420                                         }
1421                                 }
1422                                 if (who)
1423                                 {
1424                                         if ((command == "NICK") && (params.size() > 0))
1425                                         {
1426                                                 /* On nick messages, check that the nick doesnt
1427                                                  * already exist here. If it does, kill their copy,
1428                                                  * and our copy.
1429                                                  */
1430                                                 userrec* x = this->Instance->FindNick(params[0]);
1431                                                 if ((x) && (x != who))
1432                                                 {
1433                                                         std::deque<std::string> p;
1434                                                         p.push_back(params[0]);
1435                                                         p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
1436                                                         Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
1437                                                         p.clear();
1438                                                         p.push_back(prefix);
1439                                                         p.push_back("Nickname collision");
1440                                                         Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
1441                                                         userrec::QuitUser(this->Instance,x,"Nickname collision ("+prefix+" -> "+params[0]+")");
1442                                                         userrec* y = this->Instance->FindNick(prefix);
1443                                                         if (y)
1444                                                         {
1445                                                                 userrec::QuitUser(this->Instance,y,"Nickname collision");
1446                                                         }
1447                                                         return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1448                                                 }
1449                                         }
1450                                         // its a user
1451                                         target = who->server;
1452                                         const char* strparams[127];
1453                                         for (unsigned int q = 0; q < params.size(); q++)
1454                                         {
1455                                                 strparams[q] = params[q].c_str();
1456                                         }
1457                                         switch (this->Instance->CallCommandHandler(command.c_str(), strparams, params.size(), who))
1458                                         {
1459                                                 case CMD_INVALID:
1460                                                         this->SendError("Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
1461                                                         return false;
1462                                                 break;
1463                                                 case CMD_FAILURE:
1464                                                         return true;
1465                                                 break;
1466                                                 default:
1467                                                         /* CMD_SUCCESS and CMD_USER_DELETED fall through here */
1468                                                 break;
1469                                         }
1470                                 }
1471                                 else
1472                                 {
1473                                         // its not a user. Its either a server, or somethings screwed up.
1474                                         if (Utils->IsServer(prefix))
1475                                                 target = this->Instance->Config->ServerName;
1476                                         else
1477                                                 return true;
1478                                 }
1479                                 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1480
1481                         }
1482                         return true;
1483                 break;
1484         }
1485         return true;
1486 }
1487
1488 std::string TreeSocket::GetName()
1489 {
1490         std::string sourceserv = this->myhost;
1491         if (!this->InboundServerName.empty())
1492         {
1493                 sourceserv = this->InboundServerName;
1494         }
1495         return sourceserv;
1496 }
1497
1498 void TreeSocket::OnTimeout()
1499 {
1500         if (this->LinkState == CONNECTING)
1501         {
1502                 this->Instance->SNO->WriteToSnoMask('l',"CONNECT: Connection to \002"+myhost+"\002 timed out.");
1503                 Link* MyLink = Utils->FindLink(myhost);
1504                 if (MyLink)
1505                         Utils->DoFailOver(MyLink);
1506         }
1507 }
1508
1509 void TreeSocket::OnClose()
1510 {
1511         if (this->LinkState == LISTENER)
1512                 return;
1513
1514         // Connection closed.
1515         // If the connection is fully up (state CONNECTED)
1516         // then propogate a netsplit to all peers.
1517         std::string quitserver = this->myhost;
1518         if (!this->InboundServerName.empty())
1519         {
1520                 quitserver = this->InboundServerName;
1521         }
1522         TreeServer* s = Utils->FindServer(quitserver);
1523         if (s)
1524         {
1525                 Squit(s,"Remote host closed the connection");
1526         }
1527
1528         if (!quitserver.empty())
1529         {
1530                 this->Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' failed.",quitserver.c_str());
1531                 time_t server_uptime = Instance->Time() - this->age;    
1532                 if (server_uptime)
1533                         Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' was established for %s", quitserver.c_str(), Utils->Creator->TimeToStr(server_uptime).c_str());
1534         }
1535 }
1536
1537 int TreeSocket::OnIncomingConnection(int newsock, char* ip)
1538 {
1539         /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
1540          * or discovering if this port is the server port, we don't allow connections from any
1541          * IPs for which we don't have a link block.
1542          */
1543         bool found = false;
1544
1545         found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), ip) != Utils->ValidIPs.end());
1546         if (!found)
1547         {
1548                 for (vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
1549                         if (irc::sockets::MatchCIDR(ip, (*i).c_str()))
1550                                 found = true;
1551
1552                 if (!found)
1553                 {
1554                         this->Instance->SNO->WriteToSnoMask('l',"Server connection from %s denied (no link blocks with that IP address)", ip);
1555                         close(newsock);
1556                         return false;
1557                 }
1558         }
1559
1560         TreeSocket* s = new TreeSocket(this->Utils, this->Instance, newsock, ip, this->Hook);
1561         s = s; /* Whinge whinge whinge, thats all GCC ever does. */
1562         return true;
1563 }