]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/treesocket2.cpp
Make error reporting work properly, it seemed to loose errors.
[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 "configreader.h"
15 #include "users.h"
16 #include "channels.h"
17 #include "modules.h"
18 #include "commands/cmd_whois.h"
19 #include "commands/cmd_stats.h"
20 #include "socket.h"
21 #include "inspircd.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 int TreeSocket::WriteLine(std::string line)
38 {
39         Instance->Log(DEBUG, "-> %s", line.c_str());
40         line.append("\r\n");
41         return this->Write(line);
42 }
43
44
45 /* Handle ERROR command */
46 bool TreeSocket::Error(std::deque<std::string> &params)
47 {
48         if (params.size() < 1)
49                 return false;
50         this->Instance->SNO->WriteToSnoMask('l',"ERROR from %s: %s",(InboundServerName != "" ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
51         /* we will return false to cause the socket to close. */
52         return false;
53 }
54
55 bool TreeSocket::Modules(const std::string &prefix, std::deque<std::string> &params)
56 {
57         if (params.empty())
58                 return true;
59
60         if (!this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
61         {
62                 /* Pass it on, not for us */
63                 Utils->DoOneToOne(prefix, "MODULES", params, params[0]);
64                 return true;
65         }
66
67         char strbuf[MAXBUF];
68         std::deque<std::string> par;
69         par.push_back(prefix);
70         par.push_back("");
71
72         userrec* source = this->Instance->FindNick(prefix);
73         if (!source)
74                 return true;
75
76         for (unsigned int i = 0; i < Instance->Config->module_names.size(); i++)
77         {
78                 Version V = Instance->modules[i]->GetVersion();
79                 char modulename[MAXBUF];
80                 char flagstate[MAXBUF];
81                 *flagstate = 0;
82                 if (V.Flags & VF_STATIC)
83                         strlcat(flagstate,", static",MAXBUF);
84                 if (V.Flags & VF_VENDOR)
85                         strlcat(flagstate,", vendor",MAXBUF);
86                 if (V.Flags & VF_COMMON)
87                         strlcat(flagstate,", common",MAXBUF);
88                 if (V.Flags & VF_SERVICEPROVIDER)
89                         strlcat(flagstate,", service provider",MAXBUF);
90                 if (!flagstate[0])
91                         strcpy(flagstate,"  <no flags>");
92                 strlcpy(modulename,Instance->Config->module_names[i].c_str(),256);
93                 if (*source->oper)
94                 {
95                         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);
96                 }
97                 else
98                 {
99                         snprintf(strbuf, MAXBUF, "::%s 900 %s :%s",Instance->Config->ServerName,source->nick,ServerConfig::CleanFilename(modulename));
100                 }
101                 par[1] = strbuf;
102                 Utils->DoOneToOne(Instance->Config->ServerName, "PUSH", par, source->server);
103         }
104         snprintf(strbuf, MAXBUF, "::%s 901 %s :End of MODULES list", Instance->Config->ServerName, source->nick);
105         par[1] = strbuf;
106         Utils->DoOneToOne(Instance->Config->ServerName, "PUSH", par, source->server);
107         return true;
108 }
109
110 /** remote MOTD. leet, huh? */
111 bool TreeSocket::Motd(const std::string &prefix, std::deque<std::string> &params)
112 {
113         if (params.size() > 0)
114         {
115                 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
116                 {
117                         /* It's for our server */
118                         string_list results;
119                         userrec* source = this->Instance->FindNick(prefix);
120
121                         if (source)
122                         {
123                                 std::deque<std::string> par;
124                                 par.push_back(prefix);
125                                 par.push_back("");
126
127                                 if (!Instance->Config->MOTD.size())
128                                 {
129                                         par[1] = std::string("::")+Instance->Config->ServerName+" 422 "+source->nick+" :Message of the day file is missing.";
130                                         Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
131                                         return true;
132                                 }
133
134                                 par[1] = std::string("::")+Instance->Config->ServerName+" 375 "+source->nick+" :"+Instance->Config->ServerName+" message of the day";
135                                 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
136
137                                 for (unsigned int i = 0; i < Instance->Config->MOTD.size(); i++)
138                                 {
139                                         par[1] = std::string("::")+Instance->Config->ServerName+" 372 "+source->nick+" :- "+Instance->Config->MOTD[i];
140                                         Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
141                                 }
142
143                                 par[1] = std::string("::")+Instance->Config->ServerName+" 376 "+source->nick+" End of message of the day.";
144                                 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
145                         }
146                 }
147                 else
148                 {
149                         /* Pass it on */
150                         userrec* source = this->Instance->FindNick(prefix);
151                         if (source)
152                                 Utils->DoOneToOne(prefix, "MOTD", params, params[0]);
153                 }
154         }
155         return true;
156 }
157
158 /** remote ADMIN. leet, huh? */
159 bool TreeSocket::Admin(const std::string &prefix, std::deque<std::string> &params)
160 {
161         if (params.size() > 0)
162         {
163                 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
164                 {
165                         /* It's for our server */
166                         string_list results;
167                         userrec* source = this->Instance->FindNick(prefix);
168                         if (source)
169                         {
170                                 std::deque<std::string> par;
171                                 par.push_back(prefix);
172                                 par.push_back("");
173                                 par[1] = std::string("::")+Instance->Config->ServerName+" 256 "+source->nick+" :Administrative info for "+Instance->Config->ServerName;
174                                 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
175                                 par[1] = std::string("::")+Instance->Config->ServerName+" 257 "+source->nick+" :Name     - "+Instance->Config->AdminName;
176                                 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
177                                 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :Nickname - "+Instance->Config->AdminNick;
178                                 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
179                                 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :E-Mail   - "+Instance->Config->AdminEmail;
180                                 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
181                         }
182                 }
183                 else
184                 {
185                         /* Pass it on */
186                         userrec* source = this->Instance->FindNick(prefix);
187                         if (source)
188                                 Utils->DoOneToOne(prefix, "ADMIN", params, params[0]);
189                 }
190         }
191         return true;
192 }
193
194 bool TreeSocket::Stats(const std::string &prefix, std::deque<std::string> &params)
195 {
196         /* Get the reply to a STATS query if it matches this servername,
197          * and send it back as a load of PUSH queries
198          */
199         if (params.size() > 1)
200         {
201                 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[1]))
202                 {
203                         /* It's for our server */
204                         string_list results;
205                         userrec* source = this->Instance->FindNick(prefix);
206                         if (source)
207                         {
208                                 std::deque<std::string> par;
209                                 par.push_back(prefix);
210                                 par.push_back("");
211                                 DoStats(this->Instance, *(params[0].c_str()), source, results);
212                                 for (size_t i = 0; i < results.size(); i++)
213                                 {
214                                         par[1] = "::" + results[i];
215                                         Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
216                                 }
217                         }
218                 }
219                 else
220                 {
221                         /* Pass it on */
222                         userrec* source = this->Instance->FindNick(prefix);
223                         if (source)
224                                 Utils->DoOneToOne(prefix, "STATS", params, params[1]);
225                 }
226         }
227         return true;
228 }
229
230
231 /** Because the core won't let users or even SERVERS set +o,
232  * we use the OPERTYPE command to do this.
233  */
234 bool TreeSocket::OperType(const std::string &prefix, std::deque<std::string> &params)
235 {
236         if (params.size() != 1)
237                 return true;
238         std::string opertype = params[0];
239         userrec* u = this->Instance->FindNick(prefix);
240         if (u)
241         {
242                 u->modes[UM_OPERATOR] = 1;
243                 this->Instance->all_opers.push_back(u);
244                 strlcpy(u->oper,opertype.c_str(),NICKMAX-1);
245                 Utils->DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
246                 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()));
247         }
248         return true;
249 }
250
251 /** Because Andy insists that services-compatible servers must
252  * implement SVSNICK and SVSJOIN, that's exactly what we do :p
253  */
254 bool TreeSocket::ForceNick(const std::string &prefix, std::deque<std::string> &params)
255 {
256         if (params.size() < 3)
257                 return true;
258
259         userrec* u = this->Instance->FindNick(params[0]);
260
261         if (u)
262         {
263                 Utils->DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
264                 if (IS_LOCAL(u))
265                 {
266                         std::deque<std::string> par;
267                         par.push_back(params[1]);
268                         if (!u->ForceNickChange(params[1].c_str()))
269                         {
270                                 userrec::QuitUser(this->Instance, u, "Nickname collision");
271                                 return true;
272                         }
273                         u->age = atoi(params[2].c_str());
274                 }
275         }
276         return true;
277 }
278
279 bool TreeSocket::OperQuit(const std::string &prefix, std::deque<std::string> &params)
280 {
281         if (params.size() < 1)
282                 return true;
283
284         userrec* u = this->Instance->FindNick(prefix);
285
286         if (u)
287         {
288                 Utils->DoOneToAllButSender(prefix,"OPERQUIT",params,prefix);
289                 u->SetOperQuit(params[0]);
290         }
291         return true;
292 }
293
294 /*
295  * Remote SQUIT (RSQUIT). Routing works similar to SVSNICK: Route it to the server that the target is connected to locally,
296  * then let that server do the dirty work (squit it!). Example:
297  * 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
298  */
299 bool TreeSocket::RemoteSquit(const std::string &prefix, std::deque<std::string> &params)
300 {
301         /* ok.. :w00t RSQUIT jupe.barafranca.com :reason here */
302         if (params.size() < 2)
303                 return true;
304
305         TreeServer* s = Utils->FindServerMask(params[0]);
306
307         if (s)
308         {
309                 if (s == Utils->TreeRoot)
310                 {
311                         this->Instance->SNO->WriteToSnoMask('l',"What the fuck, I recieved a remote SQUIT for myself? :< (from %s", prefix.c_str());
312                         return true;
313                 }
314
315                 TreeSocket* sock = s->GetSocket();
316
317                 if (sock)
318                 {
319                         /* it's locally connected, KILL IT! */
320                         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());
321                         sock->Squit(s,"Server quit by " + prefix + ": " + params[1]);
322                         Instance->SE->DelFd(sock);
323                         sock->Close();
324                         delete sock;
325                 }
326                 else
327                 {
328                         /* route the rsquit */
329                         params[1] = ":" + params[1];
330                         Utils->DoOneToOne(prefix, "RSQUIT", params, params[0]);
331                 }
332         }
333         else
334         {
335                 /* mother fucker! it doesn't exist */
336         }
337
338         return true;
339 }
340
341 bool TreeSocket::ServiceJoin(const std::string &prefix, std::deque<std::string> &params)
342 {
343         if (params.size() < 2)
344                 return true;
345
346         userrec* u = this->Instance->FindNick(params[0]);
347
348         if (u)
349         {
350                 /* only join if it's local, otherwise just pass it on! */
351                 if (IS_LOCAL(u))
352                         chanrec::JoinUser(this->Instance, u, params[1].c_str(), false, "", Instance->Time());
353                 Utils->DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
354         }
355         return true;
356 }
357
358 bool TreeSocket::RemoteRehash(const std::string &prefix, std::deque<std::string> &params)
359 {
360         if (params.size() < 1)
361                 return false;
362
363         std::string servermask = params[0];
364
365         if (this->Instance->MatchText(this->Instance->Config->ServerName,servermask))
366         {
367                 this->Instance->SNO->WriteToSnoMask('l',"Remote rehash initiated by \002"+prefix+"\002.");
368                 this->Instance->RehashServer();
369                 Utils->ReadConfiguration(false);
370                 InitializeDisabledCommands(Instance->Config->DisabledCommands, Instance);
371         }
372         Utils->DoOneToAllButSender(prefix,"REHASH",params,prefix);
373         return true;
374 }
375
376 bool TreeSocket::RemoteKill(const std::string &prefix, std::deque<std::string> &params)
377 {
378         if (params.size() != 2)
379                 return true;
380
381         std::string nick = params[0];
382         userrec* u = this->Instance->FindNick(prefix);
383         userrec* who = this->Instance->FindNick(nick);
384
385         if (who)
386         {
387                 /* Prepend kill source, if we don't have one */
388                 std::string sourceserv = prefix;
389                 if (u)
390                 {
391                         sourceserv = u->server;
392                 }
393                 if (*(params[1].c_str()) != '[')
394                 {
395                         params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
396                 }
397                 std::string reason = params[1];
398                 params[1] = ":" + params[1];
399                 Utils->DoOneToAllButSender(prefix,"KILL",params,sourceserv);
400                 who->Write(":%s KILL %s :%s (%s)", sourceserv.c_str(), who->nick, sourceserv.c_str(), reason.c_str());
401                 userrec::QuitUser(this->Instance,who,reason);
402         }
403         return true;
404 }
405
406 bool TreeSocket::LocalPong(const std::string &prefix, std::deque<std::string> &params)
407 {
408         if (params.size() < 1)
409                 return true;
410
411         if (params.size() == 1)
412         {
413                 TreeServer* ServerSource = Utils->FindServer(prefix);
414                 if (ServerSource)
415                 {
416                         ServerSource->SetPingFlag();
417                         ServerSource->rtt = Instance->Time() - ServerSource->LastPing;
418                 }
419         }
420         else
421         {
422                 std::string forwardto = params[1];
423                 if (forwardto == this->Instance->Config->ServerName)
424                 {
425                         /*
426                          * this is a PONG for us
427                          * if the prefix is a user, check theyre local, and if they are,
428                          * dump the PONG reply back to their fd. If its a server, do nowt.
429                          * Services might want to send these s->s, but we dont need to yet.
430                          */
431                         userrec* u = this->Instance->FindNick(prefix);
432                         if (u)
433                         {
434                                 u->WriteServ("PONG %s %s",params[0].c_str(),params[1].c_str());
435                         }
436                 }
437                 else
438                 {
439                         // not for us, pass it on :)
440                         Utils->DoOneToOne(prefix,"PONG",params,forwardto);
441                 }
442         }
443
444         return true;
445 }
446
447 bool TreeSocket::MetaData(const std::string &prefix, std::deque<std::string> &params)
448 {
449         if (params.size() < 2)
450                 return true;
451         else if (params.size() < 3)
452                 params.push_back("");
453         TreeServer* ServerSource = Utils->FindServer(prefix);
454         if (ServerSource)
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                                         do_whois(this->Instance, who_to_send_to, u, signon, idle, nick_whoised.c_str());
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->DoOneToAllButSender(prefix,"SERVER",params,prefix);
816         this->Instance->SNO->WriteToSnoMask('l',"Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
817         return true;
818 }
819
820 bool TreeSocket::ComparePass(const std::string &ours, const std::string &theirs)
821 {
822         if ((!strncmp(ours.c_str(), "HMAC-SHA256:", 12)) || (!strncmp(theirs.c_str(), "HMAC-SHA256:", 12)))
823         {
824                 /* One or both of us specified hmac sha256, but we don't have sha256 module loaded!
825                  * We can't allow this password as valid.
826                  */
827                 if (!Instance->FindModule("m_sha256.so") || !Utils->ChallengeResponse)
828                                 return false;
829                 else
830                         /* Straight string compare of hashes */
831                         return ours == theirs;
832         }
833         else
834                 /* Straight string compare of plaintext */
835                 return ours == theirs;
836 }
837
838 bool TreeSocket::Outbound_Reply_Server(std::deque<std::string> &params)
839 {
840         if (params.size() < 4)
841                 return false;
842
843         irc::string servername = params[0].c_str();
844         std::string sname = params[0];
845         std::string password = params[1];
846         std::string description = params[3];
847         int hops = atoi(params[2].c_str());
848
849         this->InboundServerName = sname;
850         this->InboundDescription = description;
851
852         if (hops)
853         {
854                 this->SendError("Server too far away for authentication");
855                 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
856                 return false;
857         }
858
859         for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
860         {
861                 if ((x->Name == servername) && ((ComparePass(this->MakePass(x->RecvPass,this->GetOurChallenge()),password)) || (x->RecvPass == password && (this->GetTheirChallenge().empty()))))
862                 {
863                         TreeServer* CheckDupe = Utils->FindServer(sname);
864                         if (CheckDupe)
865                         {
866                                 this->SendError("Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
867                                 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
868                                 return false;
869                         }
870                         // Begin the sync here. this kickstarts the
871                         // other side, waiting in WAIT_AUTH_2 state,
872                         // into starting their burst, as it shows
873                         // that we're happy.
874                         this->LinkState = CONNECTED;
875                         // we should add the details of this server now
876                         // to the servers tree, as a child of the root
877                         // node.
878                         TreeServer* Node = new TreeServer(this->Utils,this->Instance,sname,description,Utils->TreeRoot,this,x->Hidden);
879                         Utils->TreeRoot->AddChild(Node);
880                         params[3] = ":" + params[3];
881                         Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,sname);
882                         this->bursting = true;
883                         this->DoBurst(Node);
884                         return true;
885                 }
886         }
887         this->SendError("Invalid credentials");
888         this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
889         return false;
890 }
891
892 bool TreeSocket::Inbound_Server(std::deque<std::string> &params)
893 {
894         if (params.size() < 4)
895                 return false;
896         irc::string servername = params[0].c_str();
897         std::string sname = params[0];
898         std::string password = params[1];
899         std::string description = params[3];
900         int hops = atoi(params[2].c_str());
901
902         this->InboundServerName = sname;
903         this->InboundDescription = description;
904
905         if (hops)
906         {
907                 this->SendError("Server too far away for authentication");
908                 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
909                 return false;
910         }
911
912         for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
913         {
914                 if ((x->Name == servername) && ((ComparePass(this->MakePass(x->RecvPass,this->GetOurChallenge()),password) || x->RecvPass == password && (this->GetTheirChallenge().empty()))))
915                 {
916                         /* First check for instances of the server that are waiting between the inbound and outbound SERVER command */
917                         TreeSocket* CheckDupeSocket = Utils->FindBurstingServer(sname);
918                         if (CheckDupeSocket)
919                         {
920                                 /* If we find one, we abort the link to prevent a race condition */
921                                 this->SendError("Negotiation collision");
922                                 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists in a negotiating state.");
923                                 CheckDupeSocket->SendError("Negotiation collision");
924                                 Instance->SE->DelFd(CheckDupeSocket);
925                                 CheckDupeSocket->Close();
926                                 delete CheckDupeSocket;
927                                 return false;
928                         }
929                         /* Now check for fully initialized instances of the server */
930                         TreeServer* CheckDupe = Utils->FindServer(sname);
931                         if (CheckDupe)
932                         {
933                                 this->SendError("Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
934                                 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
935                                 return false;
936                         }
937                         this->Instance->SNO->WriteToSnoMask('l',"Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
938                         if (this->Hook)
939                         {
940                                 std::string name = InspSocketNameRequest((Module*)Utils->Creator, this->Hook).Send();
941                                 this->Instance->SNO->WriteToSnoMask('l',"Connection from \2"+sname+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] using transport \2"+name+"\2");
942                         }
943
944                         Utils->AddBurstingServer(sname,this);
945
946                         // this is good. Send our details: Our server name and description and hopcount of 0,
947                         // along with the sendpass from this block.
948                         this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+this->MakePass(x->SendPass, this->GetTheirChallenge())+" 0 :"+this->Instance->Config->ServerDesc);
949                         // move to the next state, we are now waiting for THEM.
950                         this->LinkState = WAIT_AUTH_2;
951                         return true;
952                 }
953         }
954         this->SendError("Invalid credentials");
955         this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
956         return false;
957 }
958
959 void TreeSocket::Split(const std::string &line, std::deque<std::string> &n)
960 {
961         n.clear();
962         irc::tokenstream tokens(line);
963         std::string param;
964         while (tokens.GetToken(param))
965                 n.push_back(param);
966         return;
967 }
968
969 bool TreeSocket::ProcessLine(std::string &line)
970 {
971         std::deque<std::string> params;
972         irc::string command;
973         std::string prefix;
974
975         line = line.substr(0, line.find_first_of("\r\n"));
976
977         if (line.empty())
978                 return true;
979
980         Instance->Log(DEBUG, "<- %s", line.c_str());
981
982         this->Split(line.c_str(),params);
983
984         if ((params[0][0] == ':') && (params.size() > 1))
985         {
986                 prefix = params[0].substr(1);
987                 params.pop_front();
988         }
989         command = params[0].c_str();
990         params.pop_front();
991         switch (this->LinkState)
992         {
993                 TreeServer* Node;
994
995                 case WAIT_AUTH_1:
996                         // Waiting for SERVER command from remote server. Server initiating
997                         // the connection sends the first SERVER command, listening server
998                         // replies with theirs if its happy, then if the initiator is happy,
999                         // it starts to send its net sync, which starts the merge, otherwise
1000                         // it sends an ERROR.
1001                         if (command == "PASS")
1002                         {
1003                                 /* Silently ignored */
1004                         }
1005                         else if (command == "SERVER")
1006                         {
1007                                 return this->Inbound_Server(params);
1008                         }
1009                         else if (command == "ERROR")
1010                         {
1011                                 return this->Error(params);
1012                         }
1013                         else if (command == "USER")
1014                         {
1015                                 this->SendError("Client connections to this port are prohibited.");
1016                                 return false;
1017                         }
1018                         else if (command == "CAPAB")
1019                         {
1020                                 return this->Capab(params);
1021                         }
1022                         else if ((command == "U") || (command == "S"))
1023                         {
1024                                 this->SendError("Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
1025                                 return false;
1026                         }
1027                         else
1028                         {
1029                                 irc::string error = "Invalid command in negotiation phase: " + command;
1030                                 this->SendError(assign(error));
1031                                 return false;
1032                         }
1033                 break;
1034                 case WAIT_AUTH_2:
1035                         // Waiting for start of other side's netmerge to say they liked our
1036                         // password.
1037                         if (command == "SERVER")
1038                         {
1039                                 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1040                                 // silently ignore.
1041                                 return true;
1042                         }
1043                         else if ((command == "U") || (command == "S"))
1044                         {
1045                                 this->SendError("Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
1046                                 return false;
1047                         }
1048                         else if (command == "BURST")
1049                         {
1050                                 if (params.size() && Utils->EnableTimeSync)
1051                                 {
1052                                         bool we_have_delta = (Instance->Time(false) != Instance->Time(true));
1053                                         time_t them = atoi(params[0].c_str());
1054                                         time_t delta = them - Instance->Time(false);
1055                                         if ((delta < -300) || (delta > 300))
1056                                         {
1057                                                 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));
1058                                                 SendError("Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than ten minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
1059                                                 return false;
1060                                         }
1061                                         else if ((delta < -30) || (delta > 30))
1062                                         {
1063                                                 Instance->SNO->WriteToSnoMask('l',"\2WARNING\2: Your clocks are out by %d seconds. Please consider synching your clocks.", abs(delta));
1064                                         }
1065
1066                                         if (!Utils->MasterTime && !we_have_delta)
1067                                         {
1068                                                 this->Instance->SetTimeDelta(delta);
1069                                                 // Send this new timestamp to any other servers
1070                                                 Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
1071                                         }
1072                                 }
1073                                 this->LinkState = CONNECTED;
1074                                 Link* lnk = Utils->FindLink(InboundServerName);
1075                                 Node = new TreeServer(this->Utils,this->Instance, InboundServerName, InboundDescription, Utils->TreeRoot, this, lnk ? lnk->Hidden : false);
1076                                 Utils->DelBurstingServer(this);
1077                                 Utils->TreeRoot->AddChild(Node);
1078                                 params.clear();
1079                                 params.push_back(InboundServerName);
1080                                 params.push_back("*");
1081                                 params.push_back("1");
1082                                 params.push_back(":"+InboundDescription);
1083                                 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,InboundServerName);
1084                                 this->bursting = true;
1085                                 this->DoBurst(Node);
1086                         }
1087                         else if (command == "ERROR")
1088                         {
1089                                 return this->Error(params);
1090                         }
1091                         else if (command == "CAPAB")
1092                         {
1093                                 return this->Capab(params);
1094                         }
1095
1096                 break;
1097                 case LISTENER:
1098                         this->SendError("Internal error -- listening socket accepted its own descriptor!!!");
1099                         return false;
1100                 break;
1101                 case CONNECTING:
1102                         if (command == "SERVER")
1103                         {
1104                                 // another server we connected to, which was in WAIT_AUTH_1 state,
1105                                 // has just sent us their credentials. If we get this far, theyre
1106                                 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1107                                 // if we're happy with this, we should send our netburst which
1108                                 // kickstarts the merge.
1109                                 return this->Outbound_Reply_Server(params);
1110                         }
1111                         else if (command == "ERROR")
1112                         {
1113                                 return this->Error(params);
1114                         }
1115                         else if (command == "CAPAB")
1116                         {
1117                                 return this->Capab(params);
1118                         }
1119                 break;
1120                 case CONNECTED:
1121                         // This is the 'authenticated' state, when all passwords
1122                         // have been exchanged and anything past this point is taken
1123                         // as gospel.
1124
1125                         if (prefix != "")
1126                         {
1127                                 std::string direction = prefix;
1128                                 userrec* t = this->Instance->FindNick(prefix);
1129                                 if (t)
1130                                 {
1131                                         direction = t->server;
1132                                 }
1133                                 TreeServer* route_back_again = Utils->BestRouteTo(direction);
1134                                 if ((!route_back_again) || (route_back_again->GetSocket() != this))
1135                                 {
1136                                         if (route_back_again)
1137                                                 Instance->Log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
1138                                         return true;
1139                                 }
1140                                 /* Fix by brain:
1141                                  * When there is activity on the socket, reset the ping counter so
1142                                  * that we're not wasting bandwidth pinging an active server.
1143                                  */
1144                                 route_back_again->SetNextPingTime(time(NULL) + 60);
1145                                 route_back_again->SetPingFlag();
1146                         }
1147
1148                         if (command == "SVSMODE")
1149                         {
1150                                 /* Services expects us to implement
1151                                  * SVSMODE. In inspircd its the same as
1152                                  * MODE anyway.
1153                                  */
1154                                 command = "MODE";
1155                         }
1156                         std::string target = "";
1157                         /* Yes, know, this is a mess. Its reasonably fast though as we're
1158                          * working with std::string here.
1159                          */
1160                         if ((command == "NICK") && (params.size() >= 8))
1161                         {
1162                                 return this->IntroduceClient(prefix,params);
1163                         }
1164                         else if (command == "FJOIN")
1165                         {
1166                                 return this->ForceJoin(prefix,params);
1167                         }
1168                         else if (command == "STATS")
1169                         {
1170                                 return this->Stats(prefix, params);
1171                         }
1172                         else if (command == "MOTD")
1173                         {
1174                                 return this->Motd(prefix, params);
1175                         }
1176                         else if (command == "MODULES")
1177                         {
1178                                 return this->Modules(prefix, params);
1179                         }
1180                         else if (command == "ADMIN")
1181                         {
1182                                 return this->Admin(prefix, params);
1183                         }
1184                         else if (command == "SERVER")
1185                         {
1186                                 return this->RemoteServer(prefix,params);
1187                         }
1188                         else if (command == "ERROR")
1189                         {
1190                                 return this->Error(params);
1191                         }
1192                         else if (command == "OPERTYPE")
1193                         {
1194                                 return this->OperType(prefix,params);
1195                         }
1196                         else if (command == "FMODE")
1197                         {
1198                                 return this->ForceMode(prefix,params);
1199                         }
1200                         else if (command == "KILL")
1201                         {
1202                                 return this->RemoteKill(prefix,params);
1203                         }
1204                         else if (command == "FTOPIC")
1205                         {
1206                                 return this->ForceTopic(prefix,params);
1207                         }
1208                         else if (command == "REHASH")
1209                         {
1210                                 return this->RemoteRehash(prefix,params);
1211                         }
1212                         else if (command == "METADATA")
1213                         {
1214                                 return this->MetaData(prefix,params);
1215                         }
1216                         else if (command == "REMSTATUS")
1217                         {
1218                                 return this->RemoveStatus(prefix,params);
1219                         }
1220                         else if (command == "PING")
1221                         {
1222                                 /*
1223                                  * We just got a ping from a server that's bursting.
1224                                  * This can't be right, so set them to not bursting, and
1225                                  * apply their lines.
1226                                  */
1227                                 if (this->bursting)
1228                                 {
1229                                         this->bursting = false;
1230                                         Instance->XLines->apply_lines(Utils->lines_to_apply);
1231                                         Utils->lines_to_apply = 0;
1232                                 }
1233                                 if (prefix == "")
1234                                 {
1235                                         prefix = this->GetName();
1236                                 }
1237                                 return this->LocalPing(prefix,params);
1238                         }
1239                         else if (command == "PONG")
1240                         {
1241                                 /*
1242                                  * We just got a pong from a server that's bursting.
1243                                  * This can't be right, so set them to not bursting, and
1244                                  * apply their lines.
1245                                  */
1246                                 if (this->bursting)
1247                                 {
1248                                         this->bursting = false;
1249                                         Instance->XLines->apply_lines(Utils->lines_to_apply);
1250                                         Utils->lines_to_apply = 0;
1251                                 }
1252                                 if (prefix == "")
1253                                 {
1254                                         prefix = this->GetName();
1255                                 }
1256                                 return this->LocalPong(prefix,params);
1257                         }
1258                         else if (command == "VERSION")
1259                         {
1260                                 return this->ServerVersion(prefix,params);
1261                         }
1262                         else if (command == "FHOST")
1263                         {
1264                                 return this->ChangeHost(prefix,params);
1265                         }
1266                         else if (command == "FNAME")
1267                         {
1268                                 return this->ChangeName(prefix,params);
1269                         }
1270                         else if (command == "ADDLINE")
1271                         {
1272                                 return this->AddLine(prefix,params);
1273                         }
1274                         else if (command == "SVSNICK")
1275                         {
1276                                 if (prefix == "")
1277                                 {
1278                                         prefix = this->GetName();
1279                                 }
1280                                 return this->ForceNick(prefix,params);
1281                         }
1282                         else if (command == "OPERQUIT")
1283                         {
1284                                 return this->OperQuit(prefix,params);
1285                         }
1286                         else if (command == "RSQUIT")
1287                         {
1288                                 return this->RemoteSquit(prefix, params);
1289                         }
1290                         else if (command == "IDLE")
1291                         {
1292                                 return this->Whois(prefix,params);
1293                         }
1294                         else if (command == "PUSH")
1295                         {
1296                                 return this->Push(prefix,params);
1297                         }
1298                         else if (command == "TIMESET")
1299                         {
1300                                 return this->HandleSetTime(prefix, params);
1301                         }
1302                         else if (command == "TIME")
1303                         {
1304                                 return this->Time(prefix,params);
1305                         }
1306                         else if ((command == "KICK") && (Utils->IsServer(prefix)))
1307                         {
1308                                 std::string sourceserv = this->myhost;
1309                                 if (params.size() == 3)
1310                                 {
1311                                         userrec* user = this->Instance->FindNick(params[1]);
1312                                         chanrec* chan = this->Instance->FindChan(params[0]);
1313                                         if (user && chan)
1314                                         {
1315                                                 if (!chan->ServerKickUser(user, params[2].c_str(), false))
1316                                                         /* Yikes, the channels gone! */
1317                                                         delete chan;
1318                                         }
1319                                 }
1320                                 if (this->InboundServerName != "")
1321                                 {
1322                                         sourceserv = this->InboundServerName;
1323                                 }
1324                                 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1325                         }
1326                         else if (command == "SVSJOIN")
1327                         {
1328                                 if (prefix == "")
1329                                 {
1330                                         prefix = this->GetName();
1331                                 }
1332                                 return this->ServiceJoin(prefix,params);
1333                         }
1334                         else if (command == "SQUIT")
1335                         {
1336                                 if (params.size() == 2)
1337                                 {
1338                                         this->Squit(Utils->FindServer(params[0]),params[1]);
1339                                 }
1340                                 return true;
1341                         }
1342                         else if (command == "OPERNOTICE")
1343                         {
1344                                 std::string sourceserv = this->myhost;
1345                                 if (this->InboundServerName != "")
1346                                         sourceserv = this->InboundServerName;
1347                                 if (params.size() >= 1)
1348                                         Instance->WriteOpers("*** From " + sourceserv + ": " + params[0]);
1349                                 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1350                         }
1351                         else if (command == "MODENOTICE")
1352                         {
1353                                 std::string sourceserv = this->myhost;
1354                                 if (this->InboundServerName != "")
1355                                         sourceserv = this->InboundServerName;
1356                                 if (params.size() >= 2)
1357                                 {
1358                                         Instance->WriteMode(params[0].c_str(), WM_AND, "*** From %s: %s", sourceserv.c_str(), params[1].c_str());
1359                                 }
1360                                 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1361                         }
1362                         else if (command == "SNONOTICE")
1363                         {
1364                                 std::string sourceserv = this->myhost;
1365                                 if (this->InboundServerName != "")
1366                                         sourceserv = this->InboundServerName;
1367                                 if (params.size() >= 2)
1368                                 {
1369                                         Instance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + sourceserv + ": "+ params[1]);
1370                                 }
1371                                 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1372                         }
1373                         else if (command == "ENDBURST")
1374                         {
1375                                 this->bursting = false;
1376                                 Instance->XLines->apply_lines(Utils->lines_to_apply);
1377                                 Utils->lines_to_apply = 0;
1378                                 std::string sourceserv = this->myhost;
1379                                 if (this->InboundServerName != "")
1380                                 {
1381                                         sourceserv = this->InboundServerName;
1382                                 }
1383                                 this->Instance->SNO->WriteToSnoMask('l',"Received end of netburst from \2%s\2",sourceserv.c_str());
1384
1385                                 Event rmode((char*)sourceserv.c_str(), (Module*)Utils->Creator, "new_server");
1386                                 rmode.Send(Instance);
1387
1388                                 return true;
1389                         }
1390                         else
1391                         {
1392                                 // not a special inter-server command.
1393                                 // Emulate the actual user doing the command,
1394                                 // this saves us having a huge ugly parser.
1395                                 userrec* who = this->Instance->FindNick(prefix);
1396                                 std::string sourceserv = this->myhost;
1397                                 if (this->InboundServerName != "")
1398                                 {
1399                                         sourceserv = this->InboundServerName;
1400                                 }
1401                                 if ((!who) && (command == "MODE"))
1402                                 {
1403                                         if (Utils->IsServer(prefix))
1404                                         {
1405                                                 const char* modelist[127];
1406                                                 for (size_t i = 0; i < params.size(); i++)
1407                                                         modelist[i] = params[i].c_str();
1408                                                 userrec* fake = new userrec(Instance);
1409                                                 fake->SetFd(FD_MAGIC_NUMBER);
1410                                                 this->Instance->SendMode(modelist, params.size(), fake);
1411
1412                                                 delete fake;
1413                                                 /* Hot potato! pass it on! */
1414                                                 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1415                                         }
1416                                 }
1417                                 if (who)
1418                                 {
1419                                         if ((command == "NICK") && (params.size() > 0))
1420                                         {
1421                                                 /* On nick messages, check that the nick doesnt
1422                                                  * already exist here. If it does, kill their copy,
1423                                                  * and our copy.
1424                                                  */
1425                                                 userrec* x = this->Instance->FindNick(params[0]);
1426                                                 if ((x) && (x != who))
1427                                                 {
1428                                                         std::deque<std::string> p;
1429                                                         p.push_back(params[0]);
1430                                                         p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
1431                                                         Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
1432                                                         p.clear();
1433                                                         p.push_back(prefix);
1434                                                         p.push_back("Nickname collision");
1435                                                         Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
1436                                                         userrec::QuitUser(this->Instance,x,"Nickname collision ("+prefix+" -> "+params[0]+")");
1437                                                         userrec* y = this->Instance->FindNick(prefix);
1438                                                         if (y)
1439                                                         {
1440                                                                 userrec::QuitUser(this->Instance,y,"Nickname collision");
1441                                                         }
1442                                                         return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1443                                                 }
1444                                         }
1445                                         // its a user
1446                                         target = who->server;
1447                                         const char* strparams[127];
1448                                         for (unsigned int q = 0; q < params.size(); q++)
1449                                         {
1450                                                 strparams[q] = params[q].c_str();
1451                                         }
1452                                         switch (this->Instance->CallCommandHandler(command.c_str(), strparams, params.size(), who))
1453                                         {
1454                                                 case CMD_INVALID:
1455                                                         this->SendError("Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
1456                                                         return false;
1457                                                 break;
1458                                                 case CMD_FAILURE:
1459                                                         return true;
1460                                                 break;
1461                                                 default:
1462                                                         /* CMD_SUCCESS and CMD_USER_DELETED fall through here */
1463                                                 break;
1464                                         }
1465                                 }
1466                                 else
1467                                 {
1468                                         // its not a user. Its either a server, or somethings screwed up.
1469                                         if (Utils->IsServer(prefix))
1470                                                 target = this->Instance->Config->ServerName;
1471                                         else
1472                                                 return true;
1473                                 }
1474                                 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1475
1476                         }
1477                         return true;
1478                 break;
1479         }
1480         return true;
1481 }
1482
1483 std::string TreeSocket::GetName()
1484 {
1485         std::string sourceserv = this->myhost;
1486         if (this->InboundServerName != "")
1487         {
1488                 sourceserv = this->InboundServerName;
1489         }
1490         return sourceserv;
1491 }
1492
1493 void TreeSocket::OnTimeout()
1494 {
1495         if (this->LinkState == CONNECTING)
1496         {
1497                 this->Instance->SNO->WriteToSnoMask('l',"CONNECT: Connection to \002"+myhost+"\002 timed out.");
1498                 Link* MyLink = Utils->FindLink(myhost);
1499                 if (MyLink)
1500                         Utils->DoFailOver(MyLink);
1501         }
1502 }
1503
1504 void TreeSocket::OnClose()
1505 {
1506         // Connection closed.
1507         // If the connection is fully up (state CONNECTED)
1508         // then propogate a netsplit to all peers.
1509         std::string quitserver = this->myhost;
1510         if (this->InboundServerName != "")
1511         {
1512                 quitserver = this->InboundServerName;
1513         }
1514         TreeServer* s = Utils->FindServer(quitserver);
1515         if (s)
1516         {
1517                 Squit(s,"Remote host closed the connection");
1518         }
1519
1520         if (quitserver != "")
1521                 this->Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' failed.",quitserver.c_str());
1522 }
1523
1524 int TreeSocket::OnIncomingConnection(int newsock, char* ip)
1525 {
1526         /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
1527          * or discovering if this port is the server port, we don't allow connections from any
1528          * IPs for which we don't have a link block.
1529          */
1530         bool found = false;
1531
1532         found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), ip) != Utils->ValidIPs.end());
1533         if (!found)
1534         {
1535                 for (vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
1536                         if (irc::sockets::MatchCIDR(ip, (*i).c_str()))
1537                                 found = true;
1538
1539                 if (!found)
1540                 {
1541                         this->Instance->SNO->WriteToSnoMask('l',"Server connection from %s denied (no link blocks with that IP address)", ip);
1542                         close(newsock);
1543                         return false;
1544                 }
1545         }
1546
1547         TreeSocket* s = new TreeSocket(this->Utils, this->Instance, newsock, ip, this->Hook);
1548         s = s; /* Whinge whinge whinge, thats all GCC ever does. */
1549         return true;
1550 }