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 * ---------------------------------------------------
14 #include "configreader.h"
18 #include "commands/cmd_whois.h"
19 #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 int TreeSocket::WriteLine(std::string line)
39 Instance->Log(DEBUG, "-> %s", line.c_str());
41 return this->Write(line);
45 /* Handle ERROR command */
46 bool TreeSocket::Error(std::deque<std::string> ¶ms)
48 if (params.size() < 1)
50 this->Instance->SNO->WriteToSnoMask('l',"ERROR from %s: %s",(InboundServerName != "" ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
51 /* we will return false to cause the socket to close. */
55 bool TreeSocket::Modules(const std::string &prefix, std::deque<std::string> ¶ms)
60 if (!this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
62 /* Pass it on, not for us */
63 Utils->DoOneToOne(prefix, "MODULES", params, params[0]);
68 std::deque<std::string> par;
69 par.push_back(prefix);
72 userrec* source = this->Instance->FindNick(prefix);
76 for (unsigned int i = 0; i < Instance->Config->module_names.size(); i++)
78 Version V = Instance->modules[i]->GetVersion();
79 char modulename[MAXBUF];
80 char flagstate[MAXBUF];
82 if (V.Flags & VF_STATIC)
83 strlcat(flagstate,", static",MAXBUF);
84 if (V.Flags & VF_VENDOR)
85 strlcat(flagstate,", vendor",MAXBUF);
86 if (V.Flags & VF_COMMON)
87 strlcat(flagstate,", common",MAXBUF);
88 if (V.Flags & VF_SERVICEPROVIDER)
89 strlcat(flagstate,", service provider",MAXBUF);
91 strcpy(flagstate," <no flags>");
92 strlcpy(modulename,Instance->Config->module_names[i].c_str(),256);
95 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);
99 snprintf(strbuf, MAXBUF, "::%s 900 %s :%s",Instance->Config->ServerName,source->nick,ServerConfig::CleanFilename(modulename));
102 Utils->DoOneToOne(Instance->Config->ServerName, "PUSH", par, source->server);
104 snprintf(strbuf, MAXBUF, "::%s 901 %s :End of MODULES list", Instance->Config->ServerName, source->nick);
106 Utils->DoOneToOne(Instance->Config->ServerName, "PUSH", par, source->server);
110 /** remote MOTD. leet, huh? */
111 bool TreeSocket::Motd(const std::string &prefix, std::deque<std::string> ¶ms)
113 if (params.size() > 0)
115 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
117 /* It's for our server */
119 userrec* source = this->Instance->FindNick(prefix);
123 std::deque<std::string> par;
124 par.push_back(prefix);
127 if (!Instance->Config->MOTD.size())
129 par[1] = std::string("::")+Instance->Config->ServerName+" 422 "+source->nick+" :Message of the day file is missing.";
130 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
134 par[1] = std::string("::")+Instance->Config->ServerName+" 375 "+source->nick+" :"+Instance->Config->ServerName+" message of the day";
135 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
137 for (unsigned int i = 0; i < Instance->Config->MOTD.size(); i++)
139 par[1] = std::string("::")+Instance->Config->ServerName+" 372 "+source->nick+" :- "+Instance->Config->MOTD[i];
140 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
143 par[1] = std::string("::")+Instance->Config->ServerName+" 376 "+source->nick+" End of message of the day.";
144 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
150 userrec* source = this->Instance->FindNick(prefix);
152 Utils->DoOneToOne(prefix, "MOTD", params, params[0]);
158 /** remote ADMIN. leet, huh? */
159 bool TreeSocket::Admin(const std::string &prefix, std::deque<std::string> ¶ms)
161 if (params.size() > 0)
163 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
165 /* It's for our server */
167 userrec* source = this->Instance->FindNick(prefix);
170 std::deque<std::string> par;
171 par.push_back(prefix);
173 par[1] = std::string("::")+Instance->Config->ServerName+" 256 "+source->nick+" :Administrative info for "+Instance->Config->ServerName;
174 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
175 par[1] = std::string("::")+Instance->Config->ServerName+" 257 "+source->nick+" :Name - "+Instance->Config->AdminName;
176 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
177 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :Nickname - "+Instance->Config->AdminNick;
178 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
179 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :E-Mail - "+Instance->Config->AdminEmail;
180 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
186 userrec* source = this->Instance->FindNick(prefix);
188 Utils->DoOneToOne(prefix, "ADMIN", params, params[0]);
194 bool TreeSocket::Stats(const std::string &prefix, std::deque<std::string> ¶ms)
196 /* Get the reply to a STATS query if it matches this servername,
197 * and send it back as a load of PUSH queries
199 if (params.size() > 1)
201 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[1]))
203 /* It's for our server */
205 userrec* source = this->Instance->FindNick(prefix);
208 std::deque<std::string> par;
209 par.push_back(prefix);
211 DoStats(this->Instance, *(params[0].c_str()), source, results);
212 for (size_t i = 0; i < results.size(); i++)
214 par[1] = "::" + results[i];
215 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
222 userrec* source = this->Instance->FindNick(prefix);
224 Utils->DoOneToOne(prefix, "STATS", params, params[1]);
231 /** Because the core won't let users or even SERVERS set +o,
232 * we use the OPERTYPE command to do this.
234 bool TreeSocket::OperType(const std::string &prefix, std::deque<std::string> ¶ms)
236 if (params.size() != 1)
238 std::string opertype = params[0];
239 userrec* u = this->Instance->FindNick(prefix);
242 u->modes[UM_OPERATOR] = 1;
243 this->Instance->all_opers.push_back(u);
244 strlcpy(u->oper,opertype.c_str(),NICKMAX-1);
245 Utils->DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
246 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()));
251 /** Because Andy insists that services-compatible servers must
252 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
254 bool TreeSocket::ForceNick(const std::string &prefix, std::deque<std::string> ¶ms)
256 if (params.size() < 3)
259 userrec* u = this->Instance->FindNick(params[0]);
263 Utils->DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
266 std::deque<std::string> par;
267 par.push_back(params[1]);
268 if (!u->ForceNickChange(params[1].c_str()))
270 userrec::QuitUser(this->Instance, u, "Nickname collision");
273 u->age = atoi(params[2].c_str());
279 bool TreeSocket::OperQuit(const std::string &prefix, std::deque<std::string> ¶ms)
281 if (params.size() < 1)
284 userrec* u = this->Instance->FindNick(prefix);
288 Utils->DoOneToAllButSender(prefix,"OPERQUIT",params,prefix);
289 u->SetOperQuit(params[0]);
295 * Remote SQUIT (RSQUIT). Routing works similar to SVSNICK: Route it to the server that the target is connected to locally,
296 * then let that server do the dirty work (squit it!). Example:
297 * 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
299 bool TreeSocket::RemoteSquit(const std::string &prefix, std::deque<std::string> ¶ms)
301 /* ok.. :w00t RSQUIT jupe.barafranca.com :reason here */
302 if (params.size() < 2)
305 TreeServer* s = Utils->FindServerMask(params[0]);
309 if (s == Utils->TreeRoot)
311 this->Instance->SNO->WriteToSnoMask('l',"What the fuck, I recieved a remote SQUIT for myself? :< (from %s", prefix.c_str());
315 TreeSocket* sock = s->GetSocket();
319 /* it's locally connected, KILL IT! */
320 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());
321 sock->Squit(s,"Server quit by " + prefix + ": " + params[1]);
322 Instance->SE->DelFd(sock);
328 /* route the rsquit */
329 params[1] = ":" + params[1];
330 Utils->DoOneToOne(prefix, "RSQUIT", params, params[0]);
335 /* mother fucker! it doesn't exist */
341 bool TreeSocket::ServiceJoin(const std::string &prefix, std::deque<std::string> ¶ms)
343 if (params.size() < 2)
346 userrec* u = this->Instance->FindNick(params[0]);
350 /* only join if it's local, otherwise just pass it on! */
352 chanrec::JoinUser(this->Instance, u, params[1].c_str(), false, "", Instance->Time());
353 Utils->DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
358 bool TreeSocket::RemoteRehash(const std::string &prefix, std::deque<std::string> ¶ms)
360 if (params.size() < 1)
363 std::string servermask = params[0];
365 if (this->Instance->MatchText(this->Instance->Config->ServerName,servermask))
367 this->Instance->SNO->WriteToSnoMask('l',"Remote rehash initiated by \002"+prefix+"\002.");
368 this->Instance->RehashServer();
369 Utils->ReadConfiguration(false);
370 InitializeDisabledCommands(Instance->Config->DisabledCommands, Instance);
372 Utils->DoOneToAllButSender(prefix,"REHASH",params,prefix);
376 bool TreeSocket::RemoteKill(const std::string &prefix, std::deque<std::string> ¶ms)
378 if (params.size() != 2)
381 std::string nick = params[0];
382 userrec* u = this->Instance->FindNick(prefix);
383 userrec* who = this->Instance->FindNick(nick);
387 /* Prepend kill source, if we don't have one */
388 std::string sourceserv = prefix;
391 sourceserv = u->server;
393 if (*(params[1].c_str()) != '[')
395 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
397 std::string reason = params[1];
398 params[1] = ":" + params[1];
399 Utils->DoOneToAllButSender(prefix,"KILL",params,sourceserv);
400 who->Write(":%s KILL %s :%s (%s)", sourceserv.c_str(), who->nick, sourceserv.c_str(), reason.c_str());
401 userrec::QuitUser(this->Instance,who,reason);
406 bool TreeSocket::LocalPong(const std::string &prefix, std::deque<std::string> ¶ms)
408 if (params.size() < 1)
411 if (params.size() == 1)
413 TreeServer* ServerSource = Utils->FindServer(prefix);
416 ServerSource->SetPingFlag();
417 ServerSource->rtt = Instance->Time() - ServerSource->LastPing;
422 std::string forwardto = params[1];
423 if (forwardto == this->Instance->Config->ServerName)
426 * this is a PONG for us
427 * if the prefix is a user, check theyre local, and if they are,
428 * dump the PONG reply back to their fd. If its a server, do nowt.
429 * Services might want to send these s->s, but we dont need to yet.
431 userrec* u = this->Instance->FindNick(prefix);
434 u->WriteServ("PONG %s %s",params[0].c_str(),params[1].c_str());
439 // not for us, pass it on :)
440 Utils->DoOneToOne(prefix,"PONG",params,forwardto);
447 bool TreeSocket::MetaData(const std::string &prefix, std::deque<std::string> ¶ms)
449 if (params.size() < 2)
451 else if (params.size() < 3)
452 params.push_back("");
453 TreeServer* ServerSource = Utils->FindServer(prefix);
456 if (params[0] == "*")
458 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));
460 else if (*(params[0].c_str()) == '#')
462 chanrec* c = this->Instance->FindChan(params[0]);
465 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
468 else if (*(params[0].c_str()) != '#')
470 userrec* u = this->Instance->FindNick(params[0]);
473 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
478 params[2] = ":" + params[2];
479 Utils->DoOneToAllButSender(prefix,"METADATA",params,prefix);
483 bool TreeSocket::ServerVersion(const std::string &prefix, std::deque<std::string> ¶ms)
485 if (params.size() < 1)
488 TreeServer* ServerSource = Utils->FindServer(prefix);
492 ServerSource->SetVersion(params[0]);
494 params[0] = ":" + params[0];
495 Utils->DoOneToAllButSender(prefix,"VERSION",params,prefix);
499 bool TreeSocket::ChangeHost(const std::string &prefix, std::deque<std::string> ¶ms)
501 if (params.size() < 1)
503 userrec* u = this->Instance->FindNick(prefix);
507 u->ChangeDisplayedHost(params[0].c_str());
508 Utils->DoOneToAllButSender(prefix,"FHOST",params,u->server);
513 bool TreeSocket::AddLine(const std::string &prefix, std::deque<std::string> ¶ms)
515 if (params.size() < 6)
517 bool propogate = false;
519 Utils->lines_to_apply = 0;
520 switch (*(params[0].c_str()))
523 propogate = Instance->XLines->add_zline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
524 Instance->XLines->zline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
526 Utils->lines_to_apply |= APPLY_ZLINES;
529 propogate = Instance->XLines->add_qline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
530 Instance->XLines->qline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
532 Utils->lines_to_apply |= APPLY_QLINES;
535 propogate = Instance->XLines->add_eline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
536 Instance->XLines->eline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
539 propogate = Instance->XLines->add_gline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
540 Instance->XLines->gline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
542 Utils->lines_to_apply |= APPLY_GLINES;
545 propogate = Instance->XLines->add_kline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
547 Utils->lines_to_apply |= APPLY_KLINES;
550 /* Just in case... */
551 this->Instance->SNO->WriteToSnoMask('x',"\2WARNING\2: Invalid xline type '"+params[0]+"' sent by server "+prefix+", ignored!");
555 /* Send it on its way */
558 if (atoi(params[4].c_str()))
560 time_t c_requires_crap = ConvToInt(params[4]) + Instance->Time();
561 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());
565 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());
567 params[5] = ":" + params[5];
568 Utils->DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
572 Instance->XLines->apply_lines(Utils->lines_to_apply);
573 Utils->lines_to_apply = 0;
578 bool TreeSocket::ChangeName(const std::string &prefix, std::deque<std::string> ¶ms)
580 if (params.size() < 1)
582 userrec* u = this->Instance->FindNick(prefix);
585 u->ChangeName(params[0].c_str());
586 params[0] = ":" + params[0];
587 Utils->DoOneToAllButSender(prefix,"FNAME",params,u->server);
592 bool TreeSocket::Whois(const std::string &prefix, std::deque<std::string> ¶ms)
594 if (params.size() < 1)
596 userrec* u = this->Instance->FindNick(prefix);
599 // an incoming request
600 if (params.size() == 1)
602 userrec* x = this->Instance->FindNick(params[0]);
603 if ((x) && (IS_LOCAL(x)))
605 userrec* x = this->Instance->FindNick(params[0]);
608 snprintf(signon, MAXBUF, "%lu", (unsigned long)x->signon);
609 snprintf(idle, MAXBUF, "%lu", (unsigned long)abs((x->idle_lastmsg) - Instance->Time(true)));
610 std::deque<std::string> par;
611 par.push_back(prefix);
612 par.push_back(signon);
614 // ours, we're done, pass it BACK
615 Utils->DoOneToOne(params[0], "IDLE", par, u->server);
619 // not ours pass it on
621 Utils->DoOneToOne(prefix, "IDLE", params, x->server);
624 else if (params.size() == 3)
626 std::string who_did_the_whois = params[0];
627 userrec* who_to_send_to = this->Instance->FindNick(who_did_the_whois);
628 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
630 // an incoming reply to a whois we sent out
631 std::string nick_whoised = prefix;
632 unsigned long signon = atoi(params[1].c_str());
633 unsigned long idle = atoi(params[2].c_str());
634 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
636 do_whois(this->Instance, who_to_send_to, u, signon, idle, nick_whoised.c_str());
641 // not ours, pass it on
643 Utils->DoOneToOne(prefix, "IDLE", params, who_to_send_to->server);
650 bool TreeSocket::Push(const std::string &prefix, std::deque<std::string> ¶ms)
652 if (params.size() < 2)
654 userrec* u = this->Instance->FindNick(params[0]);
663 // continue the raw onwards
664 params[1] = ":" + params[1];
665 Utils->DoOneToOne(prefix,"PUSH",params,u->server);
670 bool TreeSocket::HandleSetTime(const std::string &prefix, std::deque<std::string> ¶ms)
672 if (!params.size() || !Utils->EnableTimeSync)
677 if ((params.size() == 2) && (params[1] == "FORCE"))
680 time_t them = atoi(params[0].c_str());
681 time_t us = Instance->Time(false);
683 time_t diff = them - us;
685 Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
687 if (force || (them != us))
689 time_t old = Instance->SetTimeDelta(diff);
690 Instance->Log(DEBUG, "TS (diff %d) from %s applied (old delta was %d)", diff, prefix.c_str(), old);
696 bool TreeSocket::Time(const std::string &prefix, std::deque<std::string> ¶ms)
698 // :source.server TIME remote.server sendernick
699 // :remote.server TIME source.server sendernick TS
700 if (params.size() == 2)
702 // someone querying our time?
703 if (this->Instance->Config->ServerName == params[0])
705 userrec* u = this->Instance->FindNick(params[1]);
708 params.push_back(ConvToStr(Instance->Time(false)));
710 Utils->DoOneToOne(this->Instance->Config->ServerName,"TIME",params,params[0]);
715 // not us, pass it on
716 userrec* u = this->Instance->FindNick(params[1]);
718 Utils->DoOneToOne(prefix,"TIME",params,params[0]);
721 else if (params.size() == 3)
723 // a response to a previous TIME
724 userrec* u = this->Instance->FindNick(params[1]);
725 if ((u) && (IS_LOCAL(u)))
727 time_t rawtime = atol(params[2].c_str());
728 struct tm * timeinfo;
729 timeinfo = localtime(&rawtime);
731 snprintf(tms,26,"%s",asctime(timeinfo));
733 u->WriteServ("391 %s %s :%s",u->nick,prefix.c_str(),tms);
738 Utils->DoOneToOne(prefix,"TIME",params,u->server);
744 bool TreeSocket::LocalPing(const std::string &prefix, std::deque<std::string> ¶ms)
746 if (params.size() < 1)
748 if (params.size() == 1)
750 std::string stufftobounce = params[0];
751 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" PONG "+stufftobounce);
756 std::string forwardto = params[1];
757 if (forwardto == this->Instance->Config->ServerName)
759 // this is a ping for us, send back PONG to the requesting server
760 params[1] = params[0];
761 params[0] = forwardto;
762 Utils->DoOneToOne(forwardto,"PONG",params,params[1]);
766 // not for us, pass it on :)
767 Utils->DoOneToOne(prefix,"PING",params,forwardto);
773 /** TODO: This creates a total mess of output and needs to really use irc::modestacker.
775 bool TreeSocket::RemoveStatus(const std::string &prefix, std::deque<std::string> ¶ms)
777 if (params.size() < 1)
779 chanrec* c = Instance->FindChan(params[0]);
782 for (char modeletter = 'A'; modeletter <= 'z'; modeletter++)
784 ModeHandler* mh = Instance->Modes->FindMode(modeletter, MODETYPE_CHANNEL);
792 bool TreeSocket::RemoteServer(const std::string &prefix, std::deque<std::string> ¶ms)
794 if (params.size() < 4)
796 std::string servername = params[0];
797 std::string password = params[1];
798 // hopcount is not used for a remote server, we calculate this ourselves
799 std::string description = params[3];
800 TreeServer* ParentOfThis = Utils->FindServer(prefix);
803 this->SendError("Protocol error - Introduced remote server from unknown server "+prefix);
806 TreeServer* CheckDupe = Utils->FindServer(servername);
809 this->SendError("Server "+servername+" already exists!");
810 this->Instance->SNO->WriteToSnoMask('l',"Server \2"+servername+"\2 being introduced from \2" + prefix + "\2 denied, already exists. Closing link with " + prefix);
813 Link* lnk = Utils->FindLink(servername);
814 TreeServer* Node = new TreeServer(this->Utils,this->Instance,servername,description,ParentOfThis,NULL, lnk ? lnk->Hidden : false);
815 ParentOfThis->AddChild(Node);
816 params[3] = ":" + params[3];
817 Utils->DoOneToAllButSender(prefix,"SERVER",params,prefix);
818 this->Instance->SNO->WriteToSnoMask('l',"Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
822 bool TreeSocket::ComparePass(const std::string &ours, const std::string &theirs)
824 if ((!strncmp(ours.c_str(), "HMAC-SHA256:", 12)) || (!strncmp(theirs.c_str(), "HMAC-SHA256:", 12)))
826 /* One or both of us specified hmac sha256, but we don't have sha256 module loaded!
827 * We can't allow this password as valid.
829 if (!Instance->FindModule("m_sha256.so") || !Utils->ChallengeResponse)
832 /* Straight string compare of hashes */
833 return ours == theirs;
836 /* Straight string compare of plaintext */
837 return ours == theirs;
840 bool TreeSocket::Outbound_Reply_Server(std::deque<std::string> ¶ms)
842 if (params.size() < 4)
845 irc::string servername = params[0].c_str();
846 std::string sname = params[0];
847 std::string password = params[1];
848 std::string description = params[3];
849 int hops = atoi(params[2].c_str());
851 this->InboundServerName = sname;
852 this->InboundDescription = description;
856 this->SendError("Server too far away for authentication");
857 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
861 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
863 if ((x->Name == servername) && ((ComparePass(this->MakePass(x->RecvPass,this->GetOurChallenge()),password)) || (x->RecvPass == password && (this->GetTheirChallenge().empty()))))
865 TreeServer* CheckDupe = Utils->FindServer(sname);
868 this->SendError("Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
869 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
872 // Begin the sync here. this kickstarts the
873 // other side, waiting in WAIT_AUTH_2 state,
874 // into starting their burst, as it shows
876 this->LinkState = CONNECTED;
877 // we should add the details of this server now
878 // to the servers tree, as a child of the root
880 TreeServer* Node = new TreeServer(this->Utils,this->Instance,sname,description,Utils->TreeRoot,this,x->Hidden);
881 Utils->TreeRoot->AddChild(Node);
882 params[3] = ":" + params[3];
883 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,sname);
884 this->bursting = true;
889 this->SendError("Invalid credentials");
890 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
894 bool TreeSocket::Inbound_Server(std::deque<std::string> ¶ms)
896 if (params.size() < 4)
898 irc::string servername = params[0].c_str();
899 std::string sname = params[0];
900 std::string password = params[1];
901 std::string description = params[3];
902 int hops = atoi(params[2].c_str());
904 this->InboundServerName = sname;
905 this->InboundDescription = description;
909 this->SendError("Server too far away for authentication");
910 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
914 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
916 if ((x->Name == servername) && ((ComparePass(this->MakePass(x->RecvPass,this->GetOurChallenge()),password) || x->RecvPass == password && (this->GetTheirChallenge().empty()))))
918 /* First check for instances of the server that are waiting between the inbound and outbound SERVER command */
919 TreeSocket* CheckDupeSocket = Utils->FindBurstingServer(sname);
922 /* If we find one, we abort the link to prevent a race condition */
923 this->SendError("Negotiation collision");
924 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists in a negotiating state.");
925 CheckDupeSocket->SendError("Negotiation collision");
926 Instance->SE->DelFd(CheckDupeSocket);
927 CheckDupeSocket->Close();
928 delete CheckDupeSocket;
931 /* Now check for fully initialized instances of the server */
932 TreeServer* CheckDupe = Utils->FindServer(sname);
935 this->SendError("Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
936 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
939 this->Instance->SNO->WriteToSnoMask('l',"Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
942 std::string name = InspSocketNameRequest((Module*)Utils->Creator, this->Hook).Send();
943 this->Instance->SNO->WriteToSnoMask('l',"Connection from \2"+sname+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] using transport \2"+name+"\2");
946 Utils->AddBurstingServer(sname,this);
948 // this is good. Send our details: Our server name and description and hopcount of 0,
949 // along with the sendpass from this block.
950 this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+this->MakePass(x->SendPass, this->GetTheirChallenge())+" 0 :"+this->Instance->Config->ServerDesc);
951 // move to the next state, we are now waiting for THEM.
952 this->LinkState = WAIT_AUTH_2;
956 this->SendError("Invalid credentials");
957 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
961 void TreeSocket::Split(const std::string &line, std::deque<std::string> &n)
964 irc::tokenstream tokens(line);
966 while (tokens.GetToken(param))
971 bool TreeSocket::ProcessLine(std::string &line)
973 std::deque<std::string> params;
977 line = line.substr(0, line.find_first_of("\r\n"));
982 Instance->Log(DEBUG, "<- %s", line.c_str());
984 this->Split(line.c_str(),params);
986 if ((params[0][0] == ':') && (params.size() > 1))
988 prefix = params[0].substr(1);
991 command = params[0].c_str();
993 switch (this->LinkState)
998 // Waiting for SERVER command from remote server. Server initiating
999 // the connection sends the first SERVER command, listening server
1000 // replies with theirs if its happy, then if the initiator is happy,
1001 // it starts to send its net sync, which starts the merge, otherwise
1002 // it sends an ERROR.
1003 if (command == "PASS")
1005 /* Silently ignored */
1007 else if (command == "SERVER")
1009 return this->Inbound_Server(params);
1011 else if (command == "ERROR")
1013 return this->Error(params);
1015 else if (command == "USER")
1017 this->SendError("Client connections to this port are prohibited.");
1020 else if (command == "CAPAB")
1022 return this->Capab(params);
1024 else if ((command == "U") || (command == "S"))
1026 this->SendError("Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
1031 irc::string error = "Invalid command in negotiation phase: " + command;
1032 this->SendError(assign(error));
1037 // Waiting for start of other side's netmerge to say they liked our
1039 if (command == "SERVER")
1041 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1045 else if ((command == "U") || (command == "S"))
1047 this->SendError("Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
1050 else if (command == "BURST")
1052 if (params.size() && Utils->EnableTimeSync)
1054 bool we_have_delta = (Instance->Time(false) != Instance->Time(true));
1055 time_t them = atoi(params[0].c_str());
1056 time_t delta = them - Instance->Time(false);
1057 if ((delta < -300) || (delta > 300))
1059 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));
1060 SendError("Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than ten minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
1063 else if ((delta < -30) || (delta > 30))
1065 Instance->SNO->WriteToSnoMask('l',"\2WARNING\2: Your clocks are out by %d seconds. Please consider synching your clocks.", abs(delta));
1068 if (!Utils->MasterTime && !we_have_delta)
1070 this->Instance->SetTimeDelta(delta);
1071 // Send this new timestamp to any other servers
1072 Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
1075 this->LinkState = CONNECTED;
1076 Link* lnk = Utils->FindLink(InboundServerName);
1077 Node = new TreeServer(this->Utils,this->Instance, InboundServerName, InboundDescription, Utils->TreeRoot, this, lnk ? lnk->Hidden : false);
1078 Utils->DelBurstingServer(this);
1079 Utils->TreeRoot->AddChild(Node);
1081 params.push_back(InboundServerName);
1082 params.push_back("*");
1083 params.push_back("1");
1084 params.push_back(":"+InboundDescription);
1085 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,InboundServerName);
1086 this->bursting = true;
1087 this->DoBurst(Node);
1089 else if (command == "ERROR")
1091 return this->Error(params);
1093 else if (command == "CAPAB")
1095 return this->Capab(params);
1100 this->SendError("Internal error -- listening socket accepted its own descriptor!!!");
1104 if (command == "SERVER")
1106 // another server we connected to, which was in WAIT_AUTH_1 state,
1107 // has just sent us their credentials. If we get this far, theyre
1108 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1109 // if we're happy with this, we should send our netburst which
1110 // kickstarts the merge.
1111 return this->Outbound_Reply_Server(params);
1113 else if (command == "ERROR")
1115 return this->Error(params);
1117 else if (command == "CAPAB")
1119 return this->Capab(params);
1123 // This is the 'authenticated' state, when all passwords
1124 // have been exchanged and anything past this point is taken
1129 std::string direction = prefix;
1130 userrec* t = this->Instance->FindNick(prefix);
1133 direction = t->server;
1135 TreeServer* route_back_again = Utils->BestRouteTo(direction);
1136 if ((!route_back_again) || (route_back_again->GetSocket() != this))
1138 if (route_back_again)
1139 Instance->Log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
1143 * When there is activity on the socket, reset the ping counter so
1144 * that we're not wasting bandwidth pinging an active server.
1146 route_back_again->SetNextPingTime(time(NULL) + 60);
1147 route_back_again->SetPingFlag();
1150 if ((command == "MODE") && (params.size() >= 2))
1152 chanrec* channel = Instance->FindChan(params[0]);
1155 userrec* x = Instance->FindNick(prefix);
1158 Instance->Log(DEFAULT,
1159 "WARNING: I revceived modes '%s' from another server '%s'. This is not compliant with InspIRCd. Please check that server for bugs.",
1160 params[1].c_str(), x->server);
1161 Instance->SNO->WriteToSnoMask('d', "WARNING: The server %s is sending nonstandard modes: '%s MODE %s' and may cause desyncs.",
1162 x->server, x->nick, params[1].c_str());
1167 if (command == "SVSMODE")
1169 /* Services expects us to implement
1170 * SVSMODE. In inspircd its the same as
1175 std::string target = "";
1176 /* Yes, know, this is a mess. Its reasonably fast though as we're
1177 * working with std::string here.
1179 if ((command == "NICK") && (params.size() >= 8))
1181 return this->IntroduceClient(prefix,params);
1183 else if (command == "FJOIN")
1185 return this->ForceJoin(prefix,params);
1187 else if (command == "STATS")
1189 return this->Stats(prefix, params);
1191 else if (command == "MOTD")
1193 return this->Motd(prefix, params);
1195 else if (command == "MODULES")
1197 return this->Modules(prefix, params);
1199 else if (command == "ADMIN")
1201 return this->Admin(prefix, params);
1203 else if (command == "SERVER")
1205 return this->RemoteServer(prefix,params);
1207 else if (command == "ERROR")
1209 return this->Error(params);
1211 else if (command == "OPERTYPE")
1213 return this->OperType(prefix,params);
1215 else if (command == "FMODE")
1217 return this->ForceMode(prefix,params);
1219 else if (command == "KILL")
1221 return this->RemoteKill(prefix,params);
1223 else if (command == "FTOPIC")
1225 return this->ForceTopic(prefix,params);
1227 else if (command == "REHASH")
1229 return this->RemoteRehash(prefix,params);
1231 else if (command == "METADATA")
1233 return this->MetaData(prefix,params);
1235 else if (command == "REMSTATUS")
1237 return this->RemoveStatus(prefix,params);
1239 else if (command == "PING")
1242 * We just got a ping from a server that's bursting.
1243 * This can't be right, so set them to not bursting, and
1244 * apply their lines.
1248 this->bursting = false;
1249 Instance->XLines->apply_lines(Utils->lines_to_apply);
1250 Utils->lines_to_apply = 0;
1254 prefix = this->GetName();
1256 return this->LocalPing(prefix,params);
1258 else if (command == "PONG")
1261 * We just got a pong from a server that's bursting.
1262 * This can't be right, so set them to not bursting, and
1263 * apply their lines.
1267 this->bursting = false;
1268 Instance->XLines->apply_lines(Utils->lines_to_apply);
1269 Utils->lines_to_apply = 0;
1273 prefix = this->GetName();
1275 return this->LocalPong(prefix,params);
1277 else if (command == "VERSION")
1279 return this->ServerVersion(prefix,params);
1281 else if (command == "FHOST")
1283 return this->ChangeHost(prefix,params);
1285 else if (command == "FNAME")
1287 return this->ChangeName(prefix,params);
1289 else if (command == "ADDLINE")
1291 return this->AddLine(prefix,params);
1293 else if (command == "SVSNICK")
1297 prefix = this->GetName();
1299 return this->ForceNick(prefix,params);
1301 else if (command == "OPERQUIT")
1303 return this->OperQuit(prefix,params);
1305 else if (command == "RSQUIT")
1307 return this->RemoteSquit(prefix, params);
1309 else if (command == "IDLE")
1311 return this->Whois(prefix,params);
1313 else if (command == "PUSH")
1315 return this->Push(prefix,params);
1317 else if (command == "TIMESET")
1319 return this->HandleSetTime(prefix, params);
1321 else if (command == "TIME")
1323 return this->Time(prefix,params);
1325 else if ((command == "KICK") && (Utils->IsServer(prefix)))
1327 std::string sourceserv = this->myhost;
1328 if (params.size() == 3)
1330 userrec* user = this->Instance->FindNick(params[1]);
1331 chanrec* chan = this->Instance->FindChan(params[0]);
1334 if (!chan->ServerKickUser(user, params[2].c_str(), false))
1335 /* Yikes, the channels gone! */
1339 if (this->InboundServerName != "")
1341 sourceserv = this->InboundServerName;
1343 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1345 else if (command == "SVSJOIN")
1349 prefix = this->GetName();
1351 return this->ServiceJoin(prefix,params);
1353 else if (command == "SQUIT")
1355 if (params.size() == 2)
1357 this->Squit(Utils->FindServer(params[0]),params[1]);
1361 else if (command == "OPERNOTICE")
1363 std::string sourceserv = this->myhost;
1364 if (this->InboundServerName != "")
1365 sourceserv = this->InboundServerName;
1366 if (params.size() >= 1)
1367 Instance->WriteOpers("*** From " + sourceserv + ": " + params[0]);
1368 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1370 else if (command == "MODENOTICE")
1372 std::string sourceserv = this->myhost;
1373 if (this->InboundServerName != "")
1374 sourceserv = this->InboundServerName;
1375 if (params.size() >= 2)
1377 Instance->WriteMode(params[0].c_str(), WM_AND, "*** From %s: %s", sourceserv.c_str(), params[1].c_str());
1379 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1381 else if (command == "SNONOTICE")
1383 std::string sourceserv = this->myhost;
1384 if (this->InboundServerName != "")
1385 sourceserv = this->InboundServerName;
1386 if (params.size() >= 2)
1388 Instance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + sourceserv + ": "+ params[1]);
1390 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1392 else if (command == "ENDBURST")
1394 this->bursting = false;
1395 Instance->XLines->apply_lines(Utils->lines_to_apply);
1396 Utils->lines_to_apply = 0;
1397 std::string sourceserv = this->myhost;
1398 if (this->InboundServerName != "")
1400 sourceserv = this->InboundServerName;
1402 this->Instance->SNO->WriteToSnoMask('l',"Received end of netburst from \2%s\2",sourceserv.c_str());
1404 Event rmode((char*)sourceserv.c_str(), (Module*)Utils->Creator, "new_server");
1405 rmode.Send(Instance);
1411 // not a special inter-server command.
1412 // Emulate the actual user doing the command,
1413 // this saves us having a huge ugly parser.
1414 userrec* who = this->Instance->FindNick(prefix);
1415 std::string sourceserv = this->myhost;
1416 if (this->InboundServerName != "")
1418 sourceserv = this->InboundServerName;
1420 if ((!who) && (command == "MODE"))
1422 if (Utils->IsServer(prefix))
1424 const char* modelist[127];
1425 for (size_t i = 0; i < params.size(); i++)
1426 modelist[i] = params[i].c_str();
1427 userrec* fake = new userrec(Instance);
1428 fake->SetFd(FD_MAGIC_NUMBER);
1429 this->Instance->SendMode(modelist, params.size(), fake);
1432 /* Hot potato! pass it on! */
1433 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1438 if ((command == "NICK") && (params.size() > 0))
1440 /* On nick messages, check that the nick doesnt
1441 * already exist here. If it does, kill their copy,
1444 userrec* x = this->Instance->FindNick(params[0]);
1445 if ((x) && (x != who))
1447 std::deque<std::string> p;
1448 p.push_back(params[0]);
1449 p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
1450 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
1452 p.push_back(prefix);
1453 p.push_back("Nickname collision");
1454 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
1455 userrec::QuitUser(this->Instance,x,"Nickname collision ("+prefix+" -> "+params[0]+")");
1456 userrec* y = this->Instance->FindNick(prefix);
1459 userrec::QuitUser(this->Instance,y,"Nickname collision");
1461 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1465 target = who->server;
1466 const char* strparams[127];
1467 for (unsigned int q = 0; q < params.size(); q++)
1469 strparams[q] = params[q].c_str();
1471 switch (this->Instance->CallCommandHandler(command.c_str(), strparams, params.size(), who))
1474 this->SendError("Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
1481 /* CMD_SUCCESS and CMD_USER_DELETED fall through here */
1487 // its not a user. Its either a server, or somethings screwed up.
1488 if (Utils->IsServer(prefix))
1489 target = this->Instance->Config->ServerName;
1493 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1502 std::string TreeSocket::GetName()
1504 std::string sourceserv = this->myhost;
1505 if (this->InboundServerName != "")
1507 sourceserv = this->InboundServerName;
1512 void TreeSocket::OnTimeout()
1514 if (this->LinkState == CONNECTING)
1516 this->Instance->SNO->WriteToSnoMask('l',"CONNECT: Connection to \002"+myhost+"\002 timed out.");
1517 Link* MyLink = Utils->FindLink(myhost);
1519 Utils->DoFailOver(MyLink);
1523 void TreeSocket::OnClose()
1525 // Connection closed.
1526 // If the connection is fully up (state CONNECTED)
1527 // then propogate a netsplit to all peers.
1528 std::string quitserver = this->myhost;
1529 if (this->InboundServerName != "")
1531 quitserver = this->InboundServerName;
1533 TreeServer* s = Utils->FindServer(quitserver);
1536 Squit(s,"Remote host closed the connection");
1539 if (quitserver != "")
1540 this->Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' failed.",quitserver.c_str());
1543 int TreeSocket::OnIncomingConnection(int newsock, char* ip)
1545 /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
1546 * or discovering if this port is the server port, we don't allow connections from any
1547 * IPs for which we don't have a link block.
1551 found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), ip) != Utils->ValidIPs.end());
1554 for (vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
1555 if (irc::sockets::MatchCIDR(ip, (*i).c_str()))
1560 this->Instance->SNO->WriteToSnoMask('l',"Server connection from %s denied (no link blocks with that IP address)", ip);
1566 TreeSocket* s = new TreeSocket(this->Utils, this->Instance, newsock, ip, this->Hook);
1567 s = s; /* Whinge whinge whinge, thats all GCC ever does. */