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 "commands/cmd_whois.h"
16 #include "commands/cmd_stats.h"
20 #include "transport.h"
21 #include "socketengine.h"
23 #include "m_spanningtree/main.h"
24 #include "m_spanningtree/utils.h"
25 #include "m_spanningtree/treeserver.h"
26 #include "m_spanningtree/link.h"
27 #include "m_spanningtree/treesocket.h"
28 #include "m_spanningtree/resolvers.h"
29 #include "m_spanningtree/handshaketimer.h"
31 /* $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 */
33 static std::map<std::string, std::string> warned; /* Server names that have had protocol violation warnings displayed for them */
35 int TreeSocket::WriteLine(std::string line)
37 Instance->Log(DEBUG, "S[%d] O %s", this->GetFd(), line.c_str());
39 return this->Write(line);
43 /* Handle ERROR command */
44 bool TreeSocket::Error(std::deque<std::string> ¶ms)
46 if (params.size() < 1)
48 this->Instance->SNO->WriteToSnoMask('l',"ERROR from %s: %s",(!InboundServerName.empty() ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
49 /* we will return false to cause the socket to close. */
53 bool TreeSocket::Modules(const std::string &prefix, std::deque<std::string> ¶ms)
58 if (!this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
60 /* Pass it on, not for us */
61 Utils->DoOneToOne(prefix, "MODULES", params, params[0]);
66 std::deque<std::string> par;
67 par.push_back(prefix);
70 userrec* source = this->Instance->FindNick(prefix);
74 for (unsigned int i = 0; i < Instance->Config->module_names.size(); i++)
76 Version V = Instance->modules[i]->GetVersion();
77 char modulename[MAXBUF];
78 char flagstate[MAXBUF];
80 if (V.Flags & VF_STATIC)
81 strlcat(flagstate,", static",MAXBUF);
82 if (V.Flags & VF_VENDOR)
83 strlcat(flagstate,", vendor",MAXBUF);
84 if (V.Flags & VF_COMMON)
85 strlcat(flagstate,", common",MAXBUF);
86 if (V.Flags & VF_SERVICEPROVIDER)
87 strlcat(flagstate,", service provider",MAXBUF);
89 strcpy(flagstate," <no flags>");
90 strlcpy(modulename,Instance->Config->module_names[i].c_str(),256);
93 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);
97 snprintf(strbuf, MAXBUF, "::%s 900 %s :%s",Instance->Config->ServerName,source->nick,ServerConfig::CleanFilename(modulename));
100 Utils->DoOneToOne(Instance->Config->ServerName, "PUSH", par, source->server);
102 snprintf(strbuf, MAXBUF, "::%s 901 %s :End of MODULES list", Instance->Config->ServerName, source->nick);
104 Utils->DoOneToOne(Instance->Config->ServerName, "PUSH", par, source->server);
108 /** remote MOTD. leet, huh? */
109 bool TreeSocket::Motd(const std::string &prefix, std::deque<std::string> ¶ms)
111 if (params.size() > 0)
113 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
115 /* It's for our server */
117 userrec* source = this->Instance->FindNick(prefix);
121 std::deque<std::string> par;
122 par.push_back(prefix);
125 if (!Instance->Config->MOTD.size())
127 par[1] = std::string("::")+Instance->Config->ServerName+" 422 "+source->nick+" :Message of the day file is missing.";
128 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
132 par[1] = std::string("::")+Instance->Config->ServerName+" 375 "+source->nick+" :"+Instance->Config->ServerName+" message of the day";
133 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
135 for (unsigned int i = 0; i < Instance->Config->MOTD.size(); i++)
137 par[1] = std::string("::")+Instance->Config->ServerName+" 372 "+source->nick+" :- "+Instance->Config->MOTD[i];
138 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
141 par[1] = std::string("::")+Instance->Config->ServerName+" 376 "+source->nick+" :End of message of the day.";
142 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
148 userrec* source = this->Instance->FindNick(prefix);
150 Utils->DoOneToOne(prefix, "MOTD", params, params[0]);
156 /** remote ADMIN. leet, huh? */
157 bool TreeSocket::Admin(const std::string &prefix, std::deque<std::string> ¶ms)
159 if (params.size() > 0)
161 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
163 /* It's for our server */
165 userrec* source = this->Instance->FindNick(prefix);
168 std::deque<std::string> par;
169 par.push_back(prefix);
171 par[1] = std::string("::")+Instance->Config->ServerName+" 256 "+source->nick+" :Administrative info for "+Instance->Config->ServerName;
172 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
173 par[1] = std::string("::")+Instance->Config->ServerName+" 257 "+source->nick+" :Name - "+Instance->Config->AdminName;
174 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
175 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :Nickname - "+Instance->Config->AdminNick;
176 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
177 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :E-Mail - "+Instance->Config->AdminEmail;
178 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
184 userrec* source = this->Instance->FindNick(prefix);
186 Utils->DoOneToOne(prefix, "ADMIN", params, params[0]);
192 bool TreeSocket::Stats(const std::string &prefix, std::deque<std::string> ¶ms)
194 /* Get the reply to a STATS query if it matches this servername,
195 * and send it back as a load of PUSH queries
197 if (params.size() > 1)
199 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[1]))
201 /* It's for our server */
203 userrec* source = this->Instance->FindNick(prefix);
206 std::deque<std::string> par;
207 par.push_back(prefix);
209 DoStats(this->Instance, *(params[0].c_str()), source, results);
210 for (size_t i = 0; i < results.size(); i++)
212 par[1] = "::" + results[i];
213 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
220 userrec* source = this->Instance->FindNick(prefix);
222 Utils->DoOneToOne(prefix, "STATS", params, params[1]);
229 /** Because the core won't let users or even SERVERS set +o,
230 * we use the OPERTYPE command to do this.
232 bool TreeSocket::OperType(const std::string &prefix, std::deque<std::string> ¶ms)
234 if (params.size() != 1)
236 std::string opertype = params[0];
237 userrec* u = this->Instance->FindNick(prefix);
240 u->modes[UM_OPERATOR] = 1;
241 this->Instance->all_opers.push_back(u);
242 strlcpy(u->oper,opertype.c_str(),NICKMAX-1);
243 Utils->DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
245 TreeServer* remoteserver=Utils->FindServer(u->server);
248 if (this->Utils->quiet_bursts)
251 * If quiet bursts are enabled, and server is bursting or silent uline (i.e. services),
252 * then do nothing. -- w00t
256 Utils->FindRemoteBurstServer(remoteserver) ||
257 this->Instance->SilentULine(this->Instance->FindServerNamePtr(u->server))
265 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()));
270 /** Because Andy insists that services-compatible servers must
271 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
273 bool TreeSocket::ForceNick(const std::string &prefix, std::deque<std::string> ¶ms)
275 if (params.size() < 3)
278 userrec* u = this->Instance->FindNick(params[0]);
282 Utils->DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
286 std::deque<std::string> par;
287 par.push_back(params[1]);
289 if (!u->ForceNickChange(params[1].c_str()))
292 if (!u->ForceNickChange(u->uuid))
294 userrec::QuitUser(this->Instance, u, "Nickname collision");
299 u->age = atoi(params[2].c_str());
306 bool TreeSocket::OperQuit(const std::string &prefix, std::deque<std::string> ¶ms)
308 if (params.size() < 1)
311 userrec* u = this->Instance->FindNick(prefix);
315 u->SetOperQuit(params[0]);
316 params[0] = ":" + params[0];
317 Utils->DoOneToAllButSender(prefix,"OPERQUIT",params,prefix);
322 bool TreeSocket::ServiceJoin(const std::string &prefix, std::deque<std::string> ¶ms)
324 if (params.size() < 2)
327 if (!this->Instance->IsChannel(params[1].c_str()))
330 userrec* u = this->Instance->FindNick(params[0]);
334 /* only join if it's local, otherwise just pass it on! */
336 chanrec::JoinUser(this->Instance, u, params[1].c_str(), false, "", Instance->Time());
337 Utils->DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
342 bool TreeSocket::RemoteRehash(const std::string &prefix, std::deque<std::string> ¶ms)
344 if (params.size() < 1)
347 std::string servermask = params[0];
349 if (this->Instance->MatchText(this->Instance->Config->ServerName,servermask))
351 this->Instance->SNO->WriteToSnoMask('l',"Remote rehash initiated by \002"+prefix+"\002.");
352 this->Instance->RehashServer();
353 Utils->ReadConfiguration(false);
354 InitializeDisabledCommands(Instance->Config->DisabledCommands, Instance);
356 Utils->DoOneToAllButSender(prefix,"REHASH",params,prefix);
360 bool TreeSocket::RemoteKill(const std::string &prefix, std::deque<std::string> ¶ms)
362 if (params.size() != 2)
365 userrec* who = this->Instance->FindNick(params[0]);
369 /* Prepend kill source, if we don't have one */
370 if (*(params[1].c_str()) != '[')
372 params[1] = "[" + prefix + "] Killed (" + params[1] +")";
374 std::string reason = params[1];
375 params[1] = ":" + params[1];
376 Utils->DoOneToAllButSender(prefix,"KILL",params,prefix);
377 // NOTE: This is safe with kill hiding on, as RemoteKill is only reached if we have a server prefix.
378 // in short this is not executed for USERS.
379 who->Write(":%s KILL %s :%s (%s)", prefix.c_str(), who->nick, prefix.c_str(), reason.c_str());
380 userrec::QuitUser(this->Instance,who,reason);
385 bool TreeSocket::LocalPong(const std::string &prefix, std::deque<std::string> ¶ms)
387 if (params.size() < 1)
390 if (params.size() == 1)
392 TreeServer* ServerSource = Utils->FindServer(prefix);
395 ServerSource->SetPingFlag();
397 gettimeofday(&t, NULL);
398 long ts = (t.tv_sec * 1000) + (t.tv_usec / 1000);
399 ServerSource->rtt = ts - ServerSource->LastPingMsec;
404 std::string forwardto = params[1];
405 if (forwardto == this->Instance->Config->ServerName)
408 * this is a PONG for us
409 * if the prefix is a user, check theyre local, and if they are,
410 * dump the PONG reply back to their fd. If its a server, do nowt.
411 * Services might want to send these s->s, but we dont need to yet.
413 userrec* u = this->Instance->FindNick(prefix);
416 u->WriteServ("PONG %s %s",params[0].c_str(),params[1].c_str());
421 // not for us, pass it on :)
422 Utils->DoOneToOne(prefix,"PONG",params,forwardto);
429 bool TreeSocket::MetaData(const std::string &prefix, std::deque<std::string> ¶ms)
431 if (params.size() < 2)
433 else if (params.size() < 3)
434 params.push_back("");
435 TreeServer* ServerSource = Utils->FindServer(prefix);
438 Utils->SetRemoteBursting(ServerSource, false);
440 if (params[0] == "*")
442 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));
444 else if (*(params[0].c_str()) == '#')
446 chanrec* c = this->Instance->FindChan(params[0]);
449 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
452 else if (*(params[0].c_str()) != '#')
454 userrec* u = this->Instance->FindNick(params[0]);
457 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
462 params[2] = ":" + params[2];
463 Utils->DoOneToAllButSender(prefix,"METADATA",params,prefix);
467 bool TreeSocket::ServerVersion(const std::string &prefix, std::deque<std::string> ¶ms)
469 if (params.size() < 1)
472 TreeServer* ServerSource = Utils->FindServer(prefix);
476 ServerSource->SetVersion(params[0]);
478 params[0] = ":" + params[0];
479 Utils->DoOneToAllButSender(prefix,"VERSION",params,prefix);
483 bool TreeSocket::ChangeHost(const std::string &prefix, std::deque<std::string> ¶ms)
485 if (params.size() < 1)
487 userrec* u = this->Instance->FindNick(prefix);
491 u->ChangeDisplayedHost(params[0].c_str());
492 Utils->DoOneToAllButSender(prefix,"FHOST",params,u->server);
497 bool TreeSocket::AddLine(const std::string &prefix, std::deque<std::string> ¶ms)
499 if (params.size() < 6)
501 bool propogate = false;
503 Utils->lines_to_apply = 0;
504 switch (*(params[0].c_str()))
507 propogate = Instance->XLines->add_zline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
508 Instance->XLines->zline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
510 Utils->lines_to_apply |= APPLY_ZLINES;
513 propogate = Instance->XLines->add_qline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
514 Instance->XLines->qline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
516 Utils->lines_to_apply |= APPLY_QLINES;
519 propogate = Instance->XLines->add_eline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
520 Instance->XLines->eline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
523 propogate = Instance->XLines->add_gline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
524 Instance->XLines->gline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
526 Utils->lines_to_apply |= APPLY_GLINES;
529 propogate = Instance->XLines->add_kline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
531 Utils->lines_to_apply |= APPLY_KLINES;
534 /* Just in case... */
535 this->Instance->SNO->WriteToSnoMask('x',"\2WARNING\2: Invalid xline type '"+params[0]+"' sent by server "+prefix+", ignored!");
539 /* Send it on its way */
542 if (atoi(params[4].c_str()))
544 time_t c_requires_crap = ConvToInt(params[4]) + Instance->Time();
545 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());
549 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());
551 params[5] = ":" + params[5];
552 Utils->DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
556 Instance->XLines->apply_lines(Utils->lines_to_apply);
557 Utils->lines_to_apply = 0;
562 bool TreeSocket::ChangeName(const std::string &prefix, std::deque<std::string> ¶ms)
564 if (params.size() < 1)
566 userrec* u = this->Instance->FindNick(prefix);
569 u->ChangeName(params[0].c_str());
570 params[0] = ":" + params[0];
571 Utils->DoOneToAllButSender(prefix,"FNAME",params,u->server);
576 bool TreeSocket::Whois(const std::string &prefix, std::deque<std::string> ¶ms)
578 if (params.size() < 1)
580 userrec* u = this->Instance->FindNick(prefix);
583 // an incoming request
584 if (params.size() == 1)
586 userrec* x = this->Instance->FindNick(params[0]);
587 if ((x) && (IS_LOCAL(x)))
589 userrec* x = this->Instance->FindNick(params[0]);
592 snprintf(signon, MAXBUF, "%lu", (unsigned long)x->signon);
593 snprintf(idle, MAXBUF, "%lu", (unsigned long)abs((x->idle_lastmsg) - Instance->Time(true)));
594 std::deque<std::string> par;
595 par.push_back(prefix);
596 par.push_back(signon);
598 // ours, we're done, pass it BACK
599 Utils->DoOneToOne(params[0], "IDLE", par, u->server);
603 // not ours pass it on
605 Utils->DoOneToOne(prefix, "IDLE", params, x->server);
608 else if (params.size() == 3)
610 std::string who_did_the_whois = params[0];
611 userrec* who_to_send_to = this->Instance->FindNick(who_did_the_whois);
612 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
614 // an incoming reply to a whois we sent out
615 std::string nick_whoised = prefix;
616 unsigned long signon = atoi(params[1].c_str());
617 unsigned long idle = atoi(params[2].c_str());
618 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
620 do_whois(this->Instance, who_to_send_to, u, signon, idle, nick_whoised.c_str());
625 // not ours, pass it on
627 Utils->DoOneToOne(prefix, "IDLE", params, who_to_send_to->server);
634 bool TreeSocket::Push(const std::string &prefix, std::deque<std::string> ¶ms)
636 if (params.size() < 2)
638 userrec* u = this->Instance->FindNick(params[0]);
647 // continue the raw onwards
648 params[1] = ":" + params[1];
649 Utils->DoOneToOne(prefix,"PUSH",params,u->server);
654 bool TreeSocket::HandleSetTime(const std::string &prefix, std::deque<std::string> ¶ms)
656 if (!params.size() || !Utils->EnableTimeSync)
661 if ((params.size() == 2) && (params[1] == "FORCE"))
664 time_t them = atoi(params[0].c_str());
665 time_t us = Instance->Time(false);
667 time_t diff = them - us;
669 Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
671 if (force || (them != us))
673 time_t old = Instance->SetTimeDelta(diff);
674 Instance->Log(DEBUG, "TS (diff %d) from %s applied (old delta was %d)", diff, prefix.c_str(), old);
680 bool TreeSocket::Time(const std::string &prefix, std::deque<std::string> ¶ms)
682 // :source.server TIME remote.server sendernick
683 // :remote.server TIME source.server sendernick TS
684 if (params.size() == 2)
686 // someone querying our time?
687 if (this->Instance->Config->ServerName == params[0])
689 userrec* u = this->Instance->FindNick(params[1]);
692 params.push_back(ConvToStr(Instance->Time(false)));
694 Utils->DoOneToOne(this->Instance->Config->ServerName,"TIME",params,params[0]);
699 // not us, pass it on
700 userrec* u = this->Instance->FindNick(params[1]);
702 Utils->DoOneToOne(prefix,"TIME",params,params[0]);
705 else if (params.size() == 3)
707 // a response to a previous TIME
708 userrec* u = this->Instance->FindNick(params[1]);
709 if ((u) && (IS_LOCAL(u)))
711 time_t rawtime = atol(params[2].c_str());
712 struct tm * timeinfo;
713 timeinfo = localtime(&rawtime);
715 snprintf(tms,26,"%s",asctime(timeinfo));
717 u->WriteServ("391 %s %s :%s",u->nick,prefix.c_str(),tms);
722 Utils->DoOneToOne(prefix,"TIME",params,u->server);
728 bool TreeSocket::LocalPing(const std::string &prefix, std::deque<std::string> ¶ms)
730 if (params.size() < 1)
732 if (params.size() == 1)
734 std::string stufftobounce = params[0];
735 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" PONG "+stufftobounce);
740 std::string forwardto = params[1];
741 if (forwardto == this->Instance->Config->ServerName)
743 // this is a ping for us, send back PONG to the requesting server
744 params[1] = params[0];
745 params[0] = forwardto;
746 Utils->DoOneToOne(forwardto,"PONG",params,params[1]);
750 // not for us, pass it on :)
751 Utils->DoOneToOne(prefix,"PING",params,forwardto);
757 /** TODO: This creates a total mess of output and needs to really use irc::modestacker.
759 bool TreeSocket::RemoveStatus(const std::string &prefix, std::deque<std::string> ¶ms)
761 if (params.size() < 1)
763 chanrec* c = Instance->FindChan(params[0]);
766 for (char modeletter = 'A'; modeletter <= 'z'; modeletter++)
768 ModeHandler* mh = Instance->Modes->FindMode(modeletter, MODETYPE_CHANNEL);
776 bool TreeSocket::RemoteServer(const std::string &prefix, std::deque<std::string> ¶ms)
778 if (params.size() < 5)
780 std::string servername = params[0];
781 std::string password = params[1];
782 // hopcount is not used for a remote server, we calculate this ourselves
783 std::string sid = params[3];
784 std::string description = params[4];
785 TreeServer* ParentOfThis = Utils->FindServer(prefix);
788 this->SendError("Protocol error - Introduced remote server from unknown server "+prefix);
791 TreeServer* CheckDupe = Utils->FindServer(servername);
794 this->SendError("Server "+servername+" already exists!");
795 this->Instance->SNO->WriteToSnoMask('l',"Server \2"+servername+"\2 being introduced from \2" + prefix + "\2 denied, already exists. Closing link with " + prefix);
799 Link* lnk = Utils->FindLink(servername);
801 TreeServer *Node = new TreeServer(this->Utils, this->Instance, servername, description, sid, ParentOfThis,NULL, lnk ? lnk->Hidden : false);
803 if (Node->DuplicateID())
805 this->SendError("Server ID "+sid+" already exists on the network!");
806 this->Instance->SNO->WriteToSnoMask('l',"Server \2"+servername+"\2 being introduced from \2" + prefix + "\2 denied, server ID already exists on the network. Closing link with " + prefix);
810 ParentOfThis->AddChild(Node);
811 params[4] = ":" + params[4];
812 Utils->SetRemoteBursting(Node, true);
813 Utils->DoOneToAllButSender(prefix,"SERVER",params,prefix);
814 this->Instance->SNO->WriteToSnoMask('l',"Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
818 bool TreeSocket::ComparePass(const std::string &ours, const std::string &theirs)
820 if ((!strncmp(ours.c_str(), "HMAC-SHA256:", 12)) || (!strncmp(theirs.c_str(), "HMAC-SHA256:", 12)))
822 /* One or both of us specified hmac sha256, but we don't have sha256 module loaded!
823 * We can't allow this password as valid.
825 if (!Instance->FindModule("m_sha256.so") || !Utils->ChallengeResponse)
828 /* Straight string compare of hashes */
829 return ours == theirs;
832 /* Straight string compare of plaintext */
833 return ours == theirs;
836 bool TreeSocket::Outbound_Reply_Server(std::deque<std::string> ¶ms)
838 if (params.size() < 5)
841 irc::string servername = params[0].c_str();
842 std::string sname = params[0];
843 std::string password = params[1];
844 std::string sid = params[3];
845 std::string description = params[4];
846 int hops = atoi(params[2].c_str());
848 this->InboundServerName = sname;
849 this->InboundDescription = description;
850 this->InboundSID = sid;
853 this->SendCapabilities();
857 this->SendError("Server too far away for authentication");
858 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
862 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
864 if ((x->Name == servername) && ((ComparePass(this->MakePass(x->RecvPass,this->GetOurChallenge()),password)) || (x->RecvPass == password && (this->GetTheirChallenge().empty()))))
866 TreeServer* CheckDupe = Utils->FindServer(sname);
869 this->SendError("Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
870 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
873 // Begin the sync here. this kickstarts the
874 // other side, waiting in WAIT_AUTH_2 state,
875 // into starting their burst, as it shows
877 this->LinkState = CONNECTED;
878 // we should add the details of this server now
879 // to the servers tree, as a child of the root
882 TreeServer *Node = new TreeServer(this->Utils, this->Instance, sname, description, sid, Utils->TreeRoot, this, x->Hidden);
884 if (Node->DuplicateID())
886 this->SendError("Server ID "+sid+" already exists on the network!");
887 this->Instance->SNO->WriteToSnoMask('l',"Server \2"+assign(servername)+"\2 being introduced denied, server ID already exists on the network. Closing link.");
891 Utils->TreeRoot->AddChild(Node);
892 params[4] = ":" + params[4];
893 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,sname);
894 this->bursting = true;
899 this->SendError("Invalid credentials");
900 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
904 bool TreeSocket::Inbound_Server(std::deque<std::string> ¶ms)
906 if (params.size() < 5)
908 irc::string servername = params[0].c_str();
909 std::string sname = params[0];
910 std::string password = params[1];
911 std::string sid = params[3];
912 std::string description = params[4];
914 int hops = atoi(params[2].c_str());
916 this->InboundServerName = sname;
917 this->InboundDescription = description;
918 this->InboundSID = sid;
920 OurSID += (char)((Instance->Config->sid / 100) + 48);
921 OurSID += (char)((Instance->Config->sid / 10) % 10 + 48);
922 OurSID += (char)(Instance->Config->sid % 10 + 48);
925 this->SendCapabilities();
929 this->SendError("Server too far away for authentication");
930 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
934 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
936 if ((x->Name == servername) && ((ComparePass(this->MakePass(x->RecvPass,this->GetOurChallenge()),password) || x->RecvPass == password && (this->GetTheirChallenge().empty()))))
938 /* First check for instances of the server that are waiting between the inbound and outbound SERVER command */
939 TreeSocket* CheckDupeSocket = Utils->FindBurstingServer(sname);
942 /* If we find one, we abort the link to prevent a race condition */
943 this->SendError("Negotiation collision");
944 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists in a negotiating state.");
945 CheckDupeSocket->SendError("Negotiation collision");
946 Instance->SE->DelFd(CheckDupeSocket);
947 CheckDupeSocket->Close();
950 /* Check for fully initialized instances of the server by id */
951 Instance->Log(DEBUG,"Looking for dupe SID %s", sid.c_str());
952 TreeServer* CheckDupeSID = Utils->FindServerID(sid);
955 this->SendError("Server ID "+CheckDupeSID->GetID()+" already exists on server "+CheckDupeSID->GetName()+"!");
956 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server ID '"+CheckDupeSID->GetID()+
957 "' already exists on server "+CheckDupeSID->GetName());
960 /* Now check for fully initialized instances of the server by name */
961 TreeServer* CheckDupe = Utils->FindServer(sname);
964 this->SendError("Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
965 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
968 this->Instance->SNO->WriteToSnoMask('l',"Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
971 std::string name = InspSocketNameRequest((Module*)Utils->Creator, this->Hook).Send();
972 this->Instance->SNO->WriteToSnoMask('l',"Connection from \2"+sname+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] using transport \2"+name+"\2");
975 Utils->AddBurstingServer(sname,this);
977 // this is good. Send our details: Our server name and description and hopcount of 0,
978 // along with the sendpass from this block.
979 this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+this->MakePass(x->SendPass, this->GetTheirChallenge())+" 0 "+OurSID+" :"+this->Instance->Config->ServerDesc);
980 // move to the next state, we are now waiting for THEM.
981 this->LinkState = WAIT_AUTH_2;
985 this->SendError("Invalid credentials");
986 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
990 void TreeSocket::Split(const std::string &line, std::deque<std::string> &n)
993 irc::tokenstream tokens(line);
995 while (tokens.GetToken(param))
1003 bool TreeSocket::ProcessLine(std::string &line)
1005 std::deque<std::string> params;
1006 irc::string command;
1009 line = line.substr(0, line.find_first_of("\r\n"));
1014 Instance->Log(DEBUG, "S[%d] I %s", this->GetFd(), line.c_str());
1016 this->Split(line.c_str(),params);
1021 if ((params[0][0] == ':') && (params.size() > 1))
1023 prefix = params[0].substr(1);
1026 command = params[0].c_str();
1028 switch (this->LinkState)
1033 // Waiting for SERVER command from remote server. Server initiating
1034 // the connection sends the first SERVER command, listening server
1035 // replies with theirs if its happy, then if the initiator is happy,
1036 // it starts to send its net sync, which starts the merge, otherwise
1037 // it sends an ERROR.
1038 if (command == "PASS")
1040 /* Silently ignored */
1042 else if (command == "SERVER")
1044 return this->Inbound_Server(params);
1046 else if (command == "ERROR")
1048 return this->Error(params);
1050 else if (command == "USER")
1052 this->SendError("Client connections to this port are prohibited.");
1055 else if (command == "CAPAB")
1057 return this->Capab(params);
1061 irc::string error = "Invalid command in negotiation phase: " + command;
1062 this->SendError(assign(error));
1067 // Waiting for start of other side's netmerge to say they liked our
1069 if (command == "SERVER")
1071 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1075 else if (command == "BURST")
1077 if (params.size() && Utils->EnableTimeSync)
1079 bool we_have_delta = (Instance->Time(false) != Instance->Time(true));
1080 time_t them = atoi(params[0].c_str());
1081 time_t delta = them - Instance->Time(false);
1082 if ((delta < -600) || (delta > 600))
1084 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));
1085 SendError("Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than five minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
1088 else if ((delta < -30) || (delta > 30))
1090 Instance->SNO->WriteToSnoMask('l',"\2WARNING\2: Your clocks are out by %d seconds. Please consider synching your clocks.", abs(delta));
1093 if (!Utils->MasterTime && !we_have_delta)
1095 this->Instance->SetTimeDelta(delta);
1096 // Send this new timestamp to any other servers
1097 Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
1100 this->LinkState = CONNECTED;
1101 Link* lnk = Utils->FindLink(InboundServerName);
1103 Node = new TreeServer(this->Utils,this->Instance, InboundServerName, InboundDescription, InboundSID, Utils->TreeRoot, this, lnk ? lnk->Hidden : false);
1105 if (Node->DuplicateID())
1107 this->SendError("Server ID "+InboundSID+" already exists on the network!");
1108 this->Instance->SNO->WriteToSnoMask('l',"Server \2"+InboundServerName+"\2 being introduced from \2" + prefix + "\2 denied, server ID already exists on the network. Closing link.");
1111 Utils->DelBurstingServer(this);
1112 Utils->TreeRoot->AddChild(Node);
1114 params.push_back(InboundServerName);
1115 params.push_back("*");
1116 params.push_back("1");
1117 params.push_back(InboundSID);
1118 params.push_back(":"+InboundDescription);
1119 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,InboundServerName);
1120 this->bursting = true;
1121 this->DoBurst(Node);
1123 else if (command == "ERROR")
1125 return this->Error(params);
1127 else if (command == "CAPAB")
1129 return this->Capab(params);
1134 this->SendError("Internal error -- listening socket accepted its own descriptor!!!");
1138 if (command == "SERVER")
1140 // another server we connected to, which was in WAIT_AUTH_1 state,
1141 // has just sent us their credentials. If we get this far, theyre
1142 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1143 // if we're happy with this, we should send our netburst which
1144 // kickstarts the merge.
1145 return this->Outbound_Reply_Server(params);
1147 else if (command == "ERROR")
1149 return this->Error(params);
1151 else if (command == "CAPAB")
1153 return this->Capab(params);
1157 // This is the 'authenticated' state, when all passwords
1158 // have been exchanged and anything past this point is taken
1161 if (!prefix.empty())
1163 std::string direction = prefix;
1165 userrec *t = this->Instance->FindUUID(prefix);
1168 direction = t->server;
1171 TreeServer* route_back_again = Utils->BestRouteTo(direction);
1172 if ((!route_back_again) || (route_back_again->GetSocket() != this))
1174 if (route_back_again)
1175 Instance->Log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
1179 * When there is activity on the socket, reset the ping counter so
1180 * that we're not wasting bandwidth pinging an active server.
1182 route_back_again->SetNextPingTime(time(NULL) + Utils->PingFreq);
1183 route_back_again->SetPingFlag();
1187 prefix = this->GetName();
1190 if ((command == "MODE") && (params.size() >= 2))
1192 chanrec* channel = Instance->FindChan(params[0]);
1195 userrec* x = Instance->FindNick(prefix);
1198 if (warned.find(x->server) == warned.end())
1200 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);
1201 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());
1202 warned[x->server] = x->nick;
1208 if (command == "SVSMODE")
1210 /* Services expects us to implement
1211 * SVSMODE. In inspircd its the same as
1217 /* Yes, know, this is a mess. Its reasonably fast though as we're
1218 * working with std::string here.
1220 if (command == "UID")
1222 return this->ParseUID(prefix, params);
1224 else if (command == "FJOIN")
1226 TreeServer* ServerSource = Utils->FindServer(prefix);
1228 Utils->SetRemoteBursting(ServerSource, false);
1229 return this->ForceJoin(prefix,params);
1231 else if (command == "STATS")
1233 return this->Stats(prefix, params);
1235 else if (command == "MOTD")
1237 return this->Motd(prefix, params);
1239 else if (command == "KILL" && Utils->IsServer(prefix))
1241 return this->RemoteKill(prefix,params);
1243 else if (command == "MODULES")
1245 return this->Modules(prefix, params);
1247 else if (command == "ADMIN")
1249 return this->Admin(prefix, params);
1251 else if (command == "SERVER")
1253 return this->RemoteServer(prefix,params);
1255 else if (command == "ERROR")
1257 return this->Error(params);
1259 else if (command == "OPERTYPE")
1261 return this->OperType(prefix,params);
1263 else if (command == "FMODE")
1265 TreeServer* ServerSource = Utils->FindServer(prefix);
1267 Utils->SetRemoteBursting(ServerSource, false);
1268 return this->ForceMode(prefix,params);
1270 else if (command == "FTOPIC")
1272 return this->ForceTopic(prefix,params);
1274 else if (command == "REHASH")
1276 return this->RemoteRehash(prefix,params);
1278 else if (command == "METADATA")
1280 return this->MetaData(prefix,params);
1282 else if (command == "REMSTATUS")
1284 return this->RemoveStatus(prefix,params);
1286 else if (command == "PING")
1289 prefix = this->GetName();
1291 * We just got a ping from a server that's bursting.
1292 * This can't be right, so set them to not bursting, and
1293 * apply their lines.
1295 TreeServer* ServerSource = Utils->FindServer(prefix);
1297 Utils->SetRemoteBursting(ServerSource, false);
1301 this->bursting = false;
1302 Instance->XLines->apply_lines(Utils->lines_to_apply);
1303 Utils->lines_to_apply = 0;
1306 return this->LocalPing(prefix,params);
1308 else if (command == "PONG")
1311 prefix = this->GetName();
1313 * We just got a pong from a server that's bursting.
1314 * This can't be right, so set them to not bursting, and
1315 * apply their lines.
1317 TreeServer* ServerSource = Utils->FindServer(prefix);
1319 Utils->SetRemoteBursting(ServerSource, false);
1323 this->bursting = false;
1324 Instance->XLines->apply_lines(Utils->lines_to_apply);
1325 Utils->lines_to_apply = 0;
1328 return this->LocalPong(prefix,params);
1330 else if (command == "VERSION")
1332 return this->ServerVersion(prefix,params);
1334 else if (command == "FHOST")
1336 return this->ChangeHost(prefix,params);
1338 else if (command == "FNAME")
1340 return this->ChangeName(prefix,params);
1342 else if (command == "ADDLINE")
1344 TreeServer* ServerSource = Utils->FindServer(prefix);
1346 Utils->SetRemoteBursting(ServerSource, false);
1347 return this->AddLine(prefix,params);
1349 else if (command == "SVSNICK")
1353 prefix = this->GetName();
1355 return this->ForceNick(prefix,params);
1357 else if (command == "OPERQUIT")
1359 return this->OperQuit(prefix,params);
1361 else if (command == "IDLE")
1363 return this->Whois(prefix,params);
1365 else if (command == "PUSH")
1367 return this->Push(prefix,params);
1369 else if (command == "TIMESET")
1371 return this->HandleSetTime(prefix, params);
1373 else if (command == "TIME")
1375 return this->Time(prefix,params);
1377 else if ((command == "KICK") && (Utils->IsServer(prefix)))
1379 std::string sourceserv = this->myhost;
1380 if (params.size() == 3)
1382 userrec* user = this->Instance->FindNick(params[1]);
1383 chanrec* chan = this->Instance->FindChan(params[0]);
1386 if (!chan->ServerKickUser(user, params[2].c_str(), false))
1387 /* Yikes, the channels gone! */
1391 if (!this->InboundServerName.empty())
1393 sourceserv = this->InboundServerName;
1395 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1397 else if (command == "SVSJOIN")
1401 prefix = this->GetName();
1403 return this->ServiceJoin(prefix,params);
1405 else if (command == "SQUIT")
1407 if (params.size() == 2)
1409 this->Squit(Utils->FindServer(params[0]),params[1]);
1413 else if (command == "OPERNOTICE")
1415 std::string sourceserv = this->myhost;
1416 if (!this->InboundServerName.empty())
1417 sourceserv = this->InboundServerName;
1418 if (params.size() >= 1)
1419 Instance->WriteOpers("*** From " + sourceserv + ": " + params[0]);
1420 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1422 else if (command == "MODENOTICE")
1424 std::string sourceserv = this->myhost;
1425 if (!this->InboundServerName.empty())
1426 sourceserv = this->InboundServerName;
1427 if (params.size() >= 2)
1429 Instance->WriteMode(params[0].c_str(), WM_AND, "*** From %s: %s", sourceserv.c_str(), params[1].c_str());
1431 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1433 else if (command == "SNONOTICE")
1435 std::string sourceserv = this->myhost;
1436 if (!this->InboundServerName.empty())
1437 sourceserv = this->InboundServerName;
1438 if (params.size() >= 2)
1440 Instance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + sourceserv + ": "+ params[1]);
1442 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1444 else if (command == "ENDBURST")
1446 this->bursting = false;
1447 Instance->XLines->apply_lines(Utils->lines_to_apply);
1448 Utils->lines_to_apply = 0;
1449 std::string sourceserv = this->myhost;
1450 if (!this->InboundServerName.empty())
1451 sourceserv = this->InboundServerName;
1452 this->Instance->SNO->WriteToSnoMask('l',"Received end of netburst from \2%s\2",sourceserv.c_str());
1454 Event rmode((char*)sourceserv.c_str(), (Module*)Utils->Creator, "new_server");
1455 rmode.Send(Instance);
1462 * Not a special s2s command. Emulate the user doing it.
1463 * This saves us having a huge ugly command parser again.
1465 userrec *who = this->Instance->FindUUID(prefix);
1467 std::string sourceserv = this->myhost;
1468 if (!this->InboundServerName.empty())
1470 sourceserv = this->InboundServerName;
1472 if ((!who) && (command == "MODE"))
1474 if (Utils->IsServer(prefix))
1476 const char* modelist[MAXPARAMETERS];
1477 for (size_t i = 0; i < params.size(); i++)
1478 modelist[i] = params[i].c_str();
1479 this->Instance->SendMode(modelist, params.size(), this->Instance->FakeClient);
1480 /* Hot potato! pass it on! */
1481 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1486 if ((command == "NICK") && (params.size() > 0))
1488 /* On nick messages, check that the nick doesnt
1489 * already exist here. If it does, kill their copy,
1492 userrec* x = this->Instance->FindNick(params[0]);
1493 if ((x) && (x != who))
1495 /* x is local, who is remote */
1496 this->DoCollision(x, who->age, who->ident, who->GetIPString(), who->uuid);
1499 Old nickname collision logic..
1500 std::deque<std::string> p;
1501 p.push_back(params[0]);
1502 p.push_back(":Nickname collision ("+prefix+" -> "+params[0]+")");
1503 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
1505 p.push_back(prefix);
1506 p.push_back(":Nickname collision");
1507 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
1508 userrec::QuitUser(this->Instance,x,"Nickname collision ("+prefix+" -> "+params[0]+")");
1509 userrec* y = this->Instance->FindNick(prefix);
1512 userrec::QuitUser(this->Instance,y,"Nickname collision");
1514 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1519 target = who->server;
1520 const char* strparams[127];
1521 for (unsigned int q = 0; q < params.size(); q++)
1523 strparams[q] = params[q].c_str();
1525 switch (this->Instance->CallCommandHandler(command.c_str(), strparams, params.size(), who))
1528 this->SendError("Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
1535 /* CMD_SUCCESS and CMD_USER_DELETED fall through here */
1541 // its not a user. Its either a server, or somethings screwed up.
1542 if (Utils->IsServer(prefix))
1543 target = this->Instance->Config->ServerName;
1547 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1556 std::string TreeSocket::GetName()
1558 std::string sourceserv = this->myhost;
1559 if (!this->InboundServerName.empty())
1561 sourceserv = this->InboundServerName;
1566 void TreeSocket::OnTimeout()
1568 if (this->LinkState == CONNECTING)
1570 Utils->Creator->RemoteMessage(NULL, "CONNECT: Connection to \002%s\002 timed out.", myhost.c_str());
1571 Link* MyLink = Utils->FindLink(myhost);
1573 Utils->DoFailOver(MyLink);
1577 void TreeSocket::OnClose()
1579 if (this->LinkState == LISTENER)
1582 // Connection closed.
1583 // If the connection is fully up (state CONNECTED)
1584 // then propogate a netsplit to all peers.
1585 std::string quitserver = this->myhost;
1586 if (!this->InboundServerName.empty())
1588 quitserver = this->InboundServerName;
1590 TreeServer* s = Utils->FindServer(quitserver);
1593 Squit(s,"Remote host closed the connection");
1596 if (!quitserver.empty())
1598 Utils->Creator->RemoteMessage(NULL,"Connection to '\2%s\2' failed.",quitserver.c_str());
1599 time_t server_uptime = Instance->Time() - this->age;
1601 Utils->Creator->RemoteMessage(NULL,"Connection to '\2%s\2' was established for %s", quitserver.c_str(), Utils->Creator->TimeToStr(server_uptime).c_str());
1605 int TreeSocket::OnIncomingConnection(int newsock, char* ip)
1607 /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
1608 * or discovering if this port is the server port, we don't allow connections from any
1609 * IPs for which we don't have a link block.
1613 found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), ip) != Utils->ValidIPs.end());
1616 for (vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
1617 if (irc::sockets::MatchCIDR(ip, (*i).c_str()))
1622 Utils->Creator->RemoteMessage(NULL,"Server connection from %s denied (no link blocks with that IP address)", ip);
1628 TreeSocket* s = new TreeSocket(this->Utils, this->Instance, newsock, ip, this->Hook);
1629 s = s; /* Whinge whinge whinge, thats all GCC ever does. */