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