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