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