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