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