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.empty() ? 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);
249 TreeServer* remoteserver=Utils->FindServer(u->server);
252 if (this->Utils->quiet_bursts)
255 * If quiet bursts are enabled, and server is bursting or silent uline (i.e. services),
256 * then do nothing. -- w00t
260 Utils->FindRemoteBurstServer(remoteserver) ||
261 this->Instance->SilentULine(this->Instance->FindServerNamePtr(u->server))
269 this->Instance->SNO->WriteToSnoMask('o',"From %s: User %s (%s@%s) is now an IRC operator of type %s",u->server, u->nick,u->ident,u->host,irc::Spacify(opertype.c_str()));
274 /** Because Andy insists that services-compatible servers must
275 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
277 bool TreeSocket::ForceNick(const std::string &prefix, std::deque<std::string> ¶ms)
279 if (params.size() < 3)
282 userrec* u = this->Instance->FindNick(params[0]);
286 Utils->DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
290 std::deque<std::string> par;
291 par.push_back(params[1]);
293 if (!u->ForceNickChange(params[1].c_str()))
296 if (!u->ForceNickChange(u->uuid))
298 userrec::QuitUser(this->Instance, u, "Nickname collision");
303 u->age = atoi(params[2].c_str());
310 bool TreeSocket::OperQuit(const std::string &prefix, std::deque<std::string> ¶ms)
312 if (params.size() < 1)
315 userrec* u = this->Instance->FindNick(prefix);
319 u->SetOperQuit(params[0]);
320 params[0] = ":" + params[0];
321 Utils->DoOneToAllButSender(prefix,"OPERQUIT",params,prefix);
326 bool TreeSocket::ServiceJoin(const std::string &prefix, std::deque<std::string> ¶ms)
328 if (params.size() < 2)
331 if (!this->Instance->IsChannel(params[1].c_str()))
334 userrec* u = this->Instance->FindNick(params[0]);
338 /* only join if it's local, otherwise just pass it on! */
340 chanrec::JoinUser(this->Instance, u, params[1].c_str(), false, "", Instance->Time());
341 Utils->DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
346 bool TreeSocket::RemoteRehash(const std::string &prefix, std::deque<std::string> ¶ms)
348 if (params.size() < 1)
351 std::string servermask = params[0];
353 if (this->Instance->MatchText(this->Instance->Config->ServerName,servermask))
355 this->Instance->SNO->WriteToSnoMask('l',"Remote rehash initiated by \002"+prefix+"\002.");
356 this->Instance->RehashServer();
357 Utils->ReadConfiguration(false);
358 InitializeDisabledCommands(Instance->Config->DisabledCommands, Instance);
360 Utils->DoOneToAllButSender(prefix,"REHASH",params,prefix);
364 bool TreeSocket::RemoteKill(const std::string &prefix, std::deque<std::string> ¶ms)
366 if (params.size() != 2)
369 userrec* who = this->Instance->FindNick(params[0]);
373 /* Prepend kill source, if we don't have one */
374 if (*(params[1].c_str()) != '[')
376 params[1] = "[" + prefix + "] Killed (" + params[1] +")";
378 std::string reason = params[1];
379 params[1] = ":" + params[1];
380 Utils->DoOneToAllButSender(prefix,"KILL",params,prefix);
381 // NOTE: This is safe with kill hiding on, as RemoteKill is only reached if we have a server prefix.
382 // in short this is not executed for USERS.
383 who->Write(":%s KILL %s :%s (%s)", prefix.c_str(), who->nick, prefix.c_str(), reason.c_str());
384 userrec::QuitUser(this->Instance,who,reason);
389 bool TreeSocket::LocalPong(const std::string &prefix, std::deque<std::string> ¶ms)
391 if (params.size() < 1)
394 if (params.size() == 1)
396 TreeServer* ServerSource = Utils->FindServer(prefix);
399 ServerSource->SetPingFlag();
401 gettimeofday(&t, NULL);
402 long ts = (t.tv_sec * 1000) + (t.tv_usec / 1000);
403 ServerSource->rtt = ts - ServerSource->LastPingMsec;
408 std::string forwardto = params[1];
409 if (forwardto == this->Instance->Config->ServerName)
412 * this is a PONG for us
413 * if the prefix is a user, check theyre local, and if they are,
414 * dump the PONG reply back to their fd. If its a server, do nowt.
415 * Services might want to send these s->s, but we dont need to yet.
417 userrec* u = this->Instance->FindNick(prefix);
420 u->WriteServ("PONG %s %s",params[0].c_str(),params[1].c_str());
425 // not for us, pass it on :)
426 Utils->DoOneToOne(prefix,"PONG",params,forwardto);
433 bool TreeSocket::MetaData(const std::string &prefix, std::deque<std::string> ¶ms)
435 if (params.size() < 2)
437 else if (params.size() < 3)
438 params.push_back("");
439 TreeServer* ServerSource = Utils->FindServer(prefix);
442 Utils->SetRemoteBursting(ServerSource, false);
444 if (params[0] == "*")
446 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));
448 else if (*(params[0].c_str()) == '#')
450 chanrec* c = this->Instance->FindChan(params[0]);
453 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
456 else if (*(params[0].c_str()) != '#')
458 userrec* u = this->Instance->FindNick(params[0]);
461 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
466 params[2] = ":" + params[2];
467 Utils->DoOneToAllButSender(prefix,"METADATA",params,prefix);
471 bool TreeSocket::ServerVersion(const std::string &prefix, std::deque<std::string> ¶ms)
473 if (params.size() < 1)
476 TreeServer* ServerSource = Utils->FindServer(prefix);
480 ServerSource->SetVersion(params[0]);
482 params[0] = ":" + params[0];
483 Utils->DoOneToAllButSender(prefix,"VERSION",params,prefix);
487 bool TreeSocket::ChangeHost(const std::string &prefix, std::deque<std::string> ¶ms)
489 if (params.size() < 1)
491 userrec* u = this->Instance->FindNick(prefix);
495 u->ChangeDisplayedHost(params[0].c_str());
496 Utils->DoOneToAllButSender(prefix,"FHOST",params,u->server);
501 bool TreeSocket::AddLine(const std::string &prefix, std::deque<std::string> ¶ms)
503 if (params.size() < 6)
505 bool propogate = false;
507 Utils->lines_to_apply = 0;
508 switch (*(params[0].c_str()))
511 propogate = Instance->XLines->add_zline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
512 Instance->XLines->zline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
514 Utils->lines_to_apply |= APPLY_ZLINES;
517 propogate = Instance->XLines->add_qline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
518 Instance->XLines->qline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
520 Utils->lines_to_apply |= APPLY_QLINES;
523 propogate = Instance->XLines->add_eline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
524 Instance->XLines->eline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
527 propogate = Instance->XLines->add_gline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
528 Instance->XLines->gline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
530 Utils->lines_to_apply |= APPLY_GLINES;
533 propogate = Instance->XLines->add_kline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
535 Utils->lines_to_apply |= APPLY_KLINES;
538 /* Just in case... */
539 this->Instance->SNO->WriteToSnoMask('x',"\2WARNING\2: Invalid xline type '"+params[0]+"' sent by server "+prefix+", ignored!");
543 /* Send it on its way */
546 if (atoi(params[4].c_str()))
548 time_t c_requires_crap = ConvToInt(params[4]) + Instance->Time();
549 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());
553 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());
555 params[5] = ":" + params[5];
556 Utils->DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
560 Instance->XLines->apply_lines(Utils->lines_to_apply);
561 Utils->lines_to_apply = 0;
566 bool TreeSocket::ChangeName(const std::string &prefix, std::deque<std::string> ¶ms)
568 if (params.size() < 1)
570 userrec* u = this->Instance->FindNick(prefix);
573 u->ChangeName(params[0].c_str());
574 params[0] = ":" + params[0];
575 Utils->DoOneToAllButSender(prefix,"FNAME",params,u->server);
580 bool TreeSocket::Whois(const std::string &prefix, std::deque<std::string> ¶ms)
582 if (params.size() < 1)
584 userrec* u = this->Instance->FindNick(prefix);
587 // an incoming request
588 if (params.size() == 1)
590 userrec* x = this->Instance->FindNick(params[0]);
591 if ((x) && (IS_LOCAL(x)))
593 userrec* x = this->Instance->FindNick(params[0]);
596 snprintf(signon, MAXBUF, "%lu", (unsigned long)x->signon);
597 snprintf(idle, MAXBUF, "%lu", (unsigned long)abs((x->idle_lastmsg) - Instance->Time(true)));
598 std::deque<std::string> par;
599 par.push_back(prefix);
600 par.push_back(signon);
602 // ours, we're done, pass it BACK
603 Utils->DoOneToOne(params[0], "IDLE", par, u->server);
607 // not ours pass it on
609 Utils->DoOneToOne(prefix, "IDLE", params, x->server);
612 else if (params.size() == 3)
614 std::string who_did_the_whois = params[0];
615 userrec* who_to_send_to = this->Instance->FindNick(who_did_the_whois);
616 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
618 // an incoming reply to a whois we sent out
619 std::string nick_whoised = prefix;
620 unsigned long signon = atoi(params[1].c_str());
621 unsigned long idle = atoi(params[2].c_str());
622 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
624 do_whois(this->Instance, who_to_send_to, u, signon, idle, nick_whoised.c_str());
629 // not ours, pass it on
631 Utils->DoOneToOne(prefix, "IDLE", params, who_to_send_to->server);
638 bool TreeSocket::Push(const std::string &prefix, std::deque<std::string> ¶ms)
640 if (params.size() < 2)
642 userrec* u = this->Instance->FindNick(params[0]);
651 // continue the raw onwards
652 params[1] = ":" + params[1];
653 Utils->DoOneToOne(prefix,"PUSH",params,u->server);
658 bool TreeSocket::HandleSetTime(const std::string &prefix, std::deque<std::string> ¶ms)
660 if (!params.size() || !Utils->EnableTimeSync)
665 if ((params.size() == 2) && (params[1] == "FORCE"))
668 time_t them = atoi(params[0].c_str());
669 time_t us = Instance->Time(false);
671 time_t diff = them - us;
673 Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
675 if (force || (them != us))
677 time_t old = Instance->SetTimeDelta(diff);
678 Instance->Log(DEBUG, "TS (diff %d) from %s applied (old delta was %d)", diff, prefix.c_str(), old);
684 bool TreeSocket::Time(const std::string &prefix, std::deque<std::string> ¶ms)
686 // :source.server TIME remote.server sendernick
687 // :remote.server TIME source.server sendernick TS
688 if (params.size() == 2)
690 // someone querying our time?
691 if (this->Instance->Config->ServerName == params[0])
693 userrec* u = this->Instance->FindNick(params[1]);
696 params.push_back(ConvToStr(Instance->Time(false)));
698 Utils->DoOneToOne(this->Instance->Config->ServerName,"TIME",params,params[0]);
703 // not us, pass it on
704 userrec* u = this->Instance->FindNick(params[1]);
706 Utils->DoOneToOne(prefix,"TIME",params,params[0]);
709 else if (params.size() == 3)
711 // a response to a previous TIME
712 userrec* u = this->Instance->FindNick(params[1]);
713 if ((u) && (IS_LOCAL(u)))
715 time_t rawtime = atol(params[2].c_str());
716 struct tm * timeinfo;
717 timeinfo = localtime(&rawtime);
719 snprintf(tms,26,"%s",asctime(timeinfo));
721 u->WriteServ("391 %s %s :%s",u->nick,prefix.c_str(),tms);
726 Utils->DoOneToOne(prefix,"TIME",params,u->server);
732 bool TreeSocket::LocalPing(const std::string &prefix, std::deque<std::string> ¶ms)
734 if (params.size() < 1)
736 if (params.size() == 1)
738 std::string stufftobounce = params[0];
739 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" PONG "+stufftobounce);
744 std::string forwardto = params[1];
745 if (forwardto == this->Instance->Config->ServerName)
747 // this is a ping for us, send back PONG to the requesting server
748 params[1] = params[0];
749 params[0] = forwardto;
750 Utils->DoOneToOne(forwardto,"PONG",params,params[1]);
754 // not for us, pass it on :)
755 Utils->DoOneToOne(prefix,"PING",params,forwardto);
761 /** TODO: This creates a total mess of output and needs to really use irc::modestacker.
763 bool TreeSocket::RemoveStatus(const std::string &prefix, std::deque<std::string> ¶ms)
765 if (params.size() < 1)
767 chanrec* c = Instance->FindChan(params[0]);
770 for (char modeletter = 'A'; modeletter <= 'z'; modeletter++)
772 ModeHandler* mh = Instance->Modes->FindMode(modeletter, MODETYPE_CHANNEL);
780 bool TreeSocket::RemoteServer(const std::string &prefix, std::deque<std::string> ¶ms)
782 if (params.size() < 4)
784 std::string servername = params[0];
785 std::string password = params[1];
786 // hopcount is not used for a remote server, we calculate this ourselves
787 std::string description = params[3];
788 TreeServer* ParentOfThis = Utils->FindServer(prefix);
791 this->SendError("Protocol error - Introduced remote server from unknown server "+prefix);
794 TreeServer* CheckDupe = Utils->FindServer(servername);
797 this->SendError("Server "+servername+" already exists!");
798 this->Instance->SNO->WriteToSnoMask('l',"Server \2"+servername+"\2 being introduced from \2" + prefix + "\2 denied, already exists. Closing link with " + prefix);
801 Link* lnk = Utils->FindLink(servername);
802 TreeServer* Node = new TreeServer(this->Utils,this->Instance,servername,description,ParentOfThis,NULL, lnk ? lnk->Hidden : false);
803 ParentOfThis->AddChild(Node);
804 params[3] = ":" + params[3];
805 Utils->SetRemoteBursting(Node, true);
806 Utils->DoOneToAllButSender(prefix,"SERVER",params,prefix);
807 this->Instance->SNO->WriteToSnoMask('l',"Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
811 bool TreeSocket::ComparePass(const std::string &ours, const std::string &theirs)
813 if ((!strncmp(ours.c_str(), "HMAC-SHA256:", 12)) || (!strncmp(theirs.c_str(), "HMAC-SHA256:", 12)))
815 /* One or both of us specified hmac sha256, but we don't have sha256 module loaded!
816 * We can't allow this password as valid.
818 if (!Instance->FindModule("m_sha256.so") || !Utils->ChallengeResponse)
821 /* Straight string compare of hashes */
822 return ours == theirs;
825 /* Straight string compare of plaintext */
826 return ours == theirs;
829 bool TreeSocket::Outbound_Reply_Server(std::deque<std::string> ¶ms)
831 if (params.size() < 4)
834 irc::string servername = params[0].c_str();
835 std::string sname = params[0];
836 std::string password = params[1];
837 std::string description = params[3];
838 int hops = atoi(params[2].c_str());
840 this->InboundServerName = sname;
841 this->InboundDescription = description;
844 this->SendCapabilities();
848 this->SendError("Server too far away for authentication");
849 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
853 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
855 if ((x->Name == servername) && ((ComparePass(this->MakePass(x->RecvPass,this->GetOurChallenge()),password)) || (x->RecvPass == password && (this->GetTheirChallenge().empty()))))
857 TreeServer* CheckDupe = Utils->FindServer(sname);
860 this->SendError("Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
861 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
864 // Begin the sync here. this kickstarts the
865 // other side, waiting in WAIT_AUTH_2 state,
866 // into starting their burst, as it shows
868 this->LinkState = CONNECTED;
869 // we should add the details of this server now
870 // to the servers tree, as a child of the root
872 TreeServer* Node = new TreeServer(this->Utils,this->Instance,sname,description,Utils->TreeRoot,this,x->Hidden);
873 Utils->TreeRoot->AddChild(Node);
874 params[3] = ":" + params[3];
875 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,sname);
876 this->bursting = true;
881 this->SendError("Invalid credentials");
882 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
886 bool TreeSocket::Inbound_Server(std::deque<std::string> ¶ms)
888 if (params.size() < 4)
890 irc::string servername = params[0].c_str();
891 std::string sname = params[0];
892 std::string password = params[1];
893 std::string description = params[3];
894 int hops = atoi(params[2].c_str());
896 this->InboundServerName = sname;
897 this->InboundDescription = description;
900 this->SendCapabilities();
904 this->SendError("Server too far away for authentication");
905 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
909 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
911 if ((x->Name == servername) && ((ComparePass(this->MakePass(x->RecvPass,this->GetOurChallenge()),password) || x->RecvPass == password && (this->GetTheirChallenge().empty()))))
913 /* First check for instances of the server that are waiting between the inbound and outbound SERVER command */
914 TreeSocket* CheckDupeSocket = Utils->FindBurstingServer(sname);
917 /* If we find one, we abort the link to prevent a race condition */
918 this->SendError("Negotiation collision");
919 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists in a negotiating state.");
920 CheckDupeSocket->SendError("Negotiation collision");
921 Instance->SE->DelFd(CheckDupeSocket);
922 CheckDupeSocket->Close();
925 /* Now check for fully initialized instances of the server */
926 TreeServer* CheckDupe = Utils->FindServer(sname);
929 this->SendError("Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
930 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
933 this->Instance->SNO->WriteToSnoMask('l',"Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
936 std::string name = InspSocketNameRequest((Module*)Utils->Creator, this->Hook).Send();
937 this->Instance->SNO->WriteToSnoMask('l',"Connection from \2"+sname+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] using transport \2"+name+"\2");
940 Utils->AddBurstingServer(sname,this);
942 // this is good. Send our details: Our server name and description and hopcount of 0,
943 // along with the sendpass from this block.
944 this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+this->MakePass(x->SendPass, this->GetTheirChallenge())+" 0 :"+this->Instance->Config->ServerDesc);
945 // move to the next state, we are now waiting for THEM.
946 this->LinkState = WAIT_AUTH_2;
950 this->SendError("Invalid credentials");
951 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
955 void TreeSocket::Split(const std::string &line, std::deque<std::string> &n)
958 irc::tokenstream tokens(line);
960 while (tokens.GetToken(param))
968 bool TreeSocket::ProcessLine(std::string &line)
970 std::deque<std::string> params;
974 line = line.substr(0, line.find_first_of("\r\n"));
979 Instance->Log(DEBUG, "S[%d] <- %s", this->GetFd(), line.c_str());
981 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);
1026 irc::string error = "Invalid command in negotiation phase: " + command;
1027 this->SendError(assign(error));
1032 // Waiting for start of other side's netmerge to say they liked our
1034 if (command == "SERVER")
1036 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1040 else if (command == "BURST")
1042 if (params.size() && Utils->EnableTimeSync)
1044 bool we_have_delta = (Instance->Time(false) != Instance->Time(true));
1045 time_t them = atoi(params[0].c_str());
1046 time_t delta = them - Instance->Time(false);
1047 if ((delta < -600) || (delta > 600))
1049 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));
1050 SendError("Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than five minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
1053 else if ((delta < -30) || (delta > 30))
1055 Instance->SNO->WriteToSnoMask('l',"\2WARNING\2: Your clocks are out by %d seconds. Please consider synching your clocks.", abs(delta));
1058 if (!Utils->MasterTime && !we_have_delta)
1060 this->Instance->SetTimeDelta(delta);
1061 // Send this new timestamp to any other servers
1062 Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
1065 this->LinkState = CONNECTED;
1066 Link* lnk = Utils->FindLink(InboundServerName);
1067 Node = new TreeServer(this->Utils,this->Instance, InboundServerName, InboundDescription, Utils->TreeRoot, this, lnk ? lnk->Hidden : false);
1068 Utils->DelBurstingServer(this);
1069 Utils->TreeRoot->AddChild(Node);
1071 params.push_back(InboundServerName);
1072 params.push_back("*");
1073 params.push_back("1");
1074 params.push_back(":"+InboundDescription);
1075 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,InboundServerName);
1076 this->bursting = true;
1077 this->DoBurst(Node);
1079 else if (command == "ERROR")
1081 return this->Error(params);
1083 else if (command == "CAPAB")
1085 return this->Capab(params);
1090 this->SendError("Internal error -- listening socket accepted its own descriptor!!!");
1094 if (command == "SERVER")
1096 // another server we connected to, which was in WAIT_AUTH_1 state,
1097 // has just sent us their credentials. If we get this far, theyre
1098 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1099 // if we're happy with this, we should send our netburst which
1100 // kickstarts the merge.
1101 return this->Outbound_Reply_Server(params);
1103 else if (command == "ERROR")
1105 return this->Error(params);
1107 else if (command == "CAPAB")
1109 return this->Capab(params);
1113 // This is the 'authenticated' state, when all passwords
1114 // have been exchanged and anything past this point is taken
1117 if (!prefix.empty())
1119 std::string direction = prefix;
1121 userrec *t = this->Instance->FindUUID(prefix);
1124 userrec* t = this->Instance->FindNick(prefix);
1127 Instance->Log(DEBUG,"Ack, legacy command!");
1132 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) + Utils->PingFreq);
1147 route_back_again->SetPingFlag();
1151 prefix = this->GetName();
1154 if ((command == "MODE") && (params.size() >= 2))
1156 chanrec* channel = Instance->FindChan(params[0]);
1159 userrec* x = Instance->FindNick(prefix);
1162 if (warned.find(x->server) == warned.end())
1164 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);
1165 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());
1166 warned[x->server] = x->nick;
1172 if (command == "SVSMODE")
1174 /* Services expects us to implement
1175 * SVSMODE. In inspircd its the same as
1181 /* Yes, know, this is a mess. Its reasonably fast though as we're
1182 * working with std::string here.
1184 if (command == "UID")
1186 return this->ParseUID(prefix, params);
1188 else if (command == "FJOIN")
1190 TreeServer* ServerSource = Utils->FindServer(prefix);
1192 Utils->SetRemoteBursting(ServerSource, false);
1193 return this->ForceJoin(prefix,params);
1195 else if (command == "STATS")
1197 return this->Stats(prefix, params);
1199 else if (command == "MOTD")
1201 return this->Motd(prefix, params);
1203 else if (command == "KILL" && Utils->IsServer(prefix))
1205 return this->RemoteKill(prefix,params);
1207 else if (command == "MODULES")
1209 return this->Modules(prefix, params);
1211 else if (command == "ADMIN")
1213 return this->Admin(prefix, params);
1215 else if (command == "SERVER")
1217 return this->RemoteServer(prefix,params);
1219 else if (command == "ERROR")
1221 return this->Error(params);
1223 else if (command == "OPERTYPE")
1225 return this->OperType(prefix,params);
1227 else if (command == "FMODE")
1229 TreeServer* ServerSource = Utils->FindServer(prefix);
1231 Utils->SetRemoteBursting(ServerSource, false);
1232 return this->ForceMode(prefix,params);
1234 else if (command == "FTOPIC")
1236 return this->ForceTopic(prefix,params);
1238 else if (command == "REHASH")
1240 return this->RemoteRehash(prefix,params);
1242 else if (command == "METADATA")
1244 return this->MetaData(prefix,params);
1246 else if (command == "REMSTATUS")
1248 return this->RemoveStatus(prefix,params);
1250 else if (command == "PING")
1253 prefix = this->GetName();
1255 * We just got a ping from a server that's bursting.
1256 * This can't be right, so set them to not bursting, and
1257 * apply their lines.
1259 TreeServer* ServerSource = Utils->FindServer(prefix);
1261 Utils->SetRemoteBursting(ServerSource, false);
1265 this->bursting = false;
1266 Instance->XLines->apply_lines(Utils->lines_to_apply);
1267 Utils->lines_to_apply = 0;
1270 return this->LocalPing(prefix,params);
1272 else if (command == "PONG")
1275 prefix = this->GetName();
1277 * We just got a pong from a server that's bursting.
1278 * This can't be right, so set them to not bursting, and
1279 * apply their lines.
1281 TreeServer* ServerSource = Utils->FindServer(prefix);
1283 Utils->SetRemoteBursting(ServerSource, false);
1287 this->bursting = false;
1288 Instance->XLines->apply_lines(Utils->lines_to_apply);
1289 Utils->lines_to_apply = 0;
1292 return this->LocalPong(prefix,params);
1294 else if (command == "VERSION")
1296 return this->ServerVersion(prefix,params);
1298 else if (command == "FHOST")
1300 return this->ChangeHost(prefix,params);
1302 else if (command == "FNAME")
1304 return this->ChangeName(prefix,params);
1306 else if (command == "ADDLINE")
1308 TreeServer* ServerSource = Utils->FindServer(prefix);
1310 Utils->SetRemoteBursting(ServerSource, false);
1311 return this->AddLine(prefix,params);
1313 else if (command == "SVSNICK")
1317 prefix = this->GetName();
1319 return this->ForceNick(prefix,params);
1321 else if (command == "OPERQUIT")
1323 return this->OperQuit(prefix,params);
1325 else if (command == "IDLE")
1327 return this->Whois(prefix,params);
1329 else if (command == "PUSH")
1331 return this->Push(prefix,params);
1333 else if (command == "TIMESET")
1335 return this->HandleSetTime(prefix, params);
1337 else if (command == "TIME")
1339 return this->Time(prefix,params);
1341 else if ((command == "KICK") && (Utils->IsServer(prefix)))
1343 std::string sourceserv = this->myhost;
1344 if (params.size() == 3)
1346 userrec* user = this->Instance->FindNick(params[1]);
1347 chanrec* chan = this->Instance->FindChan(params[0]);
1350 if (!chan->ServerKickUser(user, params[2].c_str(), false))
1351 /* Yikes, the channels gone! */
1355 if (!this->InboundServerName.empty())
1357 sourceserv = this->InboundServerName;
1359 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1361 else if (command == "SVSJOIN")
1365 prefix = this->GetName();
1367 return this->ServiceJoin(prefix,params);
1369 else if (command == "SQUIT")
1371 if (params.size() == 2)
1373 this->Squit(Utils->FindServer(params[0]),params[1]);
1377 else if (command == "OPERNOTICE")
1379 std::string sourceserv = this->myhost;
1380 if (!this->InboundServerName.empty())
1381 sourceserv = this->InboundServerName;
1382 if (params.size() >= 1)
1383 Instance->WriteOpers("*** From " + sourceserv + ": " + params[0]);
1384 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1386 else if (command == "MODENOTICE")
1388 std::string sourceserv = this->myhost;
1389 if (!this->InboundServerName.empty())
1390 sourceserv = this->InboundServerName;
1391 if (params.size() >= 2)
1393 Instance->WriteMode(params[0].c_str(), WM_AND, "*** From %s: %s", sourceserv.c_str(), params[1].c_str());
1395 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1397 else if (command == "SNONOTICE")
1399 std::string sourceserv = this->myhost;
1400 if (!this->InboundServerName.empty())
1401 sourceserv = this->InboundServerName;
1402 if (params.size() >= 2)
1404 Instance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + sourceserv + ": "+ params[1]);
1406 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1408 else if (command == "ENDBURST")
1410 this->bursting = false;
1411 Instance->XLines->apply_lines(Utils->lines_to_apply);
1412 Utils->lines_to_apply = 0;
1413 std::string sourceserv = this->myhost;
1414 if (!this->InboundServerName.empty())
1415 sourceserv = this->InboundServerName;
1416 this->Instance->SNO->WriteToSnoMask('l',"Received end of netburst from \2%s\2",sourceserv.c_str());
1418 Event rmode((char*)sourceserv.c_str(), (Module*)Utils->Creator, "new_server");
1419 rmode.Send(Instance);
1426 * Not a special s2s command. Emulate the user doing it.
1427 * This saves us having a huge ugly command parser again.
1433 * First, let's find them by UID. If we don't find, try again
1434 * by nick (to catch legacy commands temporarily).
1435 * If we still don't .. carry on and pray. -- w00t
1437 userrec *who = this->Instance->FindUUID(prefix);
1441 userrec* who = this->Instance->FindNick(prefix);
1445 Instance->Log(DEBUG, "Glark! I got a legacy command!");
1449 std::string sourceserv = this->myhost;
1450 if (!this->InboundServerName.empty())
1452 sourceserv = this->InboundServerName;
1454 if ((!who) && (command == "MODE"))
1456 if (Utils->IsServer(prefix))
1458 const char* modelist[MAXPARAMETERS];
1459 for (size_t i = 0; i < params.size(); i++)
1460 modelist[i] = params[i].c_str();
1461 userrec* fake = new userrec(Instance);
1462 fake->SetFd(FD_MAGIC_NUMBER);
1463 this->Instance->SendMode(modelist, params.size(), fake);
1466 /* Hot potato! pass it on! */
1467 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1472 if ((command == "NICK") && (params.size() > 0))
1474 /* On nick messages, check that the nick doesnt
1475 * already exist here. If it does, kill their copy,
1478 userrec* x = this->Instance->FindNick(params[0]);
1479 if ((x) && (x != who))
1481 std::deque<std::string> p;
1482 p.push_back(params[0]);
1483 p.push_back(":Nickname collision ("+prefix+" -> "+params[0]+")");
1484 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
1486 p.push_back(prefix);
1487 p.push_back(":Nickname collision");
1488 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
1489 userrec::QuitUser(this->Instance,x,"Nickname collision ("+prefix+" -> "+params[0]+")");
1490 userrec* y = this->Instance->FindNick(prefix);
1493 userrec::QuitUser(this->Instance,y,"Nickname collision");
1495 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1499 target = who->server;
1500 const char* strparams[127];
1501 for (unsigned int q = 0; q < params.size(); q++)
1503 strparams[q] = params[q].c_str();
1505 switch (this->Instance->CallCommandHandler(command.c_str(), strparams, params.size(), who))
1508 this->SendError("Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
1515 /* CMD_SUCCESS and CMD_USER_DELETED fall through here */
1521 // its not a user. Its either a server, or somethings screwed up.
1522 if (Utils->IsServer(prefix))
1523 target = this->Instance->Config->ServerName;
1527 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1536 std::string TreeSocket::GetName()
1538 std::string sourceserv = this->myhost;
1539 if (!this->InboundServerName.empty())
1541 sourceserv = this->InboundServerName;
1546 void TreeSocket::OnTimeout()
1548 if (this->LinkState == CONNECTING)
1550 Utils->Creator->RemoteMessage(NULL, "CONNECT: Connection to \002%s\002 timed out.", myhost.c_str());
1551 Link* MyLink = Utils->FindLink(myhost);
1553 Utils->DoFailOver(MyLink);
1557 void TreeSocket::OnClose()
1559 if (this->LinkState == LISTENER)
1562 // Connection closed.
1563 // If the connection is fully up (state CONNECTED)
1564 // then propogate a netsplit to all peers.
1565 std::string quitserver = this->myhost;
1566 if (!this->InboundServerName.empty())
1568 quitserver = this->InboundServerName;
1570 TreeServer* s = Utils->FindServer(quitserver);
1573 Squit(s,"Remote host closed the connection");
1576 if (!quitserver.empty())
1578 Utils->Creator->RemoteMessage(NULL,"Connection to '\2%s\2' failed.",quitserver.c_str());
1579 time_t server_uptime = Instance->Time() - this->age;
1581 Utils->Creator->RemoteMessage(NULL,"Connection to '\2%s\2' was established for %s", quitserver.c_str(), Utils->Creator->TimeToStr(server_uptime).c_str());
1585 int TreeSocket::OnIncomingConnection(int newsock, char* ip)
1587 /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
1588 * or discovering if this port is the server port, we don't allow connections from any
1589 * IPs for which we don't have a link block.
1593 found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), ip) != Utils->ValidIPs.end());
1596 for (vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
1597 if (irc::sockets::MatchCIDR(ip, (*i).c_str()))
1602 Utils->Creator->RemoteMessage(NULL,"Server connection from %s denied (no link blocks with that IP address)", ip);
1608 TreeSocket* s = new TreeSocket(this->Utils, this->Instance, newsock, ip, this->Hook);
1609 s = s; /* Whinge whinge whinge, thats all GCC ever does. */