1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
15 #include "configreader.h"
19 #include "commands/cmd_whois.h"
20 #include "commands/cmd_stats.h"
24 #include "transport.h"
25 #include "socketengine.h"
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"
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 */
37 static std::map<std::string, std::string> warned; /* Server names that have had protocol violation warnings displayed for them */
39 int TreeSocket::WriteLine(std::string line)
41 Instance->Log(DEBUG, "S[%d] -> %s", this->GetFd(), line.c_str());
43 return this->Write(line);
47 /* Handle ERROR command */
48 bool TreeSocket::Error(std::deque<std::string> ¶ms)
50 if (params.size() < 1)
52 this->Instance->SNO->WriteToSnoMask('l',"ERROR from %s: %s",(InboundServerName != "" ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
53 /* we will return false to cause the socket to close. */
57 bool TreeSocket::Modules(const std::string &prefix, std::deque<std::string> ¶ms)
62 if (!this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
64 /* Pass it on, not for us */
65 Utils->DoOneToOne(prefix, "MODULES", params, params[0]);
70 std::deque<std::string> par;
71 par.push_back(prefix);
74 userrec* source = this->Instance->FindNick(prefix);
78 for (unsigned int i = 0; i < Instance->Config->module_names.size(); i++)
80 Version V = Instance->modules[i]->GetVersion();
81 char modulename[MAXBUF];
82 char flagstate[MAXBUF];
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);
93 strcpy(flagstate," <no flags>");
94 strlcpy(modulename,Instance->Config->module_names[i].c_str(),256);
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);
101 snprintf(strbuf, MAXBUF, "::%s 900 %s :%s",Instance->Config->ServerName,source->nick,ServerConfig::CleanFilename(modulename));
104 Utils->DoOneToOne(Instance->Config->ServerName, "PUSH", par, source->server);
106 snprintf(strbuf, MAXBUF, "::%s 901 %s :End of MODULES list", Instance->Config->ServerName, source->nick);
108 Utils->DoOneToOne(Instance->Config->ServerName, "PUSH", par, source->server);
112 /** remote MOTD. leet, huh? */
113 bool TreeSocket::Motd(const std::string &prefix, std::deque<std::string> ¶ms)
115 if (params.size() > 0)
117 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
119 /* It's for our server */
121 userrec* source = this->Instance->FindNick(prefix);
125 std::deque<std::string> par;
126 par.push_back(prefix);
129 if (!Instance->Config->MOTD.size())
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);
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);
139 for (unsigned int i = 0; i < Instance->Config->MOTD.size(); i++)
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);
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);
152 userrec* source = this->Instance->FindNick(prefix);
154 Utils->DoOneToOne(prefix, "MOTD", params, params[0]);
160 /** remote ADMIN. leet, huh? */
161 bool TreeSocket::Admin(const std::string &prefix, std::deque<std::string> ¶ms)
163 if (params.size() > 0)
165 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
167 /* It's for our server */
169 userrec* source = this->Instance->FindNick(prefix);
172 std::deque<std::string> par;
173 par.push_back(prefix);
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);
188 userrec* source = this->Instance->FindNick(prefix);
190 Utils->DoOneToOne(prefix, "ADMIN", params, params[0]);
196 bool TreeSocket::Stats(const std::string &prefix, std::deque<std::string> ¶ms)
198 /* Get the reply to a STATS query if it matches this servername,
199 * and send it back as a load of PUSH queries
201 if (params.size() > 1)
203 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[1]))
205 /* It's for our server */
207 userrec* source = this->Instance->FindNick(prefix);
210 std::deque<std::string> par;
211 par.push_back(prefix);
213 DoStats(this->Instance, *(params[0].c_str()), source, results);
214 for (size_t i = 0; i < results.size(); i++)
216 par[1] = "::" + results[i];
217 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
224 userrec* source = this->Instance->FindNick(prefix);
226 Utils->DoOneToOne(prefix, "STATS", params, params[1]);
233 /** Because the core won't let users or even SERVERS set +o,
234 * we use the OPERTYPE command to do this.
236 bool TreeSocket::OperType(const std::string &prefix, std::deque<std::string> ¶ms)
238 if (params.size() != 1)
240 std::string opertype = params[0];
241 userrec* u = this->Instance->FindNick(prefix);
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()));
253 /** Because Andy insists that services-compatible servers must
254 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
256 bool TreeSocket::ForceNick(const std::string &prefix, std::deque<std::string> ¶ms)
258 if (params.size() < 3)
261 userrec* u = this->Instance->FindNick(params[0]);
265 Utils->DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
268 std::deque<std::string> par;
269 par.push_back(params[1]);
270 if (!u->ForceNickChange(params[1].c_str()))
272 userrec::QuitUser(this->Instance, u, "Nickname collision");
275 u->age = atoi(params[2].c_str());
281 bool TreeSocket::OperQuit(const std::string &prefix, std::deque<std::string> ¶ms)
283 if (params.size() < 1)
286 userrec* u = this->Instance->FindNick(prefix);
290 u->SetOperQuit(params[0]);
291 params[0] = ":" + params[0];
292 Utils->DoOneToAllButSender(prefix,"OPERQUIT",params,prefix);
298 * Remote SQUIT (RSQUIT). Routing works similar to SVSNICK: Route it to the server that the target is connected to locally,
299 * then let that server do the dirty work (squit it!). Example:
300 * A -> B -> C -> D: oper on A squits D, A routes to B, B routes to C, C notices D connected locally, kills it. -- w00t
302 bool TreeSocket::RemoteSquit(const std::string &prefix, std::deque<std::string> ¶ms)
304 /* ok.. :w00t RSQUIT jupe.barafranca.com :reason here */
305 if (params.size() < 2)
308 TreeServer* s = Utils->FindServerMask(params[0]);
312 if (s == Utils->TreeRoot)
314 this->Instance->SNO->WriteToSnoMask('l',"What the fuck, I recieved a remote SQUIT for myself? :< (from %s", prefix.c_str());
318 TreeSocket* sock = s->GetSocket();
322 /* it's locally connected, KILL IT! */
323 Instance->SNO->WriteToSnoMask('l',"RSQUIT: Server \002%s\002 removed from network by %s: %s", params[0].c_str(), prefix.c_str(), params[1].c_str());
324 sock->Squit(s,"Server quit by " + prefix + ": " + params[1]);
325 Instance->SE->DelFd(sock);
331 /* route the rsquit */
332 params[1] = ":" + params[1];
333 Utils->DoOneToOne(prefix, "RSQUIT", params, params[0]);
338 /* mother fucker! it doesn't exist */
344 bool TreeSocket::ServiceJoin(const std::string &prefix, std::deque<std::string> ¶ms)
346 if (params.size() < 2)
349 userrec* u = this->Instance->FindNick(params[0]);
353 /* only join if it's local, otherwise just pass it on! */
355 chanrec::JoinUser(this->Instance, u, params[1].c_str(), false, "", Instance->Time());
356 Utils->DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
361 bool TreeSocket::RemoteRehash(const std::string &prefix, std::deque<std::string> ¶ms)
363 if (params.size() < 1)
366 std::string servermask = params[0];
368 if (this->Instance->MatchText(this->Instance->Config->ServerName,servermask))
370 this->Instance->SNO->WriteToSnoMask('l',"Remote rehash initiated by \002"+prefix+"\002.");
371 this->Instance->RehashServer();
372 Utils->ReadConfiguration(false);
373 InitializeDisabledCommands(Instance->Config->DisabledCommands, Instance);
375 Utils->DoOneToAllButSender(prefix,"REHASH",params,prefix);
379 bool TreeSocket::RemoteKill(const std::string &prefix, std::deque<std::string> ¶ms)
381 if (params.size() != 2)
384 std::string nick = params[0];
385 userrec* u = this->Instance->FindNick(prefix);
386 userrec* who = this->Instance->FindNick(nick);
390 /* Prepend kill source, if we don't have one */
391 std::string sourceserv = prefix;
394 sourceserv = u->server;
396 if (*(params[1].c_str()) != '[')
398 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
400 std::string reason = params[1];
401 params[1] = ":" + params[1];
402 Utils->DoOneToAllButSender(prefix,"KILL",params,sourceserv);
403 who->Write(":%s KILL %s :%s (%s)", sourceserv.c_str(), who->nick, sourceserv.c_str(), reason.c_str());
404 userrec::QuitUser(this->Instance,who,reason);
409 bool TreeSocket::LocalPong(const std::string &prefix, std::deque<std::string> ¶ms)
411 if (params.size() < 1)
414 if (params.size() == 1)
416 TreeServer* ServerSource = Utils->FindServer(prefix);
419 ServerSource->SetPingFlag();
420 ServerSource->rtt = Instance->Time() - ServerSource->LastPing;
425 std::string forwardto = params[1];
426 if (forwardto == this->Instance->Config->ServerName)
429 * this is a PONG for us
430 * if the prefix is a user, check theyre local, and if they are,
431 * dump the PONG reply back to their fd. If its a server, do nowt.
432 * Services might want to send these s->s, but we dont need to yet.
434 userrec* u = this->Instance->FindNick(prefix);
437 u->WriteServ("PONG %s %s",params[0].c_str(),params[1].c_str());
442 // not for us, pass it on :)
443 Utils->DoOneToOne(prefix,"PONG",params,forwardto);
450 bool TreeSocket::MetaData(const std::string &prefix, std::deque<std::string> ¶ms)
452 if (params.size() < 2)
454 else if (params.size() < 3)
455 params.push_back("");
456 TreeServer* ServerSource = Utils->FindServer(prefix);
459 Utils->SetRemoteBursting(ServerSource, false);
461 if (params[0] == "*")
463 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));
465 else if (*(params[0].c_str()) == '#')
467 chanrec* c = this->Instance->FindChan(params[0]);
470 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
473 else if (*(params[0].c_str()) != '#')
475 userrec* u = this->Instance->FindNick(params[0]);
478 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
483 params[2] = ":" + params[2];
484 Utils->DoOneToAllButSender(prefix,"METADATA",params,prefix);
488 bool TreeSocket::ServerVersion(const std::string &prefix, std::deque<std::string> ¶ms)
490 if (params.size() < 1)
493 TreeServer* ServerSource = Utils->FindServer(prefix);
497 ServerSource->SetVersion(params[0]);
499 params[0] = ":" + params[0];
500 Utils->DoOneToAllButSender(prefix,"VERSION",params,prefix);
504 bool TreeSocket::ChangeHost(const std::string &prefix, std::deque<std::string> ¶ms)
506 if (params.size() < 1)
508 userrec* u = this->Instance->FindNick(prefix);
512 u->ChangeDisplayedHost(params[0].c_str());
513 Utils->DoOneToAllButSender(prefix,"FHOST",params,u->server);
518 bool TreeSocket::AddLine(const std::string &prefix, std::deque<std::string> ¶ms)
520 if (params.size() < 6)
522 bool propogate = false;
524 Utils->lines_to_apply = 0;
525 switch (*(params[0].c_str()))
528 propogate = Instance->XLines->add_zline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
529 Instance->XLines->zline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
531 Utils->lines_to_apply |= APPLY_ZLINES;
534 propogate = Instance->XLines->add_qline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
535 Instance->XLines->qline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
537 Utils->lines_to_apply |= APPLY_QLINES;
540 propogate = Instance->XLines->add_eline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
541 Instance->XLines->eline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
544 propogate = Instance->XLines->add_gline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
545 Instance->XLines->gline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
547 Utils->lines_to_apply |= APPLY_GLINES;
550 propogate = Instance->XLines->add_kline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
552 Utils->lines_to_apply |= APPLY_KLINES;
555 /* Just in case... */
556 this->Instance->SNO->WriteToSnoMask('x',"\2WARNING\2: Invalid xline type '"+params[0]+"' sent by server "+prefix+", ignored!");
560 /* Send it on its way */
563 if (atoi(params[4].c_str()))
565 time_t c_requires_crap = ConvToInt(params[4]) + Instance->Time();
566 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());
570 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());
572 params[5] = ":" + params[5];
573 Utils->DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
577 Instance->XLines->apply_lines(Utils->lines_to_apply);
578 Utils->lines_to_apply = 0;
583 bool TreeSocket::ChangeName(const std::string &prefix, std::deque<std::string> ¶ms)
585 if (params.size() < 1)
587 userrec* u = this->Instance->FindNick(prefix);
590 u->ChangeName(params[0].c_str());
591 params[0] = ":" + params[0];
592 Utils->DoOneToAllButSender(prefix,"FNAME",params,u->server);
597 bool TreeSocket::Whois(const std::string &prefix, std::deque<std::string> ¶ms)
599 if (params.size() < 1)
601 userrec* u = this->Instance->FindNick(prefix);
604 // an incoming request
605 if (params.size() == 1)
607 userrec* x = this->Instance->FindNick(params[0]);
608 if ((x) && (IS_LOCAL(x)))
610 userrec* x = this->Instance->FindNick(params[0]);
613 snprintf(signon, MAXBUF, "%lu", (unsigned long)x->signon);
614 snprintf(idle, MAXBUF, "%lu", (unsigned long)abs((x->idle_lastmsg) - Instance->Time(true)));
615 std::deque<std::string> par;
616 par.push_back(prefix);
617 par.push_back(signon);
619 // ours, we're done, pass it BACK
620 Utils->DoOneToOne(params[0], "IDLE", par, u->server);
624 // not ours pass it on
626 Utils->DoOneToOne(prefix, "IDLE", params, x->server);
629 else if (params.size() == 3)
631 std::string who_did_the_whois = params[0];
632 userrec* who_to_send_to = this->Instance->FindNick(who_did_the_whois);
633 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
635 // an incoming reply to a whois we sent out
636 std::string nick_whoised = prefix;
637 unsigned long signon = atoi(params[1].c_str());
638 unsigned long idle = atoi(params[2].c_str());
639 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
641 do_whois(this->Instance, who_to_send_to, u, signon, idle, nick_whoised.c_str());
646 // not ours, pass it on
648 Utils->DoOneToOne(prefix, "IDLE", params, who_to_send_to->server);
655 bool TreeSocket::Push(const std::string &prefix, std::deque<std::string> ¶ms)
657 if (params.size() < 2)
659 userrec* u = this->Instance->FindNick(params[0]);
668 // continue the raw onwards
669 params[1] = ":" + params[1];
670 Utils->DoOneToOne(prefix,"PUSH",params,u->server);
675 bool TreeSocket::HandleSetTime(const std::string &prefix, std::deque<std::string> ¶ms)
677 if (!params.size() || !Utils->EnableTimeSync)
682 if ((params.size() == 2) && (params[1] == "FORCE"))
685 time_t them = atoi(params[0].c_str());
686 time_t us = Instance->Time(false);
688 time_t diff = them - us;
690 Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
692 if (force || (them != us))
694 time_t old = Instance->SetTimeDelta(diff);
695 Instance->Log(DEBUG, "TS (diff %d) from %s applied (old delta was %d)", diff, prefix.c_str(), old);
701 bool TreeSocket::Time(const std::string &prefix, std::deque<std::string> ¶ms)
703 // :source.server TIME remote.server sendernick
704 // :remote.server TIME source.server sendernick TS
705 if (params.size() == 2)
707 // someone querying our time?
708 if (this->Instance->Config->ServerName == params[0])
710 userrec* u = this->Instance->FindNick(params[1]);
713 params.push_back(ConvToStr(Instance->Time(false)));
715 Utils->DoOneToOne(this->Instance->Config->ServerName,"TIME",params,params[0]);
720 // not us, pass it on
721 userrec* u = this->Instance->FindNick(params[1]);
723 Utils->DoOneToOne(prefix,"TIME",params,params[0]);
726 else if (params.size() == 3)
728 // a response to a previous TIME
729 userrec* u = this->Instance->FindNick(params[1]);
730 if ((u) && (IS_LOCAL(u)))
732 time_t rawtime = atol(params[2].c_str());
733 struct tm * timeinfo;
734 timeinfo = localtime(&rawtime);
736 snprintf(tms,26,"%s",asctime(timeinfo));
738 u->WriteServ("391 %s %s :%s",u->nick,prefix.c_str(),tms);
743 Utils->DoOneToOne(prefix,"TIME",params,u->server);
749 bool TreeSocket::LocalPing(const std::string &prefix, std::deque<std::string> ¶ms)
751 if (params.size() < 1)
753 if (params.size() == 1)
755 std::string stufftobounce = params[0];
756 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" PONG "+stufftobounce);
761 std::string forwardto = params[1];
762 if (forwardto == this->Instance->Config->ServerName)
764 // this is a ping for us, send back PONG to the requesting server
765 params[1] = params[0];
766 params[0] = forwardto;
767 Utils->DoOneToOne(forwardto,"PONG",params,params[1]);
771 // not for us, pass it on :)
772 Utils->DoOneToOne(prefix,"PING",params,forwardto);
778 /** TODO: This creates a total mess of output and needs to really use irc::modestacker.
780 bool TreeSocket::RemoveStatus(const std::string &prefix, std::deque<std::string> ¶ms)
782 if (params.size() < 1)
784 chanrec* c = Instance->FindChan(params[0]);
787 for (char modeletter = 'A'; modeletter <= 'z'; modeletter++)
789 ModeHandler* mh = Instance->Modes->FindMode(modeletter, MODETYPE_CHANNEL);
797 bool TreeSocket::RemoteServer(const std::string &prefix, std::deque<std::string> ¶ms)
799 if (params.size() < 4)
801 std::string servername = params[0];
802 std::string password = params[1];
803 // hopcount is not used for a remote server, we calculate this ourselves
804 std::string description = params[3];
805 TreeServer* ParentOfThis = Utils->FindServer(prefix);
808 this->SendError("Protocol error - Introduced remote server from unknown server "+prefix);
811 TreeServer* CheckDupe = Utils->FindServer(servername);
814 this->SendError("Server "+servername+" already exists!");
815 this->Instance->SNO->WriteToSnoMask('l',"Server \2"+servername+"\2 being introduced from \2" + prefix + "\2 denied, already exists. Closing link with " + prefix);
818 Link* lnk = Utils->FindLink(servername);
819 TreeServer* Node = new TreeServer(this->Utils,this->Instance,servername,description,ParentOfThis,NULL, lnk ? lnk->Hidden : false);
820 ParentOfThis->AddChild(Node);
821 params[3] = ":" + params[3];
822 Utils->SetRemoteBursting(Node, true);
823 Utils->DoOneToAllButSender(prefix,"SERVER",params,prefix);
824 this->Instance->SNO->WriteToSnoMask('l',"Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
828 bool TreeSocket::ComparePass(const std::string &ours, const std::string &theirs)
830 if ((!strncmp(ours.c_str(), "HMAC-SHA256:", 12)) || (!strncmp(theirs.c_str(), "HMAC-SHA256:", 12)))
832 /* One or both of us specified hmac sha256, but we don't have sha256 module loaded!
833 * We can't allow this password as valid.
835 if (!Instance->FindModule("m_sha256.so") || !Utils->ChallengeResponse)
838 /* Straight string compare of hashes */
839 return ours == theirs;
842 /* Straight string compare of plaintext */
843 return ours == theirs;
846 bool TreeSocket::Outbound_Reply_Server(std::deque<std::string> ¶ms)
848 if (params.size() < 4)
851 irc::string servername = params[0].c_str();
852 std::string sname = params[0];
853 std::string password = params[1];
854 std::string description = params[3];
855 int hops = atoi(params[2].c_str());
857 this->InboundServerName = sname;
858 this->InboundDescription = description;
862 this->SendError("Server too far away for authentication");
863 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
867 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
869 if ((x->Name == servername) && ((ComparePass(this->MakePass(x->RecvPass,this->GetOurChallenge()),password)) || (x->RecvPass == password && (this->GetTheirChallenge().empty()))))
871 TreeServer* CheckDupe = Utils->FindServer(sname);
874 this->SendError("Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
875 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
878 // Begin the sync here. this kickstarts the
879 // other side, waiting in WAIT_AUTH_2 state,
880 // into starting their burst, as it shows
882 this->LinkState = CONNECTED;
883 // we should add the details of this server now
884 // to the servers tree, as a child of the root
886 TreeServer* Node = new TreeServer(this->Utils,this->Instance,sname,description,Utils->TreeRoot,this,x->Hidden);
887 Utils->TreeRoot->AddChild(Node);
888 params[3] = ":" + params[3];
889 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,sname);
890 this->bursting = true;
895 this->SendError("Invalid credentials");
896 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
900 bool TreeSocket::Inbound_Server(std::deque<std::string> ¶ms)
902 if (params.size() < 4)
904 irc::string servername = params[0].c_str();
905 std::string sname = params[0];
906 std::string password = params[1];
907 std::string description = params[3];
908 int hops = atoi(params[2].c_str());
910 this->InboundServerName = sname;
911 this->InboundDescription = description;
915 this->SendError("Server too far away for authentication");
916 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
920 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
922 if ((x->Name == servername) && ((ComparePass(this->MakePass(x->RecvPass,this->GetOurChallenge()),password) || x->RecvPass == password && (this->GetTheirChallenge().empty()))))
924 /* First check for instances of the server that are waiting between the inbound and outbound SERVER command */
925 TreeSocket* CheckDupeSocket = Utils->FindBurstingServer(sname);
928 /* If we find one, we abort the link to prevent a race condition */
929 this->SendError("Negotiation collision");
930 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists in a negotiating state.");
931 CheckDupeSocket->SendError("Negotiation collision");
932 Instance->SE->DelFd(CheckDupeSocket);
933 CheckDupeSocket->Close();
934 delete CheckDupeSocket;
937 /* Now check for fully initialized instances of the server */
938 TreeServer* CheckDupe = Utils->FindServer(sname);
941 this->SendError("Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
942 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
945 this->Instance->SNO->WriteToSnoMask('l',"Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
948 std::string name = InspSocketNameRequest((Module*)Utils->Creator, this->Hook).Send();
949 this->Instance->SNO->WriteToSnoMask('l',"Connection from \2"+sname+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] using transport \2"+name+"\2");
952 Utils->AddBurstingServer(sname,this);
954 // this is good. Send our details: Our server name and description and hopcount of 0,
955 // along with the sendpass from this block.
956 this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+this->MakePass(x->SendPass, this->GetTheirChallenge())+" 0 :"+this->Instance->Config->ServerDesc);
957 // move to the next state, we are now waiting for THEM.
958 this->LinkState = WAIT_AUTH_2;
962 this->SendError("Invalid credentials");
963 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
967 void TreeSocket::Split(const std::string &line, std::deque<std::string> &n)
970 irc::tokenstream tokens(line);
972 while (tokens.GetToken(param))
980 bool TreeSocket::ProcessLine(std::string &line)
982 std::deque<std::string> params;
986 line = line.substr(0, line.find_first_of("\r\n"));
991 Instance->Log(DEBUG, "S[%d] <- %s", this->GetFd(), line.c_str());
993 this->Split(line.c_str(),params);
998 if ((params[0][0] == ':') && (params.size() > 1))
1000 prefix = params[0].substr(1);
1003 command = params[0].c_str();
1005 switch (this->LinkState)
1010 // Waiting for SERVER command from remote server. Server initiating
1011 // the connection sends the first SERVER command, listening server
1012 // replies with theirs if its happy, then if the initiator is happy,
1013 // it starts to send its net sync, which starts the merge, otherwise
1014 // it sends an ERROR.
1015 if (command == "PASS")
1017 /* Silently ignored */
1019 else if (command == "SERVER")
1021 return this->Inbound_Server(params);
1023 else if (command == "ERROR")
1025 return this->Error(params);
1027 else if (command == "USER")
1029 this->SendError("Client connections to this port are prohibited.");
1032 else if (command == "CAPAB")
1034 return this->Capab(params);
1036 else if ((command == "U") || (command == "S"))
1038 this->SendError("Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
1043 irc::string error = "Invalid command in negotiation phase: " + command;
1044 this->SendError(assign(error));
1049 // Waiting for start of other side's netmerge to say they liked our
1051 if (command == "SERVER")
1053 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1057 else if ((command == "U") || (command == "S"))
1059 this->SendError("Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
1062 else if (command == "BURST")
1064 if (params.size() && Utils->EnableTimeSync)
1066 bool we_have_delta = (Instance->Time(false) != Instance->Time(true));
1067 time_t them = atoi(params[0].c_str());
1068 time_t delta = them - Instance->Time(false);
1069 if ((delta < -300) || (delta > 300))
1071 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));
1072 SendError("Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than five minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
1075 else if ((delta < -30) || (delta > 30))
1077 Instance->SNO->WriteToSnoMask('l',"\2WARNING\2: Your clocks are out by %d seconds. Please consider synching your clocks.", abs(delta));
1080 if (!Utils->MasterTime && !we_have_delta)
1082 this->Instance->SetTimeDelta(delta);
1083 // Send this new timestamp to any other servers
1084 Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
1087 this->LinkState = CONNECTED;
1088 Link* lnk = Utils->FindLink(InboundServerName);
1089 Node = new TreeServer(this->Utils,this->Instance, InboundServerName, InboundDescription, Utils->TreeRoot, this, lnk ? lnk->Hidden : false);
1090 Utils->DelBurstingServer(this);
1091 Utils->TreeRoot->AddChild(Node);
1093 params.push_back(InboundServerName);
1094 params.push_back("*");
1095 params.push_back("1");
1096 params.push_back(":"+InboundDescription);
1097 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,InboundServerName);
1098 this->bursting = true;
1099 this->DoBurst(Node);
1101 else if (command == "ERROR")
1103 return this->Error(params);
1105 else if (command == "CAPAB")
1107 return this->Capab(params);
1112 this->SendError("Internal error -- listening socket accepted its own descriptor!!!");
1116 if (command == "SERVER")
1118 // another server we connected to, which was in WAIT_AUTH_1 state,
1119 // has just sent us their credentials. If we get this far, theyre
1120 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1121 // if we're happy with this, we should send our netburst which
1122 // kickstarts the merge.
1123 return this->Outbound_Reply_Server(params);
1125 else if (command == "ERROR")
1127 return this->Error(params);
1129 else if (command == "CAPAB")
1131 return this->Capab(params);
1135 // This is the 'authenticated' state, when all passwords
1136 // have been exchanged and anything past this point is taken
1139 if (!prefix.empty())
1141 std::string direction = prefix;
1142 userrec* t = this->Instance->FindNick(prefix);
1145 direction = t->server;
1147 TreeServer* route_back_again = Utils->BestRouteTo(direction);
1148 if ((!route_back_again) || (route_back_again->GetSocket() != this))
1150 if (route_back_again)
1151 Instance->Log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
1155 * When there is activity on the socket, reset the ping counter so
1156 * that we're not wasting bandwidth pinging an active server.
1158 route_back_again->SetNextPingTime(time(NULL) + 60);
1159 route_back_again->SetPingFlag();
1163 prefix = this->GetName();
1166 if ((command == "MODE") && (params.size() >= 2))
1168 chanrec* channel = Instance->FindChan(params[0]);
1171 userrec* x = Instance->FindNick(prefix);
1174 if (warned.find(x->server) == warned.end())
1176 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);
1177 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());
1178 warned[x->server] = x->nick;
1184 if (command == "SVSMODE")
1186 /* Services expects us to implement
1187 * SVSMODE. In inspircd its the same as
1192 std::string target = "";
1193 /* Yes, know, this is a mess. Its reasonably fast though as we're
1194 * working with std::string here.
1196 if ((command == "NICK") && (params.size() >= 8))
1198 return this->IntroduceClient(prefix,params);
1200 else if (command == "FJOIN")
1202 TreeServer* ServerSource = Utils->FindServer(prefix);
1204 Utils->SetRemoteBursting(ServerSource, false);
1205 return this->ForceJoin(prefix,params);
1207 else if (command == "STATS")
1209 return this->Stats(prefix, params);
1211 else if (command == "MOTD")
1213 return this->Motd(prefix, params);
1215 else if (command == "MODULES")
1217 return this->Modules(prefix, params);
1219 else if (command == "ADMIN")
1221 return this->Admin(prefix, params);
1223 else if (command == "SERVER")
1225 return this->RemoteServer(prefix,params);
1227 else if (command == "ERROR")
1229 return this->Error(params);
1231 else if (command == "OPERTYPE")
1233 return this->OperType(prefix,params);
1235 else if (command == "FMODE")
1237 TreeServer* ServerSource = Utils->FindServer(prefix);
1239 Utils->SetRemoteBursting(ServerSource, false);
1240 return this->ForceMode(prefix,params);
1242 else if (command == "KILL")
1244 return this->RemoteKill(prefix,params);
1246 else if (command == "FTOPIC")
1248 return this->ForceTopic(prefix,params);
1250 else if (command == "REHASH")
1252 return this->RemoteRehash(prefix,params);
1254 else if (command == "METADATA")
1256 return this->MetaData(prefix,params);
1258 else if (command == "REMSTATUS")
1260 return this->RemoveStatus(prefix,params);
1262 else if (command == "PING")
1265 prefix = this->GetName();
1267 * We just got a ping from a server that's bursting.
1268 * This can't be right, so set them to not bursting, and
1269 * apply their lines.
1271 TreeServer* ServerSource = Utils->FindServer(prefix);
1273 Utils->SetRemoteBursting(ServerSource, false);
1277 this->bursting = false;
1278 Instance->XLines->apply_lines(Utils->lines_to_apply);
1279 Utils->lines_to_apply = 0;
1282 return this->LocalPing(prefix,params);
1284 else if (command == "PONG")
1287 prefix = this->GetName();
1289 * We just got a pong from a server that's bursting.
1290 * This can't be right, so set them to not bursting, and
1291 * apply their lines.
1293 TreeServer* ServerSource = Utils->FindServer(prefix);
1295 Utils->SetRemoteBursting(ServerSource, false);
1299 this->bursting = false;
1300 Instance->XLines->apply_lines(Utils->lines_to_apply);
1301 Utils->lines_to_apply = 0;
1304 return this->LocalPong(prefix,params);
1306 else if (command == "VERSION")
1308 return this->ServerVersion(prefix,params);
1310 else if (command == "FHOST")
1312 return this->ChangeHost(prefix,params);
1314 else if (command == "FNAME")
1316 return this->ChangeName(prefix,params);
1318 else if (command == "ADDLINE")
1320 TreeServer* ServerSource = Utils->FindServer(prefix);
1322 Utils->SetRemoteBursting(ServerSource, false);
1323 return this->AddLine(prefix,params);
1325 else if (command == "SVSNICK")
1329 prefix = this->GetName();
1331 return this->ForceNick(prefix,params);
1333 else if (command == "OPERQUIT")
1335 return this->OperQuit(prefix,params);
1337 else if (command == "RSQUIT")
1339 return this->RemoteSquit(prefix, params);
1341 else if (command == "IDLE")
1343 return this->Whois(prefix,params);
1345 else if (command == "PUSH")
1347 return this->Push(prefix,params);
1349 else if (command == "TIMESET")
1351 return this->HandleSetTime(prefix, params);
1353 else if (command == "TIME")
1355 return this->Time(prefix,params);
1357 else if ((command == "KICK") && (Utils->IsServer(prefix)))
1359 std::string sourceserv = this->myhost;
1360 if (params.size() == 3)
1362 userrec* user = this->Instance->FindNick(params[1]);
1363 chanrec* chan = this->Instance->FindChan(params[0]);
1366 if (!chan->ServerKickUser(user, params[2].c_str(), false))
1367 /* Yikes, the channels gone! */
1371 if (this->InboundServerName != "")
1373 sourceserv = this->InboundServerName;
1375 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1377 else if (command == "SVSJOIN")
1381 prefix = this->GetName();
1383 return this->ServiceJoin(prefix,params);
1385 else if (command == "SQUIT")
1387 if (params.size() == 2)
1389 this->Squit(Utils->FindServer(params[0]),params[1]);
1393 else if (command == "OPERNOTICE")
1395 std::string sourceserv = this->myhost;
1396 if (this->InboundServerName != "")
1397 sourceserv = this->InboundServerName;
1398 if (params.size() >= 1)
1399 Instance->WriteOpers("*** From " + sourceserv + ": " + params[0]);
1400 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1402 else if (command == "MODENOTICE")
1404 std::string sourceserv = this->myhost;
1405 if (this->InboundServerName != "")
1406 sourceserv = this->InboundServerName;
1407 if (params.size() >= 2)
1409 Instance->WriteMode(params[0].c_str(), WM_AND, "*** From %s: %s", sourceserv.c_str(), params[1].c_str());
1411 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1413 else if (command == "SNONOTICE")
1415 std::string sourceserv = this->myhost;
1416 if (this->InboundServerName != "")
1417 sourceserv = this->InboundServerName;
1418 if (params.size() >= 2)
1420 Instance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + sourceserv + ": "+ params[1]);
1422 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1424 else if (command == "ENDBURST")
1426 this->bursting = false;
1427 Instance->XLines->apply_lines(Utils->lines_to_apply);
1428 Utils->lines_to_apply = 0;
1429 std::string sourceserv = this->myhost;
1430 if (this->InboundServerName != "")
1432 sourceserv = this->InboundServerName;
1434 this->Instance->SNO->WriteToSnoMask('l',"Received end of netburst from \2%s\2",sourceserv.c_str());
1436 Event rmode((char*)sourceserv.c_str(), (Module*)Utils->Creator, "new_server");
1437 rmode.Send(Instance);
1443 // not a special inter-server command.
1444 // Emulate the actual user doing the command,
1445 // this saves us having a huge ugly parser.
1446 userrec* who = this->Instance->FindNick(prefix);
1447 std::string sourceserv = this->myhost;
1448 if (this->InboundServerName != "")
1450 sourceserv = this->InboundServerName;
1452 if ((!who) && (command == "MODE"))
1454 if (Utils->IsServer(prefix))
1456 const char* modelist[127];
1457 for (size_t i = 0; i < params.size(); i++)
1458 modelist[i] = params[i].c_str();
1459 userrec* fake = new userrec(Instance);
1460 fake->SetFd(FD_MAGIC_NUMBER);
1461 this->Instance->SendMode(modelist, params.size(), fake);
1464 /* Hot potato! pass it on! */
1465 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1470 if ((command == "NICK") && (params.size() > 0))
1472 /* On nick messages, check that the nick doesnt
1473 * already exist here. If it does, kill their copy,
1476 userrec* x = this->Instance->FindNick(params[0]);
1477 if ((x) && (x != who))
1479 std::deque<std::string> p;
1480 p.push_back(params[0]);
1481 p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
1482 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
1484 p.push_back(prefix);
1485 p.push_back("Nickname collision");
1486 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
1487 userrec::QuitUser(this->Instance,x,"Nickname collision ("+prefix+" -> "+params[0]+")");
1488 userrec* y = this->Instance->FindNick(prefix);
1491 userrec::QuitUser(this->Instance,y,"Nickname collision");
1493 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1497 target = who->server;
1498 const char* strparams[127];
1499 for (unsigned int q = 0; q < params.size(); q++)
1501 strparams[q] = params[q].c_str();
1503 switch (this->Instance->CallCommandHandler(command.c_str(), strparams, params.size(), who))
1506 this->SendError("Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
1513 /* CMD_SUCCESS and CMD_USER_DELETED fall through here */
1519 // its not a user. Its either a server, or somethings screwed up.
1520 if (Utils->IsServer(prefix))
1521 target = this->Instance->Config->ServerName;
1525 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1534 std::string TreeSocket::GetName()
1536 std::string sourceserv = this->myhost;
1537 if (this->InboundServerName != "")
1539 sourceserv = this->InboundServerName;
1544 void TreeSocket::OnTimeout()
1546 if (this->LinkState == CONNECTING)
1548 this->Instance->SNO->WriteToSnoMask('l',"CONNECT: Connection to \002"+myhost+"\002 timed out.");
1549 Link* MyLink = Utils->FindLink(myhost);
1551 Utils->DoFailOver(MyLink);
1555 void TreeSocket::OnClose()
1557 // Connection closed.
1558 // If the connection is fully up (state CONNECTED)
1559 // then propogate a netsplit to all peers.
1560 std::string quitserver = this->myhost;
1561 if (this->InboundServerName != "")
1563 quitserver = this->InboundServerName;
1565 TreeServer* s = Utils->FindServer(quitserver);
1568 Squit(s,"Remote host closed the connection");
1571 if (quitserver != "")
1573 this->Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' failed.",quitserver.c_str());
1574 time_t server_uptime = Instance->Time() - this->age;
1576 Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' was established for %s", quitserver.c_str(), Utils->Creator->TimeToStr(server_uptime).c_str());
1580 int TreeSocket::OnIncomingConnection(int newsock, char* ip)
1582 /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
1583 * or discovering if this port is the server port, we don't allow connections from any
1584 * IPs for which we don't have a link block.
1588 found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), ip) != Utils->ValidIPs.end());
1591 for (vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
1592 if (irc::sockets::MatchCIDR(ip, (*i).c_str()))
1597 this->Instance->SNO->WriteToSnoMask('l',"Server connection from %s denied (no link blocks with that IP address)", ip);
1603 TreeSocket* s = new TreeSocket(this->Utils, this->Instance, newsock, ip, this->Hook);
1604 s = s; /* Whinge whinge whinge, thats all GCC ever does. */