1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
14 #include "configreader.h"
18 #include "commands/cmd_whois.h"
19 #include "commands/cmd_stats.h"
24 #include "transport.h"
25 #include "socketengine.h"
27 #include "m_spanningtree/main.h"
28 #include "m_spanningtree/utils.h"
29 #include "m_spanningtree/treeserver.h"
30 #include "m_spanningtree/link.h"
31 #include "m_spanningtree/treesocket.h"
32 #include "m_spanningtree/resolvers.h"
33 #include "m_spanningtree/handshaketimer.h"
35 /* $ModDep: m_spanningtree/timesynctimer.h m_spanningtree/resolvers.h m_spanningtree/main.h m_spanningtree/utils.h m_spanningtree/treeserver.h m_spanningtree/link.h m_spanningtree/treesocket.h */
37 int TreeSocket::WriteLine(std::string line)
39 Instance->Log(DEBUG, "-> %s", line.c_str());
41 return this->Write(line);
44 /* Handle ERROR command */
45 bool TreeSocket::Error(std::deque<std::string> ¶ms)
47 if (params.size() < 1)
49 this->Instance->SNO->WriteToSnoMask('l',"ERROR from %s: %s",(InboundServerName != "" ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
50 /* we will return false to cause the socket to close. */
54 bool TreeSocket::Modules(const std::string &prefix, std::deque<std::string> ¶ms)
59 if (!this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
61 /* Pass it on, not for us */
62 Utils->DoOneToOne(prefix, "MODULES", params, params[0]);
67 std::deque<std::string> par;
68 par.push_back(prefix);
71 userrec* source = this->Instance->FindNick(prefix);
75 for (unsigned int i = 0; i < Instance->Config->module_names.size(); i++)
77 Version V = Instance->modules[i]->GetVersion();
78 char modulename[MAXBUF];
79 char flagstate[MAXBUF];
81 if (V.Flags & VF_STATIC)
82 strlcat(flagstate,", static",MAXBUF);
83 if (V.Flags & VF_VENDOR)
84 strlcat(flagstate,", vendor",MAXBUF);
85 if (V.Flags & VF_COMMON)
86 strlcat(flagstate,", common",MAXBUF);
87 if (V.Flags & VF_SERVICEPROVIDER)
88 strlcat(flagstate,", service provider",MAXBUF);
90 strcpy(flagstate," <no flags>");
91 strlcpy(modulename,Instance->Config->module_names[i].c_str(),256);
94 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);
98 snprintf(strbuf, MAXBUF, "::%s 900 %s :%s",Instance->Config->ServerName,source->nick,ServerConfig::CleanFilename(modulename));
101 Utils->DoOneToOne(Instance->Config->ServerName, "PUSH", par, source->server);
103 snprintf(strbuf, MAXBUF, "::%s 901 %s :End of MODULES list", Instance->Config->ServerName, source->nick);
105 Utils->DoOneToOne(Instance->Config->ServerName, "PUSH", par, source->server);
109 /** remote MOTD. leet, huh? */
110 bool TreeSocket::Motd(const std::string &prefix, std::deque<std::string> ¶ms)
112 if (params.size() > 0)
114 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
116 /* It's for our server */
118 userrec* source = this->Instance->FindNick(prefix);
122 std::deque<std::string> par;
123 par.push_back(prefix);
126 if (!Instance->Config->MOTD.size())
128 par[1] = std::string("::")+Instance->Config->ServerName+" 422 "+source->nick+" :Message of the day file is missing.";
129 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
133 par[1] = std::string("::")+Instance->Config->ServerName+" 375 "+source->nick+" :"+Instance->Config->ServerName+" message of the day";
134 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
136 for (unsigned int i = 0; i < Instance->Config->MOTD.size(); i++)
138 par[1] = std::string("::")+Instance->Config->ServerName+" 372 "+source->nick+" :- "+Instance->Config->MOTD[i];
139 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
142 par[1] = std::string("::")+Instance->Config->ServerName+" 376 "+source->nick+" End of message of the day.";
143 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
149 userrec* source = this->Instance->FindNick(prefix);
151 Utils->DoOneToOne(prefix, "MOTD", params, params[0]);
157 /** remote ADMIN. leet, huh? */
158 bool TreeSocket::Admin(const std::string &prefix, std::deque<std::string> ¶ms)
160 if (params.size() > 0)
162 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
164 /* It's for our server */
166 userrec* source = this->Instance->FindNick(prefix);
169 std::deque<std::string> par;
170 par.push_back(prefix);
172 par[1] = std::string("::")+Instance->Config->ServerName+" 256 "+source->nick+" :Administrative info for "+Instance->Config->ServerName;
173 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
174 par[1] = std::string("::")+Instance->Config->ServerName+" 257 "+source->nick+" :Name - "+Instance->Config->AdminName;
175 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
176 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :Nickname - "+Instance->Config->AdminNick;
177 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
178 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :E-Mail - "+Instance->Config->AdminEmail;
179 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
185 userrec* source = this->Instance->FindNick(prefix);
187 Utils->DoOneToOne(prefix, "ADMIN", params, params[0]);
193 bool TreeSocket::Stats(const std::string &prefix, std::deque<std::string> ¶ms)
195 /* Get the reply to a STATS query if it matches this servername,
196 * and send it back as a load of PUSH queries
198 if (params.size() > 1)
200 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[1]))
202 /* It's for our server */
204 userrec* source = this->Instance->FindNick(prefix);
207 std::deque<std::string> par;
208 par.push_back(prefix);
210 DoStats(this->Instance, *(params[0].c_str()), source, results);
211 for (size_t i = 0; i < results.size(); i++)
213 par[1] = "::" + results[i];
214 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
221 userrec* source = this->Instance->FindNick(prefix);
223 Utils->DoOneToOne(prefix, "STATS", params, params[1]);
230 /** Because the core won't let users or even SERVERS set +o,
231 * we use the OPERTYPE command to do this.
233 bool TreeSocket::OperType(const std::string &prefix, std::deque<std::string> ¶ms)
235 if (params.size() != 1)
237 std::string opertype = params[0];
238 userrec* u = this->Instance->FindNick(prefix);
241 u->modes[UM_OPERATOR] = 1;
242 this->Instance->all_opers.push_back(u);
243 strlcpy(u->oper,opertype.c_str(),NICKMAX-1);
244 Utils->DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
245 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()));
250 /** Because Andy insists that services-compatible servers must
251 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
253 bool TreeSocket::ForceNick(const std::string &prefix, std::deque<std::string> ¶ms)
255 if (params.size() < 3)
258 userrec* u = this->Instance->FindNick(params[0]);
262 Utils->DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
265 std::deque<std::string> par;
266 par.push_back(params[1]);
267 if (!u->ForceNickChange(params[1].c_str()))
269 userrec::QuitUser(this->Instance, u, "Nickname collision");
272 u->age = atoi(params[2].c_str());
278 bool TreeSocket::OperQuit(const std::string &prefix, std::deque<std::string> ¶ms)
280 if (params.size() < 1)
283 userrec* u = this->Instance->FindNick(prefix);
287 Utils->DoOneToAllButSender(prefix,"OPERQUIT",params,prefix);
288 u->SetOperQuit(params[0]);
294 * Remote SQUIT (RSQUIT). Routing works similar to SVSNICK: Route it to the server that the target is connected to locally,
295 * then let that server do the dirty work (squit it!). Example:
296 * 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
298 bool TreeSocket::RemoteSquit(const std::string &prefix, std::deque<std::string> ¶ms)
300 /* ok.. :w00t RSQUIT jupe.barafranca.com :reason here */
301 if (params.size() < 2)
304 TreeServer* s = Utils->FindServerMask(params[0]);
308 if (s == Utils->TreeRoot)
310 this->Instance->SNO->WriteToSnoMask('l',"What the fuck, I recieved a remote SQUIT for myself? :< (from %s", prefix.c_str());
314 TreeSocket* sock = s->GetSocket();
318 /* it's locally connected, KILL IT! */
319 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());
320 sock->Squit(s,"Server quit by " + prefix + ": " + params[1]);
321 Instance->SE->DelFd(sock);
327 /* route the rsquit */
328 params[1] = ":" + params[1];
329 Utils->DoOneToOne(prefix, "RSQUIT", params, params[0]);
334 /* mother fucker! it doesn't exist */
340 bool TreeSocket::ServiceJoin(const std::string &prefix, std::deque<std::string> ¶ms)
342 if (params.size() < 2)
345 userrec* u = this->Instance->FindNick(params[0]);
349 /* only join if it's local, otherwise just pass it on! */
351 chanrec::JoinUser(this->Instance, u, params[1].c_str(), false, "", Instance->Time());
352 Utils->DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
357 bool TreeSocket::RemoteRehash(const std::string &prefix, std::deque<std::string> ¶ms)
359 if (params.size() < 1)
362 std::string servermask = params[0];
364 if (this->Instance->MatchText(this->Instance->Config->ServerName,servermask))
366 this->Instance->SNO->WriteToSnoMask('l',"Remote rehash initiated by \002"+prefix+"\002.");
367 this->Instance->RehashServer();
368 Utils->ReadConfiguration(false);
369 InitializeDisabledCommands(Instance->Config->DisabledCommands, Instance);
371 Utils->DoOneToAllButSender(prefix,"REHASH",params,prefix);
375 bool TreeSocket::RemoteKill(const std::string &prefix, std::deque<std::string> ¶ms)
377 if (params.size() != 2)
380 std::string nick = params[0];
381 userrec* u = this->Instance->FindNick(prefix);
382 userrec* who = this->Instance->FindNick(nick);
386 /* Prepend kill source, if we don't have one */
387 std::string sourceserv = prefix;
390 sourceserv = u->server;
392 if (*(params[1].c_str()) != '[')
394 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
396 std::string reason = params[1];
397 params[1] = ":" + params[1];
398 Utils->DoOneToAllButSender(prefix,"KILL",params,sourceserv);
399 who->Write(":%s KILL %s :%s (%s)", sourceserv.c_str(), who->nick, sourceserv.c_str(), reason.c_str());
400 userrec::QuitUser(this->Instance,who,reason);
405 bool TreeSocket::LocalPong(const std::string &prefix, std::deque<std::string> ¶ms)
407 if (params.size() < 1)
410 if (params.size() == 1)
412 TreeServer* ServerSource = Utils->FindServer(prefix);
415 ServerSource->SetPingFlag();
416 ServerSource->rtt = Instance->Time() - ServerSource->LastPing;
421 std::string forwardto = params[1];
422 if (forwardto == this->Instance->Config->ServerName)
425 * this is a PONG for us
426 * if the prefix is a user, check theyre local, and if they are,
427 * dump the PONG reply back to their fd. If its a server, do nowt.
428 * Services might want to send these s->s, but we dont need to yet.
430 userrec* u = this->Instance->FindNick(prefix);
433 u->WriteServ("PONG %s %s",params[0].c_str(),params[1].c_str());
438 // not for us, pass it on :)
439 Utils->DoOneToOne(prefix,"PONG",params,forwardto);
446 bool TreeSocket::MetaData(const std::string &prefix, std::deque<std::string> ¶ms)
448 if (params.size() < 2)
451 params.push_back("");
452 TreeServer* ServerSource = Utils->FindServer(prefix);
455 if (params[0] == "*")
457 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));
459 else if (*(params[0].c_str()) == '#')
461 chanrec* c = this->Instance->FindChan(params[0]);
464 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
467 else if (*(params[0].c_str()) != '#')
469 userrec* u = this->Instance->FindNick(params[0]);
472 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
477 params[2] = ":" + params[2];
478 Utils->DoOneToAllButSender(prefix,"METADATA",params,prefix);
482 bool TreeSocket::ServerVersion(const std::string &prefix, std::deque<std::string> ¶ms)
484 if (params.size() < 1)
487 TreeServer* ServerSource = Utils->FindServer(prefix);
491 ServerSource->SetVersion(params[0]);
493 params[0] = ":" + params[0];
494 Utils->DoOneToAllButSender(prefix,"VERSION",params,prefix);
498 bool TreeSocket::ChangeHost(const std::string &prefix, std::deque<std::string> ¶ms)
500 if (params.size() < 1)
502 userrec* u = this->Instance->FindNick(prefix);
506 u->ChangeDisplayedHost(params[0].c_str());
507 Utils->DoOneToAllButSender(prefix,"FHOST",params,u->server);
512 bool TreeSocket::AddLine(const std::string &prefix, std::deque<std::string> ¶ms)
514 if (params.size() < 6)
516 bool propogate = false;
518 Utils->lines_to_apply = 0;
519 switch (*(params[0].c_str()))
522 propogate = Instance->XLines->add_zline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
523 Instance->XLines->zline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
525 Utils->lines_to_apply |= APPLY_ZLINES;
528 propogate = Instance->XLines->add_qline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
529 Instance->XLines->qline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
531 Utils->lines_to_apply |= APPLY_QLINES;
534 propogate = Instance->XLines->add_eline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
535 Instance->XLines->eline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
538 propogate = Instance->XLines->add_gline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
539 Instance->XLines->gline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
541 Utils->lines_to_apply |= APPLY_GLINES;
544 propogate = Instance->XLines->add_kline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
546 Utils->lines_to_apply |= APPLY_KLINES;
549 /* Just in case... */
550 this->Instance->SNO->WriteToSnoMask('x',"\2WARNING\2: Invalid xline type '"+params[0]+"' sent by server "+prefix+", ignored!");
554 /* Send it on its way */
557 if (atoi(params[4].c_str()))
559 time_t c_requires_crap = ConvToInt(params[4]) + Instance->Time();
560 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());
564 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());
566 params[5] = ":" + params[5];
567 Utils->DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
571 Instance->XLines->apply_lines(Utils->lines_to_apply);
572 Utils->lines_to_apply = 0;
577 bool TreeSocket::ChangeName(const std::string &prefix, std::deque<std::string> ¶ms)
579 if (params.size() < 1)
581 userrec* u = this->Instance->FindNick(prefix);
584 u->ChangeName(params[0].c_str());
585 params[0] = ":" + params[0];
586 Utils->DoOneToAllButSender(prefix,"FNAME",params,u->server);
591 bool TreeSocket::Whois(const std::string &prefix, std::deque<std::string> ¶ms)
593 if (params.size() < 1)
595 userrec* u = this->Instance->FindNick(prefix);
598 // an incoming request
599 if (params.size() == 1)
601 userrec* x = this->Instance->FindNick(params[0]);
602 if ((x) && (IS_LOCAL(x)))
604 userrec* x = this->Instance->FindNick(params[0]);
607 snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
608 snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-Instance->Time(true)));
609 std::deque<std::string> par;
610 par.push_back(prefix);
611 par.push_back(signon);
613 // ours, we're done, pass it BACK
614 Utils->DoOneToOne(params[0],"IDLE",par,u->server);
618 // not ours pass it on
619 Utils->DoOneToOne(prefix,"IDLE",params,x->server);
622 else if (params.size() == 3)
624 std::string who_did_the_whois = params[0];
625 userrec* who_to_send_to = this->Instance->FindNick(who_did_the_whois);
626 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
628 // an incoming reply to a whois we sent out
629 std::string nick_whoised = prefix;
630 unsigned long signon = atoi(params[1].c_str());
631 unsigned long idle = atoi(params[2].c_str());
632 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
633 do_whois(this->Instance,who_to_send_to,u,signon,idle,nick_whoised.c_str());
637 // not ours, pass it on
638 Utils->DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
645 bool TreeSocket::Push(const std::string &prefix, std::deque<std::string> ¶ms)
647 if (params.size() < 2)
649 userrec* u = this->Instance->FindNick(params[0]);
658 // continue the raw onwards
659 params[1] = ":" + params[1];
660 Utils->DoOneToOne(prefix,"PUSH",params,u->server);
665 bool TreeSocket::HandleSetTime(const std::string &prefix, std::deque<std::string> ¶ms)
667 if (!params.size() || !Utils->EnableTimeSync)
672 if ((params.size() == 2) && (params[1] == "FORCE"))
675 time_t them = atoi(params[0].c_str());
676 time_t us = Instance->Time(false);
678 time_t diff = them - us;
680 Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
682 if (force || (them != us))
684 time_t old = Instance->SetTimeDelta(diff);
685 Instance->Log(DEBUG, "TS (diff %d) from %s applied (old delta was %d)", diff, prefix.c_str(), old);
691 bool TreeSocket::Time(const std::string &prefix, std::deque<std::string> ¶ms)
693 // :source.server TIME remote.server sendernick
694 // :remote.server TIME source.server sendernick TS
695 if (params.size() == 2)
697 // someone querying our time?
698 if (this->Instance->Config->ServerName == params[0])
700 userrec* u = this->Instance->FindNick(params[1]);
703 params.push_back(ConvToStr(Instance->Time(false)));
705 Utils->DoOneToOne(this->Instance->Config->ServerName,"TIME",params,params[0]);
710 // not us, pass it on
711 userrec* u = this->Instance->FindNick(params[1]);
713 Utils->DoOneToOne(prefix,"TIME",params,params[0]);
716 else if (params.size() == 3)
718 // a response to a previous TIME
719 userrec* u = this->Instance->FindNick(params[1]);
720 if ((u) && (IS_LOCAL(u)))
722 time_t rawtime = atol(params[2].c_str());
723 struct tm * timeinfo;
724 timeinfo = localtime(&rawtime);
726 snprintf(tms,26,"%s",asctime(timeinfo));
728 u->WriteServ("391 %s %s :%s",u->nick,prefix.c_str(),tms);
733 Utils->DoOneToOne(prefix,"TIME",params,u->server);
739 bool TreeSocket::LocalPing(const std::string &prefix, std::deque<std::string> ¶ms)
741 if (params.size() < 1)
743 if (params.size() == 1)
745 std::string stufftobounce = params[0];
746 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" PONG "+stufftobounce);
751 std::string forwardto = params[1];
752 if (forwardto == this->Instance->Config->ServerName)
754 // this is a ping for us, send back PONG to the requesting server
755 params[1] = params[0];
756 params[0] = forwardto;
757 Utils->DoOneToOne(forwardto,"PONG",params,params[1]);
761 // not for us, pass it on :)
762 Utils->DoOneToOne(prefix,"PING",params,forwardto);
768 /** TODO: This creates a total mess of output and needs to really use irc::modestacker.
770 bool TreeSocket::RemoveStatus(const std::string &prefix, std::deque<std::string> ¶ms)
772 if (params.size() < 1)
774 chanrec* c = Instance->FindChan(params[0]);
777 for (char modeletter = 'A'; modeletter <= 'z'; modeletter++)
779 ModeHandler* mh = Instance->Modes->FindMode(modeletter, MODETYPE_CHANNEL);
787 bool TreeSocket::RemoteServer(const std::string &prefix, std::deque<std::string> ¶ms)
789 if (params.size() < 4)
791 std::string servername = params[0];
792 std::string password = params[1];
793 // hopcount is not used for a remote server, we calculate this ourselves
794 std::string description = params[3];
795 TreeServer* ParentOfThis = Utils->FindServer(prefix);
798 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
801 TreeServer* CheckDupe = Utils->FindServer(servername);
804 this->WriteLine("ERROR :Server "+servername+" already exists!");
805 this->Instance->SNO->WriteToSnoMask('l',"Server \2"+servername+"\2 being introduced from \2" + prefix + "\2 denied, already exists. Closing link with " + prefix);
808 Link* lnk = Utils->FindLink(servername);
809 TreeServer* Node = new TreeServer(this->Utils,this->Instance,servername,description,ParentOfThis,NULL, lnk ? lnk->Hidden : false);
810 ParentOfThis->AddChild(Node);
811 params[3] = ":" + params[3];
812 Utils->DoOneToAllButSender(prefix,"SERVER",params,prefix);
813 this->Instance->SNO->WriteToSnoMask('l',"Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
817 bool TreeSocket::ComparePass(const std::string &ours, const std::string &theirs)
819 if ((!strncmp(ours.c_str(), "HMAC-SHA256:", 12)) || (!strncmp(theirs.c_str(), "HMAC-SHA256:", 12)))
821 /* One or both of us specified hmac sha256, but we don't have sha256 module loaded!
822 * We can't allow this password as valid.
824 if (!Instance->FindModule("m_sha256.so") || !Utils->ChallengeResponse)
827 /* Straight string compare of hashes */
828 return ours == theirs;
831 /* Straight string compare of plaintext */
832 return ours == theirs;
835 bool TreeSocket::Outbound_Reply_Server(std::deque<std::string> ¶ms)
837 if (params.size() < 4)
840 irc::string servername = params[0].c_str();
841 std::string sname = params[0];
842 std::string password = params[1];
843 int hops = atoi(params[2].c_str());
847 this->WriteLine("ERROR :Server too far away for authentication");
848 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
851 std::string description = params[3];
852 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
854 if ((x->Name == servername) && (ComparePass(this->MakePass(x->RecvPass,this->GetOurChallenge()),password)))
856 TreeServer* CheckDupe = Utils->FindServer(sname);
859 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
860 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
863 // Begin the sync here. this kickstarts the
864 // other side, waiting in WAIT_AUTH_2 state,
865 // into starting their burst, as it shows
867 this->LinkState = CONNECTED;
868 // we should add the details of this server now
869 // to the servers tree, as a child of the root
871 TreeServer* Node = new TreeServer(this->Utils,this->Instance,sname,description,Utils->TreeRoot,this,x->Hidden);
872 Utils->TreeRoot->AddChild(Node);
873 params[3] = ":" + params[3];
874 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,sname);
875 this->bursting = true;
880 this->WriteLine("ERROR :Invalid credentials");
881 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
885 bool TreeSocket::Inbound_Server(std::deque<std::string> ¶ms)
887 if (params.size() < 4)
889 irc::string servername = params[0].c_str();
890 std::string sname = params[0];
891 std::string password = params[1];
892 int hops = atoi(params[2].c_str());
896 this->WriteLine("ERROR :Server too far away for authentication");
897 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
900 std::string description = params[3];
901 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
903 if ((x->Name == servername) && (ComparePass(this->MakePass(x->RecvPass,this->GetOurChallenge()),password)))
905 TreeServer* CheckDupe = Utils->FindServer(sname);
908 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
909 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
912 this->Instance->SNO->WriteToSnoMask('l',"Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
915 std::string name = InspSocketNameRequest((Module*)Utils->Creator, this->Hook).Send();
916 this->Instance->SNO->WriteToSnoMask('l',"Connection from \2"+sname+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] using transport \2"+name+"\2");
919 this->InboundServerName = sname;
920 this->InboundDescription = description;
921 // this is good. Send our details: Our server name and description and hopcount of 0,
922 // along with the sendpass from this block.
923 this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+this->MakePass(x->SendPass, this->GetTheirChallenge())+" 0 :"+this->Instance->Config->ServerDesc);
924 // move to the next state, we are now waiting for THEM.
925 this->LinkState = WAIT_AUTH_2;
929 this->WriteLine("ERROR :Invalid credentials");
930 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
934 void TreeSocket::Split(const std::string &line, std::deque<std::string> &n)
937 irc::tokenstream tokens(line);
939 while (tokens.GetToken(param))
944 bool TreeSocket::ProcessLine(std::string &line)
946 std::deque<std::string> params;
950 line = line.substr(0, line.find_first_of("\r\n"));
955 Instance->Log(DEBUG, "<- %s", line.c_str());
957 this->Split(line.c_str(),params);
959 if ((params[0][0] == ':') && (params.size() > 1))
961 prefix = params[0].substr(1);
964 command = params[0].c_str();
966 switch (this->LinkState)
971 // Waiting for SERVER command from remote server. Server initiating
972 // the connection sends the first SERVER command, listening server
973 // replies with theirs if its happy, then if the initiator is happy,
974 // it starts to send its net sync, which starts the merge, otherwise
975 // it sends an ERROR.
976 if (command == "PASS")
978 /* Silently ignored */
980 else if (command == "SERVER")
982 return this->Inbound_Server(params);
984 else if (command == "ERROR")
986 return this->Error(params);
988 else if (command == "USER")
990 this->WriteLine("ERROR :Client connections to this port are prohibited.");
993 else if (command == "CAPAB")
995 return this->Capab(params);
997 else if ((command == "U") || (command == "S"))
999 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
1004 std::string error("ERROR :Invalid command in negotiation phase: ");
1005 error.append(command.c_str());
1006 this->WriteLine(error);
1011 // Waiting for start of other side's netmerge to say they liked our
1013 if (command == "SERVER")
1015 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1019 else if ((command == "U") || (command == "S"))
1021 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
1024 else if (command == "BURST")
1026 if (params.size() && Utils->EnableTimeSync)
1028 bool we_have_delta = (Instance->Time(false) != Instance->Time(true));
1029 time_t them = atoi(params[0].c_str());
1030 time_t delta = them - Instance->Time(false);
1031 if ((delta < -300) || (delta > 300))
1033 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));
1034 WriteLine("ERROR :Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than ten minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
1037 else if ((delta < -30) || (delta > 30))
1039 Instance->SNO->WriteToSnoMask('l',"\2WARNING\2: Your clocks are out by %d seconds. Please consider synching your clocks.", abs(delta));
1042 if (!Utils->MasterTime && !we_have_delta)
1044 this->Instance->SetTimeDelta(delta);
1045 // Send this new timestamp to any other servers
1046 Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
1049 this->LinkState = CONNECTED;
1050 Link* lnk = Utils->FindLink(InboundServerName);
1051 Node = new TreeServer(this->Utils,this->Instance, InboundServerName, InboundDescription, Utils->TreeRoot, this, lnk ? lnk->Hidden : false);
1052 Utils->TreeRoot->AddChild(Node);
1054 params.push_back(InboundServerName);
1055 params.push_back("*");
1056 params.push_back("1");
1057 params.push_back(":"+InboundDescription);
1058 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,InboundServerName);
1059 this->bursting = true;
1060 this->DoBurst(Node);
1062 else if (command == "ERROR")
1064 return this->Error(params);
1066 else if (command == "CAPAB")
1068 return this->Capab(params);
1073 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
1077 if (command == "SERVER")
1079 // another server we connected to, which was in WAIT_AUTH_1 state,
1080 // has just sent us their credentials. If we get this far, theyre
1081 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1082 // if we're happy with this, we should send our netburst which
1083 // kickstarts the merge.
1084 return this->Outbound_Reply_Server(params);
1086 else if (command == "ERROR")
1088 return this->Error(params);
1090 else if (command == "CAPAB")
1092 return this->Capab(params);
1096 // This is the 'authenticated' state, when all passwords
1097 // have been exchanged and anything past this point is taken
1102 std::string direction = prefix;
1103 userrec* t = this->Instance->FindNick(prefix);
1106 direction = t->server;
1108 TreeServer* route_back_again = Utils->BestRouteTo(direction);
1109 if ((!route_back_again) || (route_back_again->GetSocket() != this))
1111 if (route_back_again)
1112 Instance->Log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
1116 * When there is activity on the socket, reset the ping counter so
1117 * that we're not wasting bandwidth pinging an active server.
1119 route_back_again->SetNextPingTime(time(NULL) + 60);
1120 route_back_again->SetPingFlag();
1123 if (command == "SVSMODE")
1125 /* Services expects us to implement
1126 * SVSMODE. In inspircd its the same as
1131 std::string target = "";
1132 /* Yes, know, this is a mess. Its reasonably fast though as we're
1133 * working with std::string here.
1135 if ((command == "NICK") && (params.size() >= 8))
1137 return this->IntroduceClient(prefix,params);
1139 else if (command == "FJOIN")
1141 return this->ForceJoin(prefix,params);
1143 else if (command == "STATS")
1145 return this->Stats(prefix, params);
1147 else if (command == "MOTD")
1149 return this->Motd(prefix, params);
1151 else if (command == "MODULES")
1153 return this->Modules(prefix, params);
1155 else if (command == "ADMIN")
1157 return this->Admin(prefix, params);
1159 else if (command == "SERVER")
1161 return this->RemoteServer(prefix,params);
1163 else if (command == "ERROR")
1165 return this->Error(params);
1167 else if (command == "OPERTYPE")
1169 return this->OperType(prefix,params);
1171 else if (command == "FMODE")
1173 return this->ForceMode(prefix,params);
1175 else if (command == "KILL")
1177 return this->RemoteKill(prefix,params);
1179 else if (command == "FTOPIC")
1181 return this->ForceTopic(prefix,params);
1183 else if (command == "REHASH")
1185 return this->RemoteRehash(prefix,params);
1187 else if (command == "METADATA")
1189 return this->MetaData(prefix,params);
1191 else if (command == "REMSTATUS")
1193 return this->RemoveStatus(prefix,params);
1195 else if (command == "PING")
1198 * We just got a ping from a server that's bursting.
1199 * This can't be right, so set them to not bursting, and
1200 * apply their lines.
1204 this->bursting = false;
1205 Instance->XLines->apply_lines(Utils->lines_to_apply);
1206 Utils->lines_to_apply = 0;
1210 prefix = this->GetName();
1212 return this->LocalPing(prefix,params);
1214 else if (command == "PONG")
1217 * We just got a pong from a server that's bursting.
1218 * This can't be right, so set them to not bursting, and
1219 * apply their lines.
1223 this->bursting = false;
1224 Instance->XLines->apply_lines(Utils->lines_to_apply);
1225 Utils->lines_to_apply = 0;
1229 prefix = this->GetName();
1231 return this->LocalPong(prefix,params);
1233 else if (command == "VERSION")
1235 return this->ServerVersion(prefix,params);
1237 else if (command == "FHOST")
1239 return this->ChangeHost(prefix,params);
1241 else if (command == "FNAME")
1243 return this->ChangeName(prefix,params);
1245 else if (command == "ADDLINE")
1247 return this->AddLine(prefix,params);
1249 else if (command == "SVSNICK")
1253 prefix = this->GetName();
1255 return this->ForceNick(prefix,params);
1257 else if (command == "OPERQUIT")
1259 return this->OperQuit(prefix,params);
1261 else if (command == "RSQUIT")
1263 return this->RemoteSquit(prefix, params);
1265 else if (command == "IDLE")
1267 return this->Whois(prefix,params);
1269 else if (command == "PUSH")
1271 return this->Push(prefix,params);
1273 else if (command == "TIMESET")
1275 return this->HandleSetTime(prefix, params);
1277 else if (command == "TIME")
1279 return this->Time(prefix,params);
1281 else if ((command == "KICK") && (Utils->IsServer(prefix)))
1283 std::string sourceserv = this->myhost;
1284 if (params.size() == 3)
1286 userrec* user = this->Instance->FindNick(params[1]);
1287 chanrec* chan = this->Instance->FindChan(params[0]);
1290 if (!chan->ServerKickUser(user, params[2].c_str(), false))
1291 /* Yikes, the channels gone! */
1295 if (this->InboundServerName != "")
1297 sourceserv = this->InboundServerName;
1299 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1301 else if (command == "SVSJOIN")
1305 prefix = this->GetName();
1307 return this->ServiceJoin(prefix,params);
1309 else if (command == "SQUIT")
1311 if (params.size() == 2)
1313 this->Squit(Utils->FindServer(params[0]),params[1]);
1317 else if (command == "OPERNOTICE")
1319 std::string sourceserv = this->myhost;
1320 if (this->InboundServerName != "")
1321 sourceserv = this->InboundServerName;
1322 if (params.size() >= 1)
1323 Instance->WriteOpers("*** From " + sourceserv + ": " + params[0]);
1324 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1326 else if (command == "MODENOTICE")
1328 std::string sourceserv = this->myhost;
1329 if (this->InboundServerName != "")
1330 sourceserv = this->InboundServerName;
1331 if (params.size() >= 2)
1333 Instance->WriteMode(params[0].c_str(), WM_AND, "*** From %s: %s", sourceserv.c_str(), params[1].c_str());
1335 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1337 else if (command == "SNONOTICE")
1339 std::string sourceserv = this->myhost;
1340 if (this->InboundServerName != "")
1341 sourceserv = this->InboundServerName;
1342 if (params.size() >= 2)
1344 Instance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + sourceserv + ": "+ params[1]);
1346 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1348 else if (command == "ENDBURST")
1350 this->bursting = false;
1351 Instance->XLines->apply_lines(Utils->lines_to_apply);
1352 Utils->lines_to_apply = 0;
1353 std::string sourceserv = this->myhost;
1354 if (this->InboundServerName != "")
1356 sourceserv = this->InboundServerName;
1358 this->Instance->SNO->WriteToSnoMask('l',"Received end of netburst from \2%s\2",sourceserv.c_str());
1360 Event rmode((char*)sourceserv.c_str(), (Module*)Utils->Creator, "new_server");
1361 rmode.Send(Instance);
1367 // not a special inter-server command.
1368 // Emulate the actual user doing the command,
1369 // this saves us having a huge ugly parser.
1370 userrec* who = this->Instance->FindNick(prefix);
1371 std::string sourceserv = this->myhost;
1372 if (this->InboundServerName != "")
1374 sourceserv = this->InboundServerName;
1376 if ((!who) && (command == "MODE"))
1378 if (Utils->IsServer(prefix))
1380 const char* modelist[127];
1381 for (size_t i = 0; i < params.size(); i++)
1382 modelist[i] = params[i].c_str();
1383 userrec* fake = new userrec(Instance);
1384 fake->SetFd(FD_MAGIC_NUMBER);
1385 this->Instance->SendMode(modelist, params.size(), fake);
1388 /* Hot potato! pass it on! */
1389 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1394 if ((command == "NICK") && (params.size() > 0))
1396 /* On nick messages, check that the nick doesnt
1397 * already exist here. If it does, kill their copy,
1400 userrec* x = this->Instance->FindNick(params[0]);
1401 if ((x) && (x != who))
1403 std::deque<std::string> p;
1404 p.push_back(params[0]);
1405 p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
1406 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
1408 p.push_back(prefix);
1409 p.push_back("Nickname collision");
1410 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
1411 userrec::QuitUser(this->Instance,x,"Nickname collision ("+prefix+" -> "+params[0]+")");
1412 userrec* y = this->Instance->FindNick(prefix);
1415 userrec::QuitUser(this->Instance,y,"Nickname collision");
1417 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1421 target = who->server;
1422 const char* strparams[127];
1423 for (unsigned int q = 0; q < params.size(); q++)
1425 strparams[q] = params[q].c_str();
1427 switch (this->Instance->CallCommandHandler(command.c_str(), strparams, params.size(), who))
1430 this->WriteLine("ERROR :Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
1437 /* CMD_SUCCESS and CMD_USER_DELETED fall through here */
1443 // its not a user. Its either a server, or somethings screwed up.
1444 if (Utils->IsServer(prefix))
1445 target = this->Instance->Config->ServerName;
1449 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1458 std::string TreeSocket::GetName()
1460 std::string sourceserv = this->myhost;
1461 if (this->InboundServerName != "")
1463 sourceserv = this->InboundServerName;
1468 void TreeSocket::OnTimeout()
1470 if (this->LinkState == CONNECTING)
1472 this->Instance->SNO->WriteToSnoMask('l',"CONNECT: Connection to \002"+myhost+"\002 timed out.");
1473 Link* MyLink = Utils->FindLink(myhost);
1475 Utils->DoFailOver(MyLink);
1479 void TreeSocket::OnClose()
1481 // Connection closed.
1482 // If the connection is fully up (state CONNECTED)
1483 // then propogate a netsplit to all peers.
1484 std::string quitserver = this->myhost;
1485 if (this->InboundServerName != "")
1487 quitserver = this->InboundServerName;
1489 TreeServer* s = Utils->FindServer(quitserver);
1492 Squit(s,"Remote host closed the connection");
1495 if (quitserver != "")
1496 this->Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' failed.",quitserver.c_str());
1499 int TreeSocket::OnIncomingConnection(int newsock, char* ip)
1501 /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
1502 * or discovering if this port is the server port, we don't allow connections from any
1503 * IPs for which we don't have a link block.
1507 found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), ip) != Utils->ValidIPs.end());
1510 for (vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
1511 if (irc::sockets::MatchCIDR(ip, (*i).c_str()))
1516 this->Instance->SNO->WriteToSnoMask('l',"Server connection from %s denied (no link blocks with that IP address)", ip);
1522 TreeSocket* s = new TreeSocket(this->Utils, this->Instance, newsock, ip, this->Hook);
1523 s = s; /* Whinge whinge whinge, thats all GCC ever does. */