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