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