1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
15 #include "configreader.h"
19 #include "commands/cmd_whois.h"
20 #include "commands/cmd_stats.h"
24 #include "transport.h"
25 #include "socketengine.h"
27 #include "m_spanningtree/main.h"
28 #include "m_spanningtree/utils.h"
29 #include "m_spanningtree/treeserver.h"
30 #include "m_spanningtree/link.h"
31 #include "m_spanningtree/treesocket.h"
32 #include "m_spanningtree/resolvers.h"
33 #include "m_spanningtree/handshaketimer.h"
35 /* $ModDep: m_spanningtree/timesynctimer.h m_spanningtree/resolvers.h m_spanningtree/main.h m_spanningtree/utils.h m_spanningtree/treeserver.h m_spanningtree/link.h m_spanningtree/treesocket.h */
37 static std::map<std::string, std::string> warned; /* Server names that have had protocol violation warnings displayed for them */
39 int TreeSocket::WriteLine(std::string line)
41 Instance->Log(DEBUG, "S[%d] -> %s", this->GetFd(), line.c_str());
43 return this->Write(line);
47 /* Handle ERROR command */
48 bool TreeSocket::Error(std::deque<std::string> ¶ms)
50 if (params.size() < 1)
52 this->Instance->SNO->WriteToSnoMask('l',"ERROR from %s: %s",(InboundServerName != "" ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
53 /* we will return false to cause the socket to close. */
57 bool TreeSocket::Modules(const std::string &prefix, std::deque<std::string> ¶ms)
62 if (!this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
64 /* Pass it on, not for us */
65 Utils->DoOneToOne(prefix, "MODULES", params, params[0]);
70 std::deque<std::string> par;
71 par.push_back(prefix);
74 userrec* source = this->Instance->FindNick(prefix);
78 for (unsigned int i = 0; i < Instance->Config->module_names.size(); i++)
80 Version V = Instance->modules[i]->GetVersion();
81 char modulename[MAXBUF];
82 char flagstate[MAXBUF];
84 if (V.Flags & VF_STATIC)
85 strlcat(flagstate,", static",MAXBUF);
86 if (V.Flags & VF_VENDOR)
87 strlcat(flagstate,", vendor",MAXBUF);
88 if (V.Flags & VF_COMMON)
89 strlcat(flagstate,", common",MAXBUF);
90 if (V.Flags & VF_SERVICEPROVIDER)
91 strlcat(flagstate,", service provider",MAXBUF);
93 strcpy(flagstate," <no flags>");
94 strlcpy(modulename,Instance->Config->module_names[i].c_str(),256);
97 snprintf(strbuf, MAXBUF, "::%s 900 %s :0x%08lx %d.%d.%d.%d %s (%s)",Instance->Config->ServerName,source->nick,(long unsigned int)Instance->modules[i],V.Major,V.Minor,V.Revision,V.Build,ServerConfig::CleanFilename(modulename),flagstate+2);
101 snprintf(strbuf, MAXBUF, "::%s 900 %s :%s",Instance->Config->ServerName,source->nick,ServerConfig::CleanFilename(modulename));
104 Utils->DoOneToOne(Instance->Config->ServerName, "PUSH", par, source->server);
106 snprintf(strbuf, MAXBUF, "::%s 901 %s :End of MODULES list", Instance->Config->ServerName, source->nick);
108 Utils->DoOneToOne(Instance->Config->ServerName, "PUSH", par, source->server);
112 /** remote MOTD. leet, huh? */
113 bool TreeSocket::Motd(const std::string &prefix, std::deque<std::string> ¶ms)
115 if (params.size() > 0)
117 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
119 /* It's for our server */
121 userrec* source = this->Instance->FindNick(prefix);
125 std::deque<std::string> par;
126 par.push_back(prefix);
129 if (!Instance->Config->MOTD.size())
131 par[1] = std::string("::")+Instance->Config->ServerName+" 422 "+source->nick+" :Message of the day file is missing.";
132 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
136 par[1] = std::string("::")+Instance->Config->ServerName+" 375 "+source->nick+" :"+Instance->Config->ServerName+" message of the day";
137 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
139 for (unsigned int i = 0; i < Instance->Config->MOTD.size(); i++)
141 par[1] = std::string("::")+Instance->Config->ServerName+" 372 "+source->nick+" :- "+Instance->Config->MOTD[i];
142 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
145 par[1] = std::string("::")+Instance->Config->ServerName+" 376 "+source->nick+" End of message of the day.";
146 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
152 userrec* source = this->Instance->FindNick(prefix);
154 Utils->DoOneToOne(prefix, "MOTD", params, params[0]);
160 /** remote ADMIN. leet, huh? */
161 bool TreeSocket::Admin(const std::string &prefix, std::deque<std::string> ¶ms)
163 if (params.size() > 0)
165 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
167 /* It's for our server */
169 userrec* source = this->Instance->FindNick(prefix);
172 std::deque<std::string> par;
173 par.push_back(prefix);
175 par[1] = std::string("::")+Instance->Config->ServerName+" 256 "+source->nick+" :Administrative info for "+Instance->Config->ServerName;
176 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
177 par[1] = std::string("::")+Instance->Config->ServerName+" 257 "+source->nick+" :Name - "+Instance->Config->AdminName;
178 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
179 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :Nickname - "+Instance->Config->AdminNick;
180 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
181 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :E-Mail - "+Instance->Config->AdminEmail;
182 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
188 userrec* source = this->Instance->FindNick(prefix);
190 Utils->DoOneToOne(prefix, "ADMIN", params, params[0]);
196 bool TreeSocket::Stats(const std::string &prefix, std::deque<std::string> ¶ms)
198 /* Get the reply to a STATS query if it matches this servername,
199 * and send it back as a load of PUSH queries
201 if (params.size() > 1)
203 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[1]))
205 /* It's for our server */
207 userrec* source = this->Instance->FindNick(prefix);
210 std::deque<std::string> par;
211 par.push_back(prefix);
213 DoStats(this->Instance, *(params[0].c_str()), source, results);
214 for (size_t i = 0; i < results.size(); i++)
216 par[1] = "::" + results[i];
217 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
224 userrec* source = this->Instance->FindNick(prefix);
226 Utils->DoOneToOne(prefix, "STATS", params, params[1]);
233 /** Because the core won't let users or even SERVERS set +o,
234 * we use the OPERTYPE command to do this.
236 bool TreeSocket::OperType(const std::string &prefix, std::deque<std::string> ¶ms)
238 if (params.size() != 1)
240 std::string opertype = params[0];
241 userrec* u = this->Instance->FindNick(prefix);
244 u->modes[UM_OPERATOR] = 1;
245 this->Instance->all_opers.push_back(u);
246 strlcpy(u->oper,opertype.c_str(),NICKMAX-1);
247 Utils->DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
248 this->Instance->SNO->WriteToSnoMask('o',"From %s: User %s (%s@%s) is now an IRC operator of type %s",u->server, u->nick,u->ident,u->host,irc::Spacify(opertype.c_str()));
253 /** Because Andy insists that services-compatible servers must
254 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
256 bool TreeSocket::ForceNick(const std::string &prefix, std::deque<std::string> ¶ms)
258 if (params.size() < 3)
261 userrec* u = this->Instance->FindNick(params[0]);
265 Utils->DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
268 std::deque<std::string> par;
269 par.push_back(params[1]);
270 if (!u->ForceNickChange(params[1].c_str()))
272 userrec::QuitUser(this->Instance, u, "Nickname collision");
275 u->age = atoi(params[2].c_str());
281 bool TreeSocket::OperQuit(const std::string &prefix, std::deque<std::string> ¶ms)
283 if (params.size() < 1)
286 userrec* u = this->Instance->FindNick(prefix);
290 u->SetOperQuit(params[0]);
291 params[0] = ":" + params[0];
292 Utils->DoOneToAllButSender(prefix,"OPERQUIT",params,prefix);
298 * Remote SQUIT (RSQUIT). Routing works similar to SVSNICK: Route it to the server that the target is connected to locally,
299 * then let that server do the dirty work (squit it!). Example:
300 * A -> B -> C -> D: oper on A squits D, A routes to B, B routes to C, C notices D connected locally, kills it. -- w00t
302 bool TreeSocket::RemoteSquit(const std::string &prefix, std::deque<std::string> ¶ms)
304 /* ok.. :w00t RSQUIT jupe.barafranca.com :reason here */
305 if (params.size() < 2)
308 TreeServer* s = Utils->FindServerMask(params[0]);
312 if (s == Utils->TreeRoot)
314 this->Instance->SNO->WriteToSnoMask('l',"What the fuck, I recieved a remote SQUIT for myself? :< (from %s", prefix.c_str());
318 TreeSocket* sock = s->GetSocket();
322 /* it's locally connected, KILL IT! */
323 Instance->SNO->WriteToSnoMask('l',"RSQUIT: Server \002%s\002 removed from network by %s: %s", params[0].c_str(), prefix.c_str(), params[1].c_str());
324 sock->Squit(s,"Server quit by " + prefix + ": " + params[1]);
325 Instance->SE->DelFd(sock);
331 /* route the rsquit */
332 params[1] = ":" + params[1];
333 Utils->DoOneToOne(prefix, "RSQUIT", params, params[0]);
338 /* mother fucker! it doesn't exist */
344 bool TreeSocket::ServiceJoin(const std::string &prefix, std::deque<std::string> ¶ms)
346 if (params.size() < 2)
349 userrec* u = this->Instance->FindNick(params[0]);
353 /* only join if it's local, otherwise just pass it on! */
355 chanrec::JoinUser(this->Instance, u, params[1].c_str(), false, "", Instance->Time());
356 Utils->DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
361 bool TreeSocket::RemoteRehash(const std::string &prefix, std::deque<std::string> ¶ms)
363 if (params.size() < 1)
366 std::string servermask = params[0];
368 if (this->Instance->MatchText(this->Instance->Config->ServerName,servermask))
370 this->Instance->SNO->WriteToSnoMask('l',"Remote rehash initiated by \002"+prefix+"\002.");
371 this->Instance->RehashServer();
372 Utils->ReadConfiguration(false);
373 InitializeDisabledCommands(Instance->Config->DisabledCommands, Instance);
375 Utils->DoOneToAllButSender(prefix,"REHASH",params,prefix);
379 bool TreeSocket::LocalPong(const std::string &prefix, std::deque<std::string> ¶ms)
381 if (params.size() < 1)
384 if (params.size() == 1)
386 TreeServer* ServerSource = Utils->FindServer(prefix);
389 ServerSource->SetPingFlag();
390 ServerSource->rtt = Instance->Time() - ServerSource->LastPing;
395 std::string forwardto = params[1];
396 if (forwardto == this->Instance->Config->ServerName)
399 * this is a PONG for us
400 * if the prefix is a user, check theyre local, and if they are,
401 * dump the PONG reply back to their fd. If its a server, do nowt.
402 * Services might want to send these s->s, but we dont need to yet.
404 userrec* u = this->Instance->FindNick(prefix);
407 u->WriteServ("PONG %s %s",params[0].c_str(),params[1].c_str());
412 // not for us, pass it on :)
413 Utils->DoOneToOne(prefix,"PONG",params,forwardto);
420 bool TreeSocket::MetaData(const std::string &prefix, std::deque<std::string> ¶ms)
422 if (params.size() < 2)
424 else if (params.size() < 3)
425 params.push_back("");
426 TreeServer* ServerSource = Utils->FindServer(prefix);
429 Utils->SetRemoteBursting(ServerSource, false);
431 if (params[0] == "*")
433 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));
435 else if (*(params[0].c_str()) == '#')
437 chanrec* c = this->Instance->FindChan(params[0]);
440 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
443 else if (*(params[0].c_str()) != '#')
445 userrec* u = this->Instance->FindNick(params[0]);
448 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
453 params[2] = ":" + params[2];
454 Utils->DoOneToAllButSender(prefix,"METADATA",params,prefix);
458 bool TreeSocket::ServerVersion(const std::string &prefix, std::deque<std::string> ¶ms)
460 if (params.size() < 1)
463 TreeServer* ServerSource = Utils->FindServer(prefix);
467 ServerSource->SetVersion(params[0]);
469 params[0] = ":" + params[0];
470 Utils->DoOneToAllButSender(prefix,"VERSION",params,prefix);
474 bool TreeSocket::ChangeHost(const std::string &prefix, std::deque<std::string> ¶ms)
476 if (params.size() < 1)
478 userrec* u = this->Instance->FindNick(prefix);
482 u->ChangeDisplayedHost(params[0].c_str());
483 Utils->DoOneToAllButSender(prefix,"FHOST",params,u->server);
488 bool TreeSocket::AddLine(const std::string &prefix, std::deque<std::string> ¶ms)
490 if (params.size() < 6)
492 bool propogate = false;
494 Utils->lines_to_apply = 0;
495 switch (*(params[0].c_str()))
498 propogate = Instance->XLines->add_zline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
499 Instance->XLines->zline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
501 Utils->lines_to_apply |= APPLY_ZLINES;
504 propogate = Instance->XLines->add_qline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
505 Instance->XLines->qline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
507 Utils->lines_to_apply |= APPLY_QLINES;
510 propogate = Instance->XLines->add_eline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
511 Instance->XLines->eline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
514 propogate = Instance->XLines->add_gline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
515 Instance->XLines->gline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
517 Utils->lines_to_apply |= APPLY_GLINES;
520 propogate = Instance->XLines->add_kline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
522 Utils->lines_to_apply |= APPLY_KLINES;
525 /* Just in case... */
526 this->Instance->SNO->WriteToSnoMask('x',"\2WARNING\2: Invalid xline type '"+params[0]+"' sent by server "+prefix+", ignored!");
530 /* Send it on its way */
533 if (atoi(params[4].c_str()))
535 time_t c_requires_crap = ConvToInt(params[4]) + Instance->Time();
536 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());
540 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());
542 params[5] = ":" + params[5];
543 Utils->DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
547 Instance->XLines->apply_lines(Utils->lines_to_apply);
548 Utils->lines_to_apply = 0;
553 bool TreeSocket::ChangeName(const std::string &prefix, std::deque<std::string> ¶ms)
555 if (params.size() < 1)
557 userrec* u = this->Instance->FindNick(prefix);
560 u->ChangeName(params[0].c_str());
561 params[0] = ":" + params[0];
562 Utils->DoOneToAllButSender(prefix,"FNAME",params,u->server);
567 bool TreeSocket::Whois(const std::string &prefix, std::deque<std::string> ¶ms)
569 if (params.size() < 1)
571 userrec* u = this->Instance->FindNick(prefix);
574 // an incoming request
575 if (params.size() == 1)
577 userrec* x = this->Instance->FindNick(params[0]);
578 if ((x) && (IS_LOCAL(x)))
580 userrec* x = this->Instance->FindNick(params[0]);
583 snprintf(signon, MAXBUF, "%lu", (unsigned long)x->signon);
584 snprintf(idle, MAXBUF, "%lu", (unsigned long)abs((x->idle_lastmsg) - Instance->Time(true)));
585 std::deque<std::string> par;
586 par.push_back(prefix);
587 par.push_back(signon);
589 // ours, we're done, pass it BACK
590 Utils->DoOneToOne(params[0], "IDLE", par, u->server);
594 // not ours pass it on
596 Utils->DoOneToOne(prefix, "IDLE", params, x->server);
599 else if (params.size() == 3)
601 std::string who_did_the_whois = params[0];
602 userrec* who_to_send_to = this->Instance->FindNick(who_did_the_whois);
603 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
605 // an incoming reply to a whois we sent out
606 std::string nick_whoised = prefix;
607 unsigned long signon = atoi(params[1].c_str());
608 unsigned long idle = atoi(params[2].c_str());
609 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
611 do_whois(this->Instance, who_to_send_to, u, signon, idle, nick_whoised.c_str());
616 // not ours, pass it on
618 Utils->DoOneToOne(prefix, "IDLE", params, who_to_send_to->server);
625 bool TreeSocket::Push(const std::string &prefix, std::deque<std::string> ¶ms)
627 if (params.size() < 2)
629 userrec* u = this->Instance->FindNick(params[0]);
638 // continue the raw onwards
639 params[1] = ":" + params[1];
640 Utils->DoOneToOne(prefix,"PUSH",params,u->server);
645 bool TreeSocket::HandleSetTime(const std::string &prefix, std::deque<std::string> ¶ms)
647 if (!params.size() || !Utils->EnableTimeSync)
652 if ((params.size() == 2) && (params[1] == "FORCE"))
655 time_t them = atoi(params[0].c_str());
656 time_t us = Instance->Time(false);
658 time_t diff = them - us;
660 Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
662 if (force || (them != us))
664 time_t old = Instance->SetTimeDelta(diff);
665 Instance->Log(DEBUG, "TS (diff %d) from %s applied (old delta was %d)", diff, prefix.c_str(), old);
671 bool TreeSocket::Time(const std::string &prefix, std::deque<std::string> ¶ms)
673 // :source.server TIME remote.server sendernick
674 // :remote.server TIME source.server sendernick TS
675 if (params.size() == 2)
677 // someone querying our time?
678 if (this->Instance->Config->ServerName == params[0])
680 userrec* u = this->Instance->FindNick(params[1]);
683 params.push_back(ConvToStr(Instance->Time(false)));
685 Utils->DoOneToOne(this->Instance->Config->ServerName,"TIME",params,params[0]);
690 // not us, pass it on
691 userrec* u = this->Instance->FindNick(params[1]);
693 Utils->DoOneToOne(prefix,"TIME",params,params[0]);
696 else if (params.size() == 3)
698 // a response to a previous TIME
699 userrec* u = this->Instance->FindNick(params[1]);
700 if ((u) && (IS_LOCAL(u)))
702 time_t rawtime = atol(params[2].c_str());
703 struct tm * timeinfo;
704 timeinfo = localtime(&rawtime);
706 snprintf(tms,26,"%s",asctime(timeinfo));
708 u->WriteServ("391 %s %s :%s",u->nick,prefix.c_str(),tms);
713 Utils->DoOneToOne(prefix,"TIME",params,u->server);
719 bool TreeSocket::LocalPing(const std::string &prefix, std::deque<std::string> ¶ms)
721 if (params.size() < 1)
723 if (params.size() == 1)
725 std::string stufftobounce = params[0];
726 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" PONG "+stufftobounce);
731 std::string forwardto = params[1];
732 if (forwardto == this->Instance->Config->ServerName)
734 // this is a ping for us, send back PONG to the requesting server
735 params[1] = params[0];
736 params[0] = forwardto;
737 Utils->DoOneToOne(forwardto,"PONG",params,params[1]);
741 // not for us, pass it on :)
742 Utils->DoOneToOne(prefix,"PING",params,forwardto);
748 /** TODO: This creates a total mess of output and needs to really use irc::modestacker.
750 bool TreeSocket::RemoveStatus(const std::string &prefix, std::deque<std::string> ¶ms)
752 if (params.size() < 1)
754 chanrec* c = Instance->FindChan(params[0]);
757 for (char modeletter = 'A'; modeletter <= 'z'; modeletter++)
759 ModeHandler* mh = Instance->Modes->FindMode(modeletter, MODETYPE_CHANNEL);
767 bool TreeSocket::RemoteServer(const std::string &prefix, std::deque<std::string> ¶ms)
769 if (params.size() < 4)
771 std::string servername = params[0];
772 std::string password = params[1];
773 // hopcount is not used for a remote server, we calculate this ourselves
774 std::string description = params[3];
775 TreeServer* ParentOfThis = Utils->FindServer(prefix);
778 this->SendError("Protocol error - Introduced remote server from unknown server "+prefix);
781 TreeServer* CheckDupe = Utils->FindServer(servername);
784 this->SendError("Server "+servername+" already exists!");
785 this->Instance->SNO->WriteToSnoMask('l',"Server \2"+servername+"\2 being introduced from \2" + prefix + "\2 denied, already exists. Closing link with " + prefix);
788 Link* lnk = Utils->FindLink(servername);
789 TreeServer* Node = new TreeServer(this->Utils,this->Instance,servername,description,ParentOfThis,NULL, lnk ? lnk->Hidden : false);
790 ParentOfThis->AddChild(Node);
791 params[3] = ":" + params[3];
792 Utils->SetRemoteBursting(Node, true);
793 Utils->DoOneToAllButSender(prefix,"SERVER",params,prefix);
794 this->Instance->SNO->WriteToSnoMask('l',"Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
798 bool TreeSocket::ComparePass(const std::string &ours, const std::string &theirs)
800 if ((!strncmp(ours.c_str(), "HMAC-SHA256:", 12)) || (!strncmp(theirs.c_str(), "HMAC-SHA256:", 12)))
802 /* One or both of us specified hmac sha256, but we don't have sha256 module loaded!
803 * We can't allow this password as valid.
805 if (!Instance->FindModule("m_sha256.so") || !Utils->ChallengeResponse)
808 /* Straight string compare of hashes */
809 return ours == theirs;
812 /* Straight string compare of plaintext */
813 return ours == theirs;
816 bool TreeSocket::Outbound_Reply_Server(std::deque<std::string> ¶ms)
818 if (params.size() < 4)
821 irc::string servername = params[0].c_str();
822 std::string sname = params[0];
823 std::string password = params[1];
824 std::string description = params[3];
825 int hops = atoi(params[2].c_str());
827 this->InboundServerName = sname;
828 this->InboundDescription = description;
832 this->SendError("Server too far away for authentication");
833 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
837 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
839 if ((x->Name == servername) && ((ComparePass(this->MakePass(x->RecvPass,this->GetOurChallenge()),password)) || (x->RecvPass == password && (this->GetTheirChallenge().empty()))))
841 TreeServer* CheckDupe = Utils->FindServer(sname);
844 this->SendError("Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
845 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
848 // Begin the sync here. this kickstarts the
849 // other side, waiting in WAIT_AUTH_2 state,
850 // into starting their burst, as it shows
852 this->LinkState = CONNECTED;
853 // we should add the details of this server now
854 // to the servers tree, as a child of the root
856 TreeServer* Node = new TreeServer(this->Utils,this->Instance,sname,description,Utils->TreeRoot,this,x->Hidden);
857 Utils->TreeRoot->AddChild(Node);
858 params[3] = ":" + params[3];
859 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,sname);
860 this->bursting = true;
865 this->SendError("Invalid credentials");
866 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
870 bool TreeSocket::Inbound_Server(std::deque<std::string> ¶ms)
872 if (params.size() < 4)
874 irc::string servername = params[0].c_str();
875 std::string sname = params[0];
876 std::string password = params[1];
877 std::string description = params[3];
878 int hops = atoi(params[2].c_str());
880 this->InboundServerName = sname;
881 this->InboundDescription = description;
885 this->SendError("Server too far away for authentication");
886 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
890 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
892 if ((x->Name == servername) && ((ComparePass(this->MakePass(x->RecvPass,this->GetOurChallenge()),password) || x->RecvPass == password && (this->GetTheirChallenge().empty()))))
894 /* First check for instances of the server that are waiting between the inbound and outbound SERVER command */
895 TreeSocket* CheckDupeSocket = Utils->FindBurstingServer(sname);
898 /* If we find one, we abort the link to prevent a race condition */
899 this->SendError("Negotiation collision");
900 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists in a negotiating state.");
901 CheckDupeSocket->SendError("Negotiation collision");
902 Instance->SE->DelFd(CheckDupeSocket);
903 CheckDupeSocket->Close();
904 delete CheckDupeSocket;
907 /* Now check for fully initialized instances of the server */
908 TreeServer* CheckDupe = Utils->FindServer(sname);
911 this->SendError("Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
912 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
915 this->Instance->SNO->WriteToSnoMask('l',"Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
918 std::string name = InspSocketNameRequest((Module*)Utils->Creator, this->Hook).Send();
919 this->Instance->SNO->WriteToSnoMask('l',"Connection from \2"+sname+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] using transport \2"+name+"\2");
922 Utils->AddBurstingServer(sname,this);
924 // this is good. Send our details: Our server name and description and hopcount of 0,
925 // along with the sendpass from this block.
926 this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+this->MakePass(x->SendPass, this->GetTheirChallenge())+" 0 :"+this->Instance->Config->ServerDesc);
927 // move to the next state, we are now waiting for THEM.
928 this->LinkState = WAIT_AUTH_2;
932 this->SendError("Invalid credentials");
933 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
937 void TreeSocket::Split(const std::string &line, std::deque<std::string> &n)
940 irc::tokenstream tokens(line);
942 while (tokens.GetToken(param))
950 bool TreeSocket::ProcessLine(std::string &line)
952 std::deque<std::string> params;
956 line = line.substr(0, line.find_first_of("\r\n"));
961 Instance->Log(DEBUG, "S[%d] <- %s", this->GetFd(), line.c_str());
963 this->Split(line.c_str(),params);
968 if ((params[0][0] == ':') && (params.size() > 1))
970 prefix = params[0].substr(1);
973 command = params[0].c_str();
975 switch (this->LinkState)
980 // Waiting for SERVER command from remote server. Server initiating
981 // the connection sends the first SERVER command, listening server
982 // replies with theirs if its happy, then if the initiator is happy,
983 // it starts to send its net sync, which starts the merge, otherwise
984 // it sends an ERROR.
985 if (command == "PASS")
987 /* Silently ignored */
989 else if (command == "SERVER")
991 return this->Inbound_Server(params);
993 else if (command == "ERROR")
995 return this->Error(params);
997 else if (command == "USER")
999 this->SendError("Client connections to this port are prohibited.");
1002 else if (command == "CAPAB")
1004 return this->Capab(params);
1006 else if ((command == "U") || (command == "S"))
1008 this->SendError("Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
1013 irc::string error = "Invalid command in negotiation phase: " + command;
1014 this->SendError(assign(error));
1019 // Waiting for start of other side's netmerge to say they liked our
1021 if (command == "SERVER")
1023 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1027 else if ((command == "U") || (command == "S"))
1029 this->SendError("Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
1032 else if (command == "BURST")
1034 if (params.size() && Utils->EnableTimeSync)
1036 bool we_have_delta = (Instance->Time(false) != Instance->Time(true));
1037 time_t them = atoi(params[0].c_str());
1038 time_t delta = them - Instance->Time(false);
1039 if ((delta < -300) || (delta > 300))
1041 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));
1042 SendError("Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than five minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
1045 else if ((delta < -30) || (delta > 30))
1047 Instance->SNO->WriteToSnoMask('l',"\2WARNING\2: Your clocks are out by %d seconds. Please consider synching your clocks.", abs(delta));
1050 if (!Utils->MasterTime && !we_have_delta)
1052 this->Instance->SetTimeDelta(delta);
1053 // Send this new timestamp to any other servers
1054 Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
1057 this->LinkState = CONNECTED;
1058 Link* lnk = Utils->FindLink(InboundServerName);
1059 Node = new TreeServer(this->Utils,this->Instance, InboundServerName, InboundDescription, Utils->TreeRoot, this, lnk ? lnk->Hidden : false);
1060 Utils->DelBurstingServer(this);
1061 Utils->TreeRoot->AddChild(Node);
1063 params.push_back(InboundServerName);
1064 params.push_back("*");
1065 params.push_back("1");
1066 params.push_back(":"+InboundDescription);
1067 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,InboundServerName);
1068 this->bursting = true;
1069 this->DoBurst(Node);
1071 else if (command == "ERROR")
1073 return this->Error(params);
1075 else if (command == "CAPAB")
1077 return this->Capab(params);
1082 this->SendError("Internal error -- listening socket accepted its own descriptor!!!");
1086 if (command == "SERVER")
1088 // another server we connected to, which was in WAIT_AUTH_1 state,
1089 // has just sent us their credentials. If we get this far, theyre
1090 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1091 // if we're happy with this, we should send our netburst which
1092 // kickstarts the merge.
1093 return this->Outbound_Reply_Server(params);
1095 else if (command == "ERROR")
1097 return this->Error(params);
1099 else if (command == "CAPAB")
1101 return this->Capab(params);
1105 // This is the 'authenticated' state, when all passwords
1106 // have been exchanged and anything past this point is taken
1109 if (!prefix.empty())
1111 std::string direction = prefix;
1112 userrec* t = this->Instance->FindNick(prefix);
1115 direction = t->server;
1117 TreeServer* route_back_again = Utils->BestRouteTo(direction);
1118 if ((!route_back_again) || (route_back_again->GetSocket() != this))
1120 if (route_back_again)
1121 Instance->Log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
1125 * When there is activity on the socket, reset the ping counter so
1126 * that we're not wasting bandwidth pinging an active server.
1128 route_back_again->SetNextPingTime(time(NULL) + 60);
1129 route_back_again->SetPingFlag();
1133 prefix = this->GetName();
1136 if ((command == "MODE") && (params.size() >= 2))
1138 chanrec* channel = Instance->FindChan(params[0]);
1141 userrec* x = Instance->FindNick(prefix);
1144 if (warned.find(x->server) == warned.end())
1146 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);
1147 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());
1148 warned[x->server] = x->nick;
1154 if (command == "SVSMODE")
1156 /* Services expects us to implement
1157 * SVSMODE. In inspircd its the same as
1162 std::string target = "";
1163 /* Yes, know, this is a mess. Its reasonably fast though as we're
1164 * working with std::string here.
1166 if ((command == "NICK") && (params.size() >= 8))
1168 return this->IntroduceClient(prefix,params);
1170 else if (command == "FJOIN")
1172 TreeServer* ServerSource = Utils->FindServer(prefix);
1174 Utils->SetRemoteBursting(ServerSource, false);
1175 return this->ForceJoin(prefix,params);
1177 else if (command == "STATS")
1179 return this->Stats(prefix, params);
1181 else if (command == "MOTD")
1183 return this->Motd(prefix, params);
1185 else if (command == "MODULES")
1187 return this->Modules(prefix, params);
1189 else if (command == "ADMIN")
1191 return this->Admin(prefix, params);
1193 else if (command == "SERVER")
1195 return this->RemoteServer(prefix,params);
1197 else if (command == "ERROR")
1199 return this->Error(params);
1201 else if (command == "OPERTYPE")
1203 return this->OperType(prefix,params);
1205 else if (command == "FMODE")
1207 TreeServer* ServerSource = Utils->FindServer(prefix);
1209 Utils->SetRemoteBursting(ServerSource, false);
1210 return this->ForceMode(prefix,params);
1212 else if (command == "FTOPIC")
1214 return this->ForceTopic(prefix,params);
1216 else if (command == "REHASH")
1218 return this->RemoteRehash(prefix,params);
1220 else if (command == "METADATA")
1222 return this->MetaData(prefix,params);
1224 else if (command == "REMSTATUS")
1226 return this->RemoveStatus(prefix,params);
1228 else if (command == "PING")
1231 prefix = this->GetName();
1233 * We just got a ping from a server that's bursting.
1234 * This can't be right, so set them to not bursting, and
1235 * apply their lines.
1237 TreeServer* ServerSource = Utils->FindServer(prefix);
1239 Utils->SetRemoteBursting(ServerSource, false);
1243 this->bursting = false;
1244 Instance->XLines->apply_lines(Utils->lines_to_apply);
1245 Utils->lines_to_apply = 0;
1248 return this->LocalPing(prefix,params);
1250 else if (command == "PONG")
1253 prefix = this->GetName();
1255 * We just got a pong 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->LocalPong(prefix,params);
1272 else if (command == "VERSION")
1274 return this->ServerVersion(prefix,params);
1276 else if (command == "FHOST")
1278 return this->ChangeHost(prefix,params);
1280 else if (command == "FNAME")
1282 return this->ChangeName(prefix,params);
1284 else if (command == "ADDLINE")
1286 TreeServer* ServerSource = Utils->FindServer(prefix);
1288 Utils->SetRemoteBursting(ServerSource, false);
1289 return this->AddLine(prefix,params);
1291 else if (command == "SVSNICK")
1295 prefix = this->GetName();
1297 return this->ForceNick(prefix,params);
1299 else if (command == "OPERQUIT")
1301 return this->OperQuit(prefix,params);
1303 else if (command == "RSQUIT")
1305 return this->RemoteSquit(prefix, params);
1307 else if (command == "IDLE")
1309 return this->Whois(prefix,params);
1311 else if (command == "PUSH")
1313 return this->Push(prefix,params);
1315 else if (command == "TIMESET")
1317 return this->HandleSetTime(prefix, params);
1319 else if (command == "TIME")
1321 return this->Time(prefix,params);
1323 else if ((command == "KICK") && (Utils->IsServer(prefix)))
1325 std::string sourceserv = this->myhost;
1326 if (params.size() == 3)
1328 userrec* user = this->Instance->FindNick(params[1]);
1329 chanrec* chan = this->Instance->FindChan(params[0]);
1332 if (!chan->ServerKickUser(user, params[2].c_str(), false))
1333 /* Yikes, the channels gone! */
1337 if (this->InboundServerName != "")
1339 sourceserv = this->InboundServerName;
1341 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1343 else if (command == "SVSJOIN")
1347 prefix = this->GetName();
1349 return this->ServiceJoin(prefix,params);
1351 else if (command == "SQUIT")
1353 if (params.size() == 2)
1355 this->Squit(Utils->FindServer(params[0]),params[1]);
1359 else if (command == "OPERNOTICE")
1361 std::string sourceserv = this->myhost;
1362 if (this->InboundServerName != "")
1363 sourceserv = this->InboundServerName;
1364 if (params.size() >= 1)
1365 Instance->WriteOpers("*** From " + sourceserv + ": " + params[0]);
1366 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1368 else if (command == "MODENOTICE")
1370 std::string sourceserv = this->myhost;
1371 if (this->InboundServerName != "")
1372 sourceserv = this->InboundServerName;
1373 if (params.size() >= 2)
1375 Instance->WriteMode(params[0].c_str(), WM_AND, "*** From %s: %s", sourceserv.c_str(), params[1].c_str());
1377 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1379 else if (command == "SNONOTICE")
1381 std::string sourceserv = this->myhost;
1382 if (this->InboundServerName != "")
1383 sourceserv = this->InboundServerName;
1384 if (params.size() >= 2)
1386 Instance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + sourceserv + ": "+ params[1]);
1388 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1390 else if (command == "ENDBURST")
1392 this->bursting = false;
1393 Instance->XLines->apply_lines(Utils->lines_to_apply);
1394 Utils->lines_to_apply = 0;
1395 std::string sourceserv = this->myhost;
1396 if (this->InboundServerName != "")
1398 sourceserv = this->InboundServerName;
1400 this->Instance->SNO->WriteToSnoMask('l',"Received end of netburst from \2%s\2",sourceserv.c_str());
1402 Event rmode((char*)sourceserv.c_str(), (Module*)Utils->Creator, "new_server");
1403 rmode.Send(Instance);
1409 // not a special inter-server command.
1410 // Emulate the actual user doing the command,
1411 // this saves us having a huge ugly parser.
1412 userrec* who = this->Instance->FindNick(prefix);
1413 std::string sourceserv = this->myhost;
1414 if (this->InboundServerName != "")
1416 sourceserv = this->InboundServerName;
1418 if ((!who) && (command == "MODE"))
1420 if (Utils->IsServer(prefix))
1422 const char* modelist[127];
1423 for (size_t i = 0; i < params.size(); i++)
1424 modelist[i] = params[i].c_str();
1425 userrec* fake = new userrec(Instance);
1426 fake->SetFd(FD_MAGIC_NUMBER);
1427 this->Instance->SendMode(modelist, params.size(), fake);
1430 /* Hot potato! pass it on! */
1431 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1436 if ((command == "NICK") && (params.size() > 0))
1438 /* On nick messages, check that the nick doesnt
1439 * already exist here. If it does, kill their copy,
1442 userrec* x = this->Instance->FindNick(params[0]);
1443 if ((x) && (x != who))
1445 std::deque<std::string> p;
1446 p.push_back(params[0]);
1447 p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
1448 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
1450 p.push_back(prefix);
1451 p.push_back("Nickname collision");
1452 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
1453 userrec::QuitUser(this->Instance,x,"Nickname collision ("+prefix+" -> "+params[0]+")");
1454 userrec* y = this->Instance->FindNick(prefix);
1457 userrec::QuitUser(this->Instance,y,"Nickname collision");
1459 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1463 target = who->server;
1464 const char* strparams[127];
1465 for (unsigned int q = 0; q < params.size(); q++)
1467 strparams[q] = params[q].c_str();
1469 switch (this->Instance->CallCommandHandler(command.c_str(), strparams, params.size(), who))
1472 this->SendError("Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
1479 /* CMD_SUCCESS and CMD_USER_DELETED fall through here */
1485 // its not a user. Its either a server, or somethings screwed up.
1486 if (Utils->IsServer(prefix))
1487 target = this->Instance->Config->ServerName;
1491 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1500 std::string TreeSocket::GetName()
1502 std::string sourceserv = this->myhost;
1503 if (this->InboundServerName != "")
1505 sourceserv = this->InboundServerName;
1510 void TreeSocket::OnTimeout()
1512 if (this->LinkState == CONNECTING)
1514 this->Instance->SNO->WriteToSnoMask('l',"CONNECT: Connection to \002"+myhost+"\002 timed out.");
1515 Link* MyLink = Utils->FindLink(myhost);
1517 Utils->DoFailOver(MyLink);
1521 void TreeSocket::OnClose()
1523 // Connection closed.
1524 // If the connection is fully up (state CONNECTED)
1525 // then propogate a netsplit to all peers.
1526 std::string quitserver = this->myhost;
1527 if (this->InboundServerName != "")
1529 quitserver = this->InboundServerName;
1531 TreeServer* s = Utils->FindServer(quitserver);
1534 Squit(s,"Remote host closed the connection");
1537 if (quitserver != "")
1539 this->Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' failed.",quitserver.c_str());
1540 time_t server_uptime = Instance->Time() - this->age;
1542 Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' was established for %s", quitserver.c_str(), Utils->Creator->TimeToStr(server_uptime).c_str());
1546 int TreeSocket::OnIncomingConnection(int newsock, char* ip)
1548 /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
1549 * or discovering if this port is the server port, we don't allow connections from any
1550 * IPs for which we don't have a link block.
1554 found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), ip) != Utils->ValidIPs.end());
1557 for (vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
1558 if (irc::sockets::MatchCIDR(ip, (*i).c_str()))
1563 this->Instance->SNO->WriteToSnoMask('l',"Server connection from %s denied (no link blocks with that IP address)", ip);
1569 TreeSocket* s = new TreeSocket(this->Utils, this->Instance, newsock, ip, this->Hook);
1570 s = s; /* Whinge whinge whinge, thats all GCC ever does. */