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);
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);
297 bool TreeSocket::ServiceJoin(const std::string &prefix, std::deque<std::string> ¶ms)
299 if (params.size() < 2)
302 userrec* u = this->Instance->FindNick(params[0]);
306 /* only join if it's local, otherwise just pass it on! */
308 chanrec::JoinUser(this->Instance, u, params[1].c_str(), false, "", Instance->Time());
309 Utils->DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
314 bool TreeSocket::RemoteRehash(const std::string &prefix, std::deque<std::string> ¶ms)
316 if (params.size() < 1)
319 std::string servermask = params[0];
321 if (this->Instance->MatchText(this->Instance->Config->ServerName,servermask))
323 this->Instance->SNO->WriteToSnoMask('l',"Remote rehash initiated by \002"+prefix+"\002.");
324 this->Instance->RehashServer();
325 Utils->ReadConfiguration(false);
326 InitializeDisabledCommands(Instance->Config->DisabledCommands, Instance);
328 Utils->DoOneToAllButSender(prefix,"REHASH",params,prefix);
332 bool TreeSocket::RemoteKill(const std::string &prefix, std::deque<std::string> ¶ms)
334 if (params.size() != 2)
337 userrec* who = this->Instance->FindNick(params[0]);
341 /* Prepend kill source, if we don't have one */
342 if (*(params[1].c_str()) != '[')
344 params[1] = "[" + prefix + "] Killed (" + params[1] +")";
346 std::string reason = params[1];
347 params[1] = ":" + params[1];
348 Utils->DoOneToAllButSender(prefix,"KILL",params,prefix);
349 who->Write(":%s KILL %s :%s (%s)", prefix.c_str(), who->nick, prefix.c_str(), reason.c_str());
350 userrec::QuitUser(this->Instance,who,reason);
355 bool TreeSocket::LocalPong(const std::string &prefix, std::deque<std::string> ¶ms)
357 if (params.size() < 1)
360 if (params.size() == 1)
362 TreeServer* ServerSource = Utils->FindServer(prefix);
365 ServerSource->SetPingFlag();
366 ServerSource->rtt = Instance->Time() - ServerSource->LastPing;
371 std::string forwardto = params[1];
372 if (forwardto == this->Instance->Config->ServerName)
375 * this is a PONG for us
376 * if the prefix is a user, check theyre local, and if they are,
377 * dump the PONG reply back to their fd. If its a server, do nowt.
378 * Services might want to send these s->s, but we dont need to yet.
380 userrec* u = this->Instance->FindNick(prefix);
383 u->WriteServ("PONG %s %s",params[0].c_str(),params[1].c_str());
388 // not for us, pass it on :)
389 Utils->DoOneToOne(prefix,"PONG",params,forwardto);
396 bool TreeSocket::MetaData(const std::string &prefix, std::deque<std::string> ¶ms)
398 if (params.size() < 2)
400 else if (params.size() < 3)
401 params.push_back("");
402 TreeServer* ServerSource = Utils->FindServer(prefix);
405 Utils->SetRemoteBursting(ServerSource, false);
407 if (params[0] == "*")
409 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));
411 else if (*(params[0].c_str()) == '#')
413 chanrec* c = this->Instance->FindChan(params[0]);
416 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
419 else if (*(params[0].c_str()) != '#')
421 userrec* u = this->Instance->FindNick(params[0]);
424 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
429 params[2] = ":" + params[2];
430 Utils->DoOneToAllButSender(prefix,"METADATA",params,prefix);
434 bool TreeSocket::ServerVersion(const std::string &prefix, std::deque<std::string> ¶ms)
436 if (params.size() < 1)
439 TreeServer* ServerSource = Utils->FindServer(prefix);
443 ServerSource->SetVersion(params[0]);
445 params[0] = ":" + params[0];
446 Utils->DoOneToAllButSender(prefix,"VERSION",params,prefix);
450 bool TreeSocket::ChangeHost(const std::string &prefix, std::deque<std::string> ¶ms)
452 if (params.size() < 1)
454 userrec* u = this->Instance->FindNick(prefix);
458 u->ChangeDisplayedHost(params[0].c_str());
459 Utils->DoOneToAllButSender(prefix,"FHOST",params,u->server);
464 bool TreeSocket::AddLine(const std::string &prefix, std::deque<std::string> ¶ms)
466 if (params.size() < 6)
468 bool propogate = false;
470 Utils->lines_to_apply = 0;
471 switch (*(params[0].c_str()))
474 propogate = Instance->XLines->add_zline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
475 Instance->XLines->zline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
477 Utils->lines_to_apply |= APPLY_ZLINES;
480 propogate = Instance->XLines->add_qline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
481 Instance->XLines->qline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
483 Utils->lines_to_apply |= APPLY_QLINES;
486 propogate = Instance->XLines->add_eline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
487 Instance->XLines->eline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
490 propogate = Instance->XLines->add_gline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
491 Instance->XLines->gline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
493 Utils->lines_to_apply |= APPLY_GLINES;
496 propogate = Instance->XLines->add_kline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
498 Utils->lines_to_apply |= APPLY_KLINES;
501 /* Just in case... */
502 this->Instance->SNO->WriteToSnoMask('x',"\2WARNING\2: Invalid xline type '"+params[0]+"' sent by server "+prefix+", ignored!");
506 /* Send it on its way */
509 if (atoi(params[4].c_str()))
511 time_t c_requires_crap = ConvToInt(params[4]) + Instance->Time();
512 this->Instance->SNO->WriteToSnoMask('x',"%s Added %cLINE on %s to expire on %s (%s).",prefix.c_str(),*(params[0].c_str()),params[1].c_str(),Instance->TimeString(c_requires_crap).c_str(),params[5].c_str());
516 this->Instance->SNO->WriteToSnoMask('x',"%s Added permenant %cLINE on %s (%s).",prefix.c_str(),*(params[0].c_str()),params[1].c_str(),params[5].c_str());
518 params[5] = ":" + params[5];
519 Utils->DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
523 Instance->XLines->apply_lines(Utils->lines_to_apply);
524 Utils->lines_to_apply = 0;
529 bool TreeSocket::ChangeName(const std::string &prefix, std::deque<std::string> ¶ms)
531 if (params.size() < 1)
533 userrec* u = this->Instance->FindNick(prefix);
536 u->ChangeName(params[0].c_str());
537 params[0] = ":" + params[0];
538 Utils->DoOneToAllButSender(prefix,"FNAME",params,u->server);
543 bool TreeSocket::Whois(const std::string &prefix, std::deque<std::string> ¶ms)
545 if (params.size() < 1)
547 userrec* u = this->Instance->FindNick(prefix);
550 // an incoming request
551 if (params.size() == 1)
553 userrec* x = this->Instance->FindNick(params[0]);
554 if ((x) && (IS_LOCAL(x)))
556 userrec* x = this->Instance->FindNick(params[0]);
559 snprintf(signon, MAXBUF, "%lu", (unsigned long)x->signon);
560 snprintf(idle, MAXBUF, "%lu", (unsigned long)abs((x->idle_lastmsg) - Instance->Time(true)));
561 std::deque<std::string> par;
562 par.push_back(prefix);
563 par.push_back(signon);
565 // ours, we're done, pass it BACK
566 Utils->DoOneToOne(params[0], "IDLE", par, u->server);
570 // not ours pass it on
572 Utils->DoOneToOne(prefix, "IDLE", params, x->server);
575 else if (params.size() == 3)
577 std::string who_did_the_whois = params[0];
578 userrec* who_to_send_to = this->Instance->FindNick(who_did_the_whois);
579 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
581 // an incoming reply to a whois we sent out
582 std::string nick_whoised = prefix;
583 unsigned long signon = atoi(params[1].c_str());
584 unsigned long idle = atoi(params[2].c_str());
585 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
587 do_whois(this->Instance, who_to_send_to, u, signon, idle, nick_whoised.c_str());
592 // not ours, pass it on
594 Utils->DoOneToOne(prefix, "IDLE", params, who_to_send_to->server);
601 bool TreeSocket::Push(const std::string &prefix, std::deque<std::string> ¶ms)
603 if (params.size() < 2)
605 userrec* u = this->Instance->FindNick(params[0]);
614 // continue the raw onwards
615 params[1] = ":" + params[1];
616 Utils->DoOneToOne(prefix,"PUSH",params,u->server);
621 bool TreeSocket::HandleSetTime(const std::string &prefix, std::deque<std::string> ¶ms)
623 if (!params.size() || !Utils->EnableTimeSync)
628 if ((params.size() == 2) && (params[1] == "FORCE"))
631 time_t them = atoi(params[0].c_str());
632 time_t us = Instance->Time(false);
634 time_t diff = them - us;
636 Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
638 if (force || (them != us))
640 time_t old = Instance->SetTimeDelta(diff);
641 Instance->Log(DEBUG, "TS (diff %d) from %s applied (old delta was %d)", diff, prefix.c_str(), old);
647 bool TreeSocket::Time(const std::string &prefix, std::deque<std::string> ¶ms)
649 // :source.server TIME remote.server sendernick
650 // :remote.server TIME source.server sendernick TS
651 if (params.size() == 2)
653 // someone querying our time?
654 if (this->Instance->Config->ServerName == params[0])
656 userrec* u = this->Instance->FindNick(params[1]);
659 params.push_back(ConvToStr(Instance->Time(false)));
661 Utils->DoOneToOne(this->Instance->Config->ServerName,"TIME",params,params[0]);
666 // not us, pass it on
667 userrec* u = this->Instance->FindNick(params[1]);
669 Utils->DoOneToOne(prefix,"TIME",params,params[0]);
672 else if (params.size() == 3)
674 // a response to a previous TIME
675 userrec* u = this->Instance->FindNick(params[1]);
676 if ((u) && (IS_LOCAL(u)))
678 time_t rawtime = atol(params[2].c_str());
679 struct tm * timeinfo;
680 timeinfo = localtime(&rawtime);
682 snprintf(tms,26,"%s",asctime(timeinfo));
684 u->WriteServ("391 %s %s :%s",u->nick,prefix.c_str(),tms);
689 Utils->DoOneToOne(prefix,"TIME",params,u->server);
695 bool TreeSocket::LocalPing(const std::string &prefix, std::deque<std::string> ¶ms)
697 if (params.size() < 1)
699 if (params.size() == 1)
701 std::string stufftobounce = params[0];
702 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" PONG "+stufftobounce);
707 std::string forwardto = params[1];
708 if (forwardto == this->Instance->Config->ServerName)
710 // this is a ping for us, send back PONG to the requesting server
711 params[1] = params[0];
712 params[0] = forwardto;
713 Utils->DoOneToOne(forwardto,"PONG",params,params[1]);
717 // not for us, pass it on :)
718 Utils->DoOneToOne(prefix,"PING",params,forwardto);
724 /** TODO: This creates a total mess of output and needs to really use irc::modestacker.
726 bool TreeSocket::RemoveStatus(const std::string &prefix, std::deque<std::string> ¶ms)
728 if (params.size() < 1)
730 chanrec* c = Instance->FindChan(params[0]);
733 for (char modeletter = 'A'; modeletter <= 'z'; modeletter++)
735 ModeHandler* mh = Instance->Modes->FindMode(modeletter, MODETYPE_CHANNEL);
743 bool TreeSocket::RemoteServer(const std::string &prefix, std::deque<std::string> ¶ms)
745 if (params.size() < 4)
747 std::string servername = params[0];
748 std::string password = params[1];
749 // hopcount is not used for a remote server, we calculate this ourselves
750 std::string description = params[3];
751 TreeServer* ParentOfThis = Utils->FindServer(prefix);
754 this->SendError("Protocol error - Introduced remote server from unknown server "+prefix);
757 TreeServer* CheckDupe = Utils->FindServer(servername);
760 this->SendError("Server "+servername+" already exists!");
761 this->Instance->SNO->WriteToSnoMask('l',"Server \2"+servername+"\2 being introduced from \2" + prefix + "\2 denied, already exists. Closing link with " + prefix);
764 Link* lnk = Utils->FindLink(servername);
765 TreeServer* Node = new TreeServer(this->Utils,this->Instance,servername,description,ParentOfThis,NULL, lnk ? lnk->Hidden : false);
766 ParentOfThis->AddChild(Node);
767 params[3] = ":" + params[3];
768 Utils->SetRemoteBursting(Node, true);
769 Utils->DoOneToAllButSender(prefix,"SERVER",params,prefix);
770 this->Instance->SNO->WriteToSnoMask('l',"Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
774 bool TreeSocket::ComparePass(const std::string &ours, const std::string &theirs)
776 if ((!strncmp(ours.c_str(), "HMAC-SHA256:", 12)) || (!strncmp(theirs.c_str(), "HMAC-SHA256:", 12)))
778 /* One or both of us specified hmac sha256, but we don't have sha256 module loaded!
779 * We can't allow this password as valid.
781 if (!Instance->FindModule("m_sha256.so") || !Utils->ChallengeResponse)
784 /* Straight string compare of hashes */
785 return ours == theirs;
788 /* Straight string compare of plaintext */
789 return ours == theirs;
792 bool TreeSocket::Outbound_Reply_Server(std::deque<std::string> ¶ms)
794 if (params.size() < 4)
797 irc::string servername = params[0].c_str();
798 std::string sname = params[0];
799 std::string password = params[1];
800 std::string description = params[3];
801 int hops = atoi(params[2].c_str());
803 this->InboundServerName = sname;
804 this->InboundDescription = description;
808 this->SendError("Server too far away for authentication");
809 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
813 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
815 if ((x->Name == servername) && ((ComparePass(this->MakePass(x->RecvPass,this->GetOurChallenge()),password)) || (x->RecvPass == password && (this->GetTheirChallenge().empty()))))
817 TreeServer* CheckDupe = Utils->FindServer(sname);
820 this->SendError("Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
821 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
824 // Begin the sync here. this kickstarts the
825 // other side, waiting in WAIT_AUTH_2 state,
826 // into starting their burst, as it shows
828 this->LinkState = CONNECTED;
829 // we should add the details of this server now
830 // to the servers tree, as a child of the root
832 TreeServer* Node = new TreeServer(this->Utils,this->Instance,sname,description,Utils->TreeRoot,this,x->Hidden);
833 Utils->TreeRoot->AddChild(Node);
834 params[3] = ":" + params[3];
835 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,sname);
836 this->bursting = true;
841 this->SendError("Invalid credentials");
842 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
846 bool TreeSocket::Inbound_Server(std::deque<std::string> ¶ms)
848 if (params.size() < 4)
850 irc::string servername = params[0].c_str();
851 std::string sname = params[0];
852 std::string password = params[1];
853 std::string description = params[3];
854 int hops = atoi(params[2].c_str());
856 this->InboundServerName = sname;
857 this->InboundDescription = description;
861 this->SendError("Server too far away for authentication");
862 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
866 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
868 if ((x->Name == servername) && ((ComparePass(this->MakePass(x->RecvPass,this->GetOurChallenge()),password) || x->RecvPass == password && (this->GetTheirChallenge().empty()))))
870 /* First check for instances of the server that are waiting between the inbound and outbound SERVER command */
871 TreeSocket* CheckDupeSocket = Utils->FindBurstingServer(sname);
874 /* If we find one, we abort the link to prevent a race condition */
875 this->SendError("Negotiation collision");
876 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists in a negotiating state.");
877 CheckDupeSocket->SendError("Negotiation collision");
878 Instance->SE->DelFd(CheckDupeSocket);
879 CheckDupeSocket->Close();
880 delete CheckDupeSocket;
883 /* Now check for fully initialized instances of the server */
884 TreeServer* CheckDupe = Utils->FindServer(sname);
887 this->SendError("Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
888 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
891 this->Instance->SNO->WriteToSnoMask('l',"Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
894 std::string name = InspSocketNameRequest((Module*)Utils->Creator, this->Hook).Send();
895 this->Instance->SNO->WriteToSnoMask('l',"Connection from \2"+sname+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] using transport \2"+name+"\2");
898 Utils->AddBurstingServer(sname,this);
900 // this is good. Send our details: Our server name and description and hopcount of 0,
901 // along with the sendpass from this block.
902 this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+this->MakePass(x->SendPass, this->GetTheirChallenge())+" 0 :"+this->Instance->Config->ServerDesc);
903 // move to the next state, we are now waiting for THEM.
904 this->LinkState = WAIT_AUTH_2;
908 this->SendError("Invalid credentials");
909 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
913 void TreeSocket::Split(const std::string &line, std::deque<std::string> &n)
916 irc::tokenstream tokens(line);
918 while (tokens.GetToken(param))
926 bool TreeSocket::ProcessLine(std::string &line)
928 std::deque<std::string> params;
932 line = line.substr(0, line.find_first_of("\r\n"));
937 Instance->Log(DEBUG, "S[%d] <- %s", this->GetFd(), line.c_str());
939 this->Split(line.c_str(),params);
944 if ((params[0][0] == ':') && (params.size() > 1))
946 prefix = params[0].substr(1);
949 command = params[0].c_str();
951 switch (this->LinkState)
956 // Waiting for SERVER command from remote server. Server initiating
957 // the connection sends the first SERVER command, listening server
958 // replies with theirs if its happy, then if the initiator is happy,
959 // it starts to send its net sync, which starts the merge, otherwise
960 // it sends an ERROR.
961 if (command == "PASS")
963 /* Silently ignored */
965 else if (command == "SERVER")
967 return this->Inbound_Server(params);
969 else if (command == "ERROR")
971 return this->Error(params);
973 else if (command == "USER")
975 this->SendError("Client connections to this port are prohibited.");
978 else if (command == "CAPAB")
980 return this->Capab(params);
982 else if ((command == "U") || (command == "S"))
984 this->SendError("Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
989 irc::string error = "Invalid command in negotiation phase: " + command;
990 this->SendError(assign(error));
995 // Waiting for start of other side's netmerge to say they liked our
997 if (command == "SERVER")
999 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1003 else if ((command == "U") || (command == "S"))
1005 this->SendError("Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
1008 else if (command == "BURST")
1010 if (params.size() && Utils->EnableTimeSync)
1012 bool we_have_delta = (Instance->Time(false) != Instance->Time(true));
1013 time_t them = atoi(params[0].c_str());
1014 time_t delta = them - Instance->Time(false);
1015 if ((delta < -300) || (delta > 300))
1017 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));
1018 SendError("Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than five minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
1021 else if ((delta < -30) || (delta > 30))
1023 Instance->SNO->WriteToSnoMask('l',"\2WARNING\2: Your clocks are out by %d seconds. Please consider synching your clocks.", abs(delta));
1026 if (!Utils->MasterTime && !we_have_delta)
1028 this->Instance->SetTimeDelta(delta);
1029 // Send this new timestamp to any other servers
1030 Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
1033 this->LinkState = CONNECTED;
1034 Link* lnk = Utils->FindLink(InboundServerName);
1035 Node = new TreeServer(this->Utils,this->Instance, InboundServerName, InboundDescription, Utils->TreeRoot, this, lnk ? lnk->Hidden : false);
1036 Utils->DelBurstingServer(this);
1037 Utils->TreeRoot->AddChild(Node);
1039 params.push_back(InboundServerName);
1040 params.push_back("*");
1041 params.push_back("1");
1042 params.push_back(":"+InboundDescription);
1043 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,InboundServerName);
1044 this->bursting = true;
1045 this->DoBurst(Node);
1047 else if (command == "ERROR")
1049 return this->Error(params);
1051 else if (command == "CAPAB")
1053 return this->Capab(params);
1058 this->SendError("Internal error -- listening socket accepted its own descriptor!!!");
1062 if (command == "SERVER")
1064 // another server we connected to, which was in WAIT_AUTH_1 state,
1065 // has just sent us their credentials. If we get this far, theyre
1066 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1067 // if we're happy with this, we should send our netburst which
1068 // kickstarts the merge.
1069 return this->Outbound_Reply_Server(params);
1071 else if (command == "ERROR")
1073 return this->Error(params);
1075 else if (command == "CAPAB")
1077 return this->Capab(params);
1081 // This is the 'authenticated' state, when all passwords
1082 // have been exchanged and anything past this point is taken
1085 if (!prefix.empty())
1087 std::string direction = prefix;
1088 userrec* t = this->Instance->FindNick(prefix);
1091 direction = t->server;
1093 TreeServer* route_back_again = Utils->BestRouteTo(direction);
1094 if ((!route_back_again) || (route_back_again->GetSocket() != this))
1096 if (route_back_again)
1097 Instance->Log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
1101 * When there is activity on the socket, reset the ping counter so
1102 * that we're not wasting bandwidth pinging an active server.
1104 route_back_again->SetNextPingTime(time(NULL) + 60);
1105 route_back_again->SetPingFlag();
1109 prefix = this->GetName();
1112 if ((command == "MODE") && (params.size() >= 2))
1114 chanrec* channel = Instance->FindChan(params[0]);
1117 userrec* x = Instance->FindNick(prefix);
1120 if (warned.find(x->server) == warned.end())
1122 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);
1123 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());
1124 warned[x->server] = x->nick;
1130 if (command == "SVSMODE")
1132 /* Services expects us to implement
1133 * SVSMODE. In inspircd its the same as
1139 /* Yes, know, this is a mess. Its reasonably fast though as we're
1140 * working with std::string here.
1142 if ((command == "NICK") && (params.size() >= 8))
1144 return this->IntroduceClient(prefix,params);
1146 else if (command == "FJOIN")
1148 TreeServer* ServerSource = Utils->FindServer(prefix);
1150 Utils->SetRemoteBursting(ServerSource, false);
1151 return this->ForceJoin(prefix,params);
1153 else if (command == "STATS")
1155 return this->Stats(prefix, params);
1157 else if (command == "MOTD")
1159 return this->Motd(prefix, params);
1161 else if (command == "KILL" && Utils->IsServer(prefix))
1163 return this->RemoteKill(prefix,params);
1165 else if (command == "MODULES")
1167 return this->Modules(prefix, params);
1169 else if (command == "ADMIN")
1171 return this->Admin(prefix, params);
1173 else if (command == "SERVER")
1175 return this->RemoteServer(prefix,params);
1177 else if (command == "ERROR")
1179 return this->Error(params);
1181 else if (command == "OPERTYPE")
1183 return this->OperType(prefix,params);
1185 else if (command == "FMODE")
1187 TreeServer* ServerSource = Utils->FindServer(prefix);
1189 Utils->SetRemoteBursting(ServerSource, false);
1190 return this->ForceMode(prefix,params);
1192 else if (command == "FTOPIC")
1194 return this->ForceTopic(prefix,params);
1196 else if (command == "REHASH")
1198 return this->RemoteRehash(prefix,params);
1200 else if (command == "METADATA")
1202 return this->MetaData(prefix,params);
1204 else if (command == "REMSTATUS")
1206 return this->RemoveStatus(prefix,params);
1208 else if (command == "PING")
1211 prefix = this->GetName();
1213 * We just got a ping from a server that's bursting.
1214 * This can't be right, so set them to not bursting, and
1215 * apply their lines.
1217 TreeServer* ServerSource = Utils->FindServer(prefix);
1219 Utils->SetRemoteBursting(ServerSource, false);
1223 this->bursting = false;
1224 Instance->XLines->apply_lines(Utils->lines_to_apply);
1225 Utils->lines_to_apply = 0;
1228 return this->LocalPing(prefix,params);
1230 else if (command == "PONG")
1233 prefix = this->GetName();
1235 * We just got a pong from a server that's bursting.
1236 * This can't be right, so set them to not bursting, and
1237 * apply their lines.
1239 TreeServer* ServerSource = Utils->FindServer(prefix);
1241 Utils->SetRemoteBursting(ServerSource, false);
1245 this->bursting = false;
1246 Instance->XLines->apply_lines(Utils->lines_to_apply);
1247 Utils->lines_to_apply = 0;
1250 return this->LocalPong(prefix,params);
1252 else if (command == "VERSION")
1254 return this->ServerVersion(prefix,params);
1256 else if (command == "FHOST")
1258 return this->ChangeHost(prefix,params);
1260 else if (command == "FNAME")
1262 return this->ChangeName(prefix,params);
1264 else if (command == "ADDLINE")
1266 TreeServer* ServerSource = Utils->FindServer(prefix);
1268 Utils->SetRemoteBursting(ServerSource, false);
1269 return this->AddLine(prefix,params);
1271 else if (command == "SVSNICK")
1275 prefix = this->GetName();
1277 return this->ForceNick(prefix,params);
1279 else if (command == "OPERQUIT")
1281 return this->OperQuit(prefix,params);
1283 else if (command == "IDLE")
1285 return this->Whois(prefix,params);
1287 else if (command == "PUSH")
1289 return this->Push(prefix,params);
1291 else if (command == "TIMESET")
1293 return this->HandleSetTime(prefix, params);
1295 else if (command == "TIME")
1297 return this->Time(prefix,params);
1299 else if ((command == "KICK") && (Utils->IsServer(prefix)))
1301 std::string sourceserv = this->myhost;
1302 if (params.size() == 3)
1304 userrec* user = this->Instance->FindNick(params[1]);
1305 chanrec* chan = this->Instance->FindChan(params[0]);
1308 if (!chan->ServerKickUser(user, params[2].c_str(), false))
1309 /* Yikes, the channels gone! */
1313 if (!this->InboundServerName.empty())
1315 sourceserv = this->InboundServerName;
1317 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1319 else if (command == "SVSJOIN")
1323 prefix = this->GetName();
1325 return this->ServiceJoin(prefix,params);
1327 else if (command == "SQUIT")
1329 if (params.size() == 2)
1331 this->Squit(Utils->FindServer(params[0]),params[1]);
1335 else if (command == "OPERNOTICE")
1337 std::string sourceserv = this->myhost;
1338 if (!this->InboundServerName.empty())
1339 sourceserv = this->InboundServerName;
1340 if (params.size() >= 1)
1341 Instance->WriteOpers("*** From " + sourceserv + ": " + params[0]);
1342 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1344 else if (command == "MODENOTICE")
1346 std::string sourceserv = this->myhost;
1347 if (!this->InboundServerName.empty())
1348 sourceserv = this->InboundServerName;
1349 if (params.size() >= 2)
1351 Instance->WriteMode(params[0].c_str(), WM_AND, "*** From %s: %s", sourceserv.c_str(), params[1].c_str());
1353 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1355 else if (command == "SNONOTICE")
1357 std::string sourceserv = this->myhost;
1358 if (!this->InboundServerName.empty())
1359 sourceserv = this->InboundServerName;
1360 if (params.size() >= 2)
1362 Instance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + sourceserv + ": "+ params[1]);
1364 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1366 else if (command == "ENDBURST")
1368 this->bursting = false;
1369 Instance->XLines->apply_lines(Utils->lines_to_apply);
1370 Utils->lines_to_apply = 0;
1371 std::string sourceserv = this->myhost;
1372 if (!this->InboundServerName.empty())
1373 sourceserv = this->InboundServerName;
1374 this->Instance->SNO->WriteToSnoMask('l',"Received end of netburst from \2%s\2",sourceserv.c_str());
1376 Event rmode((char*)sourceserv.c_str(), (Module*)Utils->Creator, "new_server");
1377 rmode.Send(Instance);
1383 // not a special inter-server command.
1384 // Emulate the actual user doing the command,
1385 // this saves us having a huge ugly parser.
1386 userrec* who = this->Instance->FindNick(prefix);
1387 std::string sourceserv = this->myhost;
1388 if (!this->InboundServerName.empty())
1390 sourceserv = this->InboundServerName;
1392 if ((!who) && (command == "MODE"))
1394 if (Utils->IsServer(prefix))
1396 const char* modelist[127];
1397 for (size_t i = 0; i < params.size(); i++)
1398 modelist[i] = params[i].c_str();
1399 userrec* fake = new userrec(Instance);
1400 fake->SetFd(FD_MAGIC_NUMBER);
1401 this->Instance->SendMode(modelist, params.size(), fake);
1404 /* Hot potato! pass it on! */
1405 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1410 if ((command == "NICK") && (params.size() > 0))
1412 /* On nick messages, check that the nick doesnt
1413 * already exist here. If it does, kill their copy,
1416 userrec* x = this->Instance->FindNick(params[0]);
1417 if ((x) && (x != who))
1419 std::deque<std::string> p;
1420 p.push_back(params[0]);
1421 p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
1422 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
1424 p.push_back(prefix);
1425 p.push_back("Nickname collision");
1426 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
1427 userrec::QuitUser(this->Instance,x,"Nickname collision ("+prefix+" -> "+params[0]+")");
1428 userrec* y = this->Instance->FindNick(prefix);
1431 userrec::QuitUser(this->Instance,y,"Nickname collision");
1433 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1437 target = who->server;
1438 const char* strparams[127];
1439 for (unsigned int q = 0; q < params.size(); q++)
1441 strparams[q] = params[q].c_str();
1443 switch (this->Instance->CallCommandHandler(command.c_str(), strparams, params.size(), who))
1446 this->SendError("Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
1453 /* CMD_SUCCESS and CMD_USER_DELETED fall through here */
1459 // its not a user. Its either a server, or somethings screwed up.
1460 if (Utils->IsServer(prefix))
1461 target = this->Instance->Config->ServerName;
1465 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1474 std::string TreeSocket::GetName()
1476 std::string sourceserv = this->myhost;
1477 if (!this->InboundServerName.empty())
1479 sourceserv = this->InboundServerName;
1484 void TreeSocket::OnTimeout()
1486 if (this->LinkState == CONNECTING)
1488 this->Instance->SNO->WriteToSnoMask('l',"CONNECT: Connection to \002"+myhost+"\002 timed out.");
1489 Link* MyLink = Utils->FindLink(myhost);
1491 Utils->DoFailOver(MyLink);
1495 void TreeSocket::OnClose()
1497 // Connection closed.
1498 // If the connection is fully up (state CONNECTED)
1499 // then propogate a netsplit to all peers.
1500 std::string quitserver = this->myhost;
1501 if (!this->InboundServerName.empty())
1503 quitserver = this->InboundServerName;
1505 TreeServer* s = Utils->FindServer(quitserver);
1508 Squit(s,"Remote host closed the connection");
1511 if (!quitserver.empty())
1513 this->Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' failed.",quitserver.c_str());
1514 time_t server_uptime = Instance->Time() - this->age;
1516 Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' was established for %s", quitserver.c_str(), Utils->Creator->TimeToStr(server_uptime).c_str());
1520 int TreeSocket::OnIncomingConnection(int newsock, char* ip)
1522 /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
1523 * or discovering if this port is the server port, we don't allow connections from any
1524 * IPs for which we don't have a link block.
1528 found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), ip) != Utils->ValidIPs.end());
1531 for (vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
1532 if (irc::sockets::MatchCIDR(ip, (*i).c_str()))
1537 this->Instance->SNO->WriteToSnoMask('l',"Server connection from %s denied (no link blocks with that IP address)", ip);
1543 TreeSocket* s = new TreeSocket(this->Utils, this->Instance, newsock, ip, this->Hook);
1544 s = s; /* Whinge whinge whinge, thats all GCC ever does. */