1 #include "configreader.h"
5 #include "commands/cmd_whois.h"
6 #include "commands/cmd_stats.h"
11 #include "transport.h"
12 #include "socketengine.h"
14 #include "m_spanningtree/main.h"
15 #include "m_spanningtree/utils.h"
16 #include "m_spanningtree/treeserver.h"
17 #include "m_spanningtree/link.h"
18 #include "m_spanningtree/treesocket.h"
19 #include "m_spanningtree/resolvers.h"
20 #include "m_spanningtree/handshaketimer.h"
22 int TreeSocket::WriteLine(std::string line)
24 Instance->Log(DEBUG, "-> %s", line.c_str());
26 return this->Write(line);
29 /* Handle ERROR command */
30 bool TreeSocket::Error(std::deque<std::string> ¶ms)
32 if (params.size() < 1)
34 this->Instance->SNO->WriteToSnoMask('l',"ERROR from %s: %s",(InboundServerName != "" ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
35 /* we will return false to cause the socket to close. */
39 /** remote MOTD. leet, huh? */
40 bool TreeSocket::Motd(const std::string &prefix, std::deque<std::string> ¶ms)
42 if (params.size() > 0)
44 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
46 /* It's for our server */
48 userrec* source = this->Instance->FindNick(prefix);
52 std::deque<std::string> par;
53 par.push_back(prefix);
56 if (!Instance->Config->MOTD.size())
58 par[1] = std::string("::")+Instance->Config->ServerName+" 422 "+source->nick+" :Message of the day file is missing.";
59 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
63 par[1] = std::string("::")+Instance->Config->ServerName+" 375 "+source->nick+" :"+Instance->Config->ServerName+" message of the day";
64 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
66 for (unsigned int i = 0; i < Instance->Config->MOTD.size(); i++)
68 par[1] = std::string("::")+Instance->Config->ServerName+" 372 "+source->nick+" :- "+Instance->Config->MOTD[i];
69 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
72 par[1] = std::string("::")+Instance->Config->ServerName+" 376 "+source->nick+" End of message of the day.";
73 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
79 userrec* source = this->Instance->FindNick(prefix);
81 Utils->DoOneToOne(prefix, "MOTD", params, params[0]);
87 /** remote ADMIN. leet, huh? */
88 bool TreeSocket::Admin(const std::string &prefix, std::deque<std::string> ¶ms)
90 if (params.size() > 0)
92 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
94 /* It's for our server */
96 userrec* source = this->Instance->FindNick(prefix);
99 std::deque<std::string> par;
100 par.push_back(prefix);
102 par[1] = std::string("::")+Instance->Config->ServerName+" 256 "+source->nick+" :Administrative info for "+Instance->Config->ServerName;
103 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
104 par[1] = std::string("::")+Instance->Config->ServerName+" 257 "+source->nick+" :Name - "+Instance->Config->AdminName;
105 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
106 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :Nickname - "+Instance->Config->AdminNick;
107 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
108 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :E-Mail - "+Instance->Config->AdminEmail;
109 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
115 userrec* source = this->Instance->FindNick(prefix);
117 Utils->DoOneToOne(prefix, "ADMIN", params, params[0]);
123 bool TreeSocket::Stats(const std::string &prefix, std::deque<std::string> ¶ms)
125 /* Get the reply to a STATS query if it matches this servername,
126 * and send it back as a load of PUSH queries
128 if (params.size() > 1)
130 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[1]))
132 /* It's for our server */
134 userrec* source = this->Instance->FindNick(prefix);
137 std::deque<std::string> par;
138 par.push_back(prefix);
140 DoStats(this->Instance, *(params[0].c_str()), source, results);
141 for (size_t i = 0; i < results.size(); i++)
143 par[1] = "::" + results[i];
144 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
151 userrec* source = this->Instance->FindNick(prefix);
153 Utils->DoOneToOne(prefix, "STATS", params, params[1]);
160 /** Because the core won't let users or even SERVERS set +o,
161 * we use the OPERTYPE command to do this.
163 bool TreeSocket::OperType(const std::string &prefix, std::deque<std::string> ¶ms)
165 if (params.size() != 1)
167 std::string opertype = params[0];
168 userrec* u = this->Instance->FindNick(prefix);
171 u->modes[UM_OPERATOR] = 1;
172 this->Instance->all_opers.push_back(u);
173 strlcpy(u->oper,opertype.c_str(),NICKMAX-1);
174 Utils->DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
175 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()));
180 /** Because Andy insists that services-compatible servers must
181 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
183 bool TreeSocket::ForceNick(const std::string &prefix, std::deque<std::string> ¶ms)
185 if (params.size() < 3)
188 userrec* u = this->Instance->FindNick(params[0]);
192 Utils->DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
195 std::deque<std::string> par;
196 par.push_back(params[1]);
197 if (!u->ForceNickChange(params[1].c_str()))
199 userrec::QuitUser(this->Instance, u, "Nickname collision");
202 u->age = atoi(params[2].c_str());
209 * Remote SQUIT (RSQUIT). Routing works similar to SVSNICK: Route it to the server that the target is connected to locally,
210 * then let that server do the dirty work (squit it!). Example:
211 * 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
213 bool TreeSocket::RemoteSquit(const std::string &prefix, std::deque<std::string> ¶ms)
215 /* ok.. :w00t RSQUIT jupe.barafranca.com :reason here */
216 if (params.size() < 2)
219 TreeServer* s = Utils->FindServerMask(params[0]);
223 if (s == Utils->TreeRoot)
225 this->Instance->SNO->WriteToSnoMask('l',"What the fuck, I recieved a remote SQUIT for myself? :< (from %s", prefix.c_str());
229 TreeSocket* sock = s->GetSocket();
233 /* it's locally connected, KILL IT! */
234 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());
235 sock->Squit(s,"Server quit by " + prefix + ": " + params[1]);
236 Instance->SE->DelFd(sock);
242 /* route the rsquit */
243 params[1] = ":" + params[1];
244 Utils->DoOneToOne(prefix, "RSQUIT", params, params[0]);
249 /* mother fucker! it doesn't exist */
255 bool TreeSocket::ServiceJoin(const std::string &prefix, std::deque<std::string> ¶ms)
257 if (params.size() < 2)
260 userrec* u = this->Instance->FindNick(params[0]);
264 /* only join if it's local, otherwise just pass it on! */
266 chanrec::JoinUser(this->Instance, u, params[1].c_str(), false);
267 Utils->DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
272 bool TreeSocket::RemoteRehash(const std::string &prefix, std::deque<std::string> ¶ms)
274 if (params.size() < 1)
277 std::string servermask = params[0];
279 if (this->Instance->MatchText(this->Instance->Config->ServerName,servermask))
281 this->Instance->SNO->WriteToSnoMask('l',"Remote rehash initiated by \002"+prefix+"\002.");
282 this->Instance->RehashServer();
283 Utils->ReadConfiguration(false);
284 InitializeDisabledCommands(Instance->Config->DisabledCommands, Instance);
286 Utils->DoOneToAllButSender(prefix,"REHASH",params,prefix);
290 bool TreeSocket::RemoteKill(const std::string &prefix, std::deque<std::string> ¶ms)
292 if (params.size() != 2)
295 std::string nick = params[0];
296 userrec* u = this->Instance->FindNick(prefix);
297 userrec* who = this->Instance->FindNick(nick);
301 /* Prepend kill source, if we don't have one */
302 std::string sourceserv = prefix;
305 sourceserv = u->server;
307 if (*(params[1].c_str()) != '[')
309 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
311 std::string reason = params[1];
312 params[1] = ":" + params[1];
313 Utils->DoOneToAllButSender(prefix,"KILL",params,sourceserv);
314 who->Write(":%s KILL %s :%s (%s)", sourceserv.c_str(), who->nick, sourceserv.c_str(), reason.c_str());
315 userrec::QuitUser(this->Instance,who,reason);
320 bool TreeSocket::LocalPong(const std::string &prefix, std::deque<std::string> ¶ms)
322 if (params.size() < 1)
325 if (params.size() == 1)
327 TreeServer* ServerSource = Utils->FindServer(prefix);
330 ServerSource->SetPingFlag();
335 std::string forwardto = params[1];
336 if (forwardto == this->Instance->Config->ServerName)
339 * this is a PONG for us
340 * if the prefix is a user, check theyre local, and if they are,
341 * dump the PONG reply back to their fd. If its a server, do nowt.
342 * Services might want to send these s->s, but we dont need to yet.
344 userrec* u = this->Instance->FindNick(prefix);
347 u->WriteServ("PONG %s %s",params[0].c_str(),params[1].c_str());
352 // not for us, pass it on :)
353 Utils->DoOneToOne(prefix,"PONG",params,forwardto);
360 bool TreeSocket::MetaData(const std::string &prefix, std::deque<std::string> ¶ms)
362 if (params.size() < 3)
364 TreeServer* ServerSource = Utils->FindServer(prefix);
367 if (params[0] == "*")
369 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));
371 else if (*(params[0].c_str()) == '#')
373 chanrec* c = this->Instance->FindChan(params[0]);
376 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
379 else if (*(params[0].c_str()) != '#')
381 userrec* u = this->Instance->FindNick(params[0]);
384 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
389 params[2] = ":" + params[2];
390 Utils->DoOneToAllButSender(prefix,"METADATA",params,prefix);
394 bool TreeSocket::ServerVersion(const std::string &prefix, std::deque<std::string> ¶ms)
396 if (params.size() < 1)
399 TreeServer* ServerSource = Utils->FindServer(prefix);
403 ServerSource->SetVersion(params[0]);
405 params[0] = ":" + params[0];
406 Utils->DoOneToAllButSender(prefix,"VERSION",params,prefix);
410 bool TreeSocket::ChangeHost(const std::string &prefix, std::deque<std::string> ¶ms)
412 if (params.size() < 1)
414 userrec* u = this->Instance->FindNick(prefix);
418 u->ChangeDisplayedHost(params[0].c_str());
419 Utils->DoOneToAllButSender(prefix,"FHOST",params,u->server);
424 bool TreeSocket::AddLine(const std::string &prefix, std::deque<std::string> ¶ms)
426 if (params.size() < 6)
428 bool propogate = false;
430 Utils->lines_to_apply = 0;
431 switch (*(params[0].c_str()))
434 propogate = Instance->XLines->add_zline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
435 Instance->XLines->zline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
437 Utils->lines_to_apply |= APPLY_ZLINES;
440 propogate = Instance->XLines->add_qline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
441 Instance->XLines->qline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
443 Utils->lines_to_apply |= APPLY_QLINES;
446 propogate = Instance->XLines->add_eline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
447 Instance->XLines->eline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
450 propogate = Instance->XLines->add_gline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
451 Instance->XLines->gline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
453 Utils->lines_to_apply |= APPLY_GLINES;
456 propogate = Instance->XLines->add_kline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
458 Utils->lines_to_apply |= APPLY_KLINES;
461 /* Just in case... */
462 this->Instance->SNO->WriteToSnoMask('x',"\2WARNING\2: Invalid xline type '"+params[0]+"' sent by server "+prefix+", ignored!");
466 /* Send it on its way */
469 if (atoi(params[4].c_str()))
471 this->Instance->SNO->WriteToSnoMask('x',"%s Added %cLINE on %s to expire in %lu seconds (%s).",prefix.c_str(),*(params[0].c_str()),params[1].c_str(),atoi(params[4].c_str()),params[5].c_str());
475 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());
477 params[5] = ":" + params[5];
478 Utils->DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
482 Instance->XLines->apply_lines(Utils->lines_to_apply);
483 Utils->lines_to_apply = 0;
488 bool TreeSocket::ChangeName(const std::string &prefix, std::deque<std::string> ¶ms)
490 if (params.size() < 1)
492 userrec* u = this->Instance->FindNick(prefix);
495 u->ChangeName(params[0].c_str());
496 params[0] = ":" + params[0];
497 Utils->DoOneToAllButSender(prefix,"FNAME",params,u->server);
502 bool TreeSocket::Whois(const std::string &prefix, std::deque<std::string> ¶ms)
504 if (params.size() < 1)
506 userrec* u = this->Instance->FindNick(prefix);
509 // an incoming request
510 if (params.size() == 1)
512 userrec* x = this->Instance->FindNick(params[0]);
513 if ((x) && (IS_LOCAL(x)))
515 userrec* x = this->Instance->FindNick(params[0]);
518 snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
519 snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-Instance->Time(true)));
520 std::deque<std::string> par;
521 par.push_back(prefix);
522 par.push_back(signon);
524 // ours, we're done, pass it BACK
525 Utils->DoOneToOne(params[0],"IDLE",par,u->server);
529 // not ours pass it on
530 Utils->DoOneToOne(prefix,"IDLE",params,x->server);
533 else if (params.size() == 3)
535 std::string who_did_the_whois = params[0];
536 userrec* who_to_send_to = this->Instance->FindNick(who_did_the_whois);
537 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
539 // an incoming reply to a whois we sent out
540 std::string nick_whoised = prefix;
541 unsigned long signon = atoi(params[1].c_str());
542 unsigned long idle = atoi(params[2].c_str());
543 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
544 do_whois(this->Instance,who_to_send_to,u,signon,idle,nick_whoised.c_str());
548 // not ours, pass it on
549 Utils->DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
556 bool TreeSocket::Push(const std::string &prefix, std::deque<std::string> ¶ms)
558 if (params.size() < 2)
560 userrec* u = this->Instance->FindNick(params[0]);
569 // continue the raw onwards
570 params[1] = ":" + params[1];
571 Utils->DoOneToOne(prefix,"PUSH",params,u->server);
576 bool TreeSocket::HandleSetTime(const std::string &prefix, std::deque<std::string> ¶ms)
578 if (!params.size() || !Utils->EnableTimeSync)
583 if ((params.size() == 2) && (params[1] == "FORCE"))
586 time_t rts = atoi(params[0].c_str());
587 time_t us = Instance->Time(true);
591 Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
593 else if (force || (rts < us))
595 int old = Instance->SetTimeDelta(rts - us);
596 Instance->Log(DEBUG, "%s TS (diff %d) from %s applied (old delta was %d)", (force) ? "Forced" : "Lower", rts - us, prefix.c_str(), old);
598 Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
602 Instance->Log(DEBUG, "Higher TS (diff %d) from %s overridden", us - rts, prefix.c_str());
604 std::deque<std::string> oparams;
605 oparams.push_back(ConvToStr(us));
607 Utils->DoOneToMany(prefix, "TIMESET", oparams);
613 bool TreeSocket::Time(const std::string &prefix, std::deque<std::string> ¶ms)
615 // :source.server TIME remote.server sendernick
616 // :remote.server TIME source.server sendernick TS
617 if (params.size() == 2)
619 // someone querying our time?
620 if (this->Instance->Config->ServerName == params[0])
622 userrec* u = this->Instance->FindNick(params[1]);
625 params.push_back(ConvToStr(Instance->Time(false)));
627 Utils->DoOneToOne(this->Instance->Config->ServerName,"TIME",params,params[0]);
632 // not us, pass it on
633 userrec* u = this->Instance->FindNick(params[1]);
635 Utils->DoOneToOne(prefix,"TIME",params,params[0]);
638 else if (params.size() == 3)
640 // a response to a previous TIME
641 userrec* u = this->Instance->FindNick(params[1]);
642 if ((u) && (IS_LOCAL(u)))
644 time_t rawtime = atol(params[2].c_str());
645 struct tm * timeinfo;
646 timeinfo = localtime(&rawtime);
648 snprintf(tms,26,"%s",asctime(timeinfo));
650 u->WriteServ("391 %s %s :%s",u->nick,prefix.c_str(),tms);
655 Utils->DoOneToOne(prefix,"TIME",params,u->server);
661 bool TreeSocket::LocalPing(const std::string &prefix, std::deque<std::string> ¶ms)
663 if (params.size() < 1)
665 if (params.size() == 1)
667 std::string stufftobounce = params[0];
668 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" PONG "+stufftobounce);
673 std::string forwardto = params[1];
674 if (forwardto == this->Instance->Config->ServerName)
676 // this is a ping for us, send back PONG to the requesting server
677 params[1] = params[0];
678 params[0] = forwardto;
679 Utils->DoOneToOne(forwardto,"PONG",params,params[1]);
683 // not for us, pass it on :)
684 Utils->DoOneToOne(prefix,"PING",params,forwardto);
690 bool TreeSocket::RemoveStatus(const std::string &prefix, std::deque<std::string> ¶ms)
692 if (params.size() < 1)
694 chanrec* c = Instance->FindChan(params[0]);
697 irc::modestacker modestack(false);
698 CUList *ulist = c->GetUsers();
700 std::deque<std::string> stackresult;
702 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
704 std::string modesequence = Instance->Modes->ModeString(i->second, c);
705 if (modesequence.length())
707 irc::spacesepstream sep(modesequence);
708 std::string modeletters = sep.GetToken();
709 while (!modeletters.empty())
711 char mletter = *(modeletters.begin());
712 modestack.Push(mletter,sep.GetToken());
713 modeletters.erase(modeletters.begin());
718 while (modestack.GetStackedLine(stackresult))
720 stackresult.push_front(ConvToStr(c->age));
721 stackresult.push_front(c->name);
722 Utils->DoOneToMany(Instance->Config->ServerName, "FMODE", stackresult);
723 stackresult.erase(stackresult.begin() + 1);
724 for (size_t z = 0; z < stackresult.size(); z++)
726 y[z] = stackresult[z].c_str();
728 userrec* n = new userrec(Instance);
729 n->SetFd(FD_MAGIC_NUMBER);
730 Instance->SendMode(y, stackresult.size(), n);
737 bool TreeSocket::RemoteServer(const std::string &prefix, std::deque<std::string> ¶ms)
739 if (params.size() < 4)
741 std::string servername = params[0];
742 std::string password = params[1];
743 // hopcount is not used for a remote server, we calculate this ourselves
744 std::string description = params[3];
745 TreeServer* ParentOfThis = Utils->FindServer(prefix);
748 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
751 TreeServer* CheckDupe = Utils->FindServer(servername);
754 this->WriteLine("ERROR :Server "+servername+" already exists!");
755 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+servername+"\2 denied, already exists");
758 TreeServer* Node = new TreeServer(this->Utils,this->Instance,servername,description,ParentOfThis,NULL);
759 ParentOfThis->AddChild(Node);
760 params[3] = ":" + params[3];
761 Utils->DoOneToAllButSender(prefix,"SERVER",params,prefix);
762 this->Instance->SNO->WriteToSnoMask('l',"Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
766 bool TreeSocket::Outbound_Reply_Server(std::deque<std::string> ¶ms)
768 if (params.size() < 4)
771 irc::string servername = params[0].c_str();
772 std::string sname = params[0];
773 std::string password = params[1];
774 int hops = atoi(params[2].c_str());
778 this->WriteLine("ERROR :Server too far away for authentication");
779 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
782 std::string description = params[3];
783 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
785 if ((x->Name == servername) && (x->RecvPass == password))
787 TreeServer* CheckDupe = Utils->FindServer(sname);
790 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
791 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
794 // Begin the sync here. this kickstarts the
795 // other side, waiting in WAIT_AUTH_2 state,
796 // into starting their burst, as it shows
798 this->LinkState = CONNECTED;
799 // we should add the details of this server now
800 // to the servers tree, as a child of the root
802 TreeServer* Node = new TreeServer(this->Utils,this->Instance,sname,description,Utils->TreeRoot,this);
803 Utils->TreeRoot->AddChild(Node);
804 params[3] = ":" + params[3];
805 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,sname);
806 this->bursting = true;
811 this->WriteLine("ERROR :Invalid credentials");
812 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
816 bool TreeSocket::Inbound_Server(std::deque<std::string> ¶ms)
818 if (params.size() < 4)
820 irc::string servername = params[0].c_str();
821 std::string sname = params[0];
822 std::string password = params[1];
823 int hops = atoi(params[2].c_str());
827 this->WriteLine("ERROR :Server too far away for authentication");
828 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
831 std::string description = params[3];
832 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
834 if ((x->Name == servername) && (x->RecvPass == password))
836 TreeServer* CheckDupe = Utils->FindServer(sname);
839 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
840 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
843 this->Instance->SNO->WriteToSnoMask('l',"Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
846 std::string name = InspSocketNameRequest((Module*)Utils->Creator, this->Hook).Send();
847 this->Instance->SNO->WriteToSnoMask('l',"Connection from \2"+sname+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] using transport \2"+name+"\2");
850 this->InboundServerName = sname;
851 this->InboundDescription = description;
852 // this is good. Send our details: Our server name and description and hopcount of 0,
853 // along with the sendpass from this block.
854 this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+x->SendPass+" 0 :"+this->Instance->Config->ServerDesc);
855 // move to the next state, we are now waiting for THEM.
856 this->LinkState = WAIT_AUTH_2;
860 this->WriteLine("ERROR :Invalid credentials");
861 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
865 void TreeSocket::Split(const std::string &line, std::deque<std::string> &n)
868 irc::tokenstream tokens(line);
870 while ((param = tokens.GetToken()) != "")
875 bool TreeSocket::ProcessLine(std::string &line)
877 std::deque<std::string> params;
881 line = line.substr(0, line.find_first_of("\r\n"));
886 Instance->Log(DEBUG, "<- %s", line.c_str());
888 this->Split(line.c_str(),params);
890 if ((params[0][0] == ':') && (params.size() > 1))
892 prefix = params[0].substr(1);
895 command = params[0].c_str();
897 switch (this->LinkState)
902 // Waiting for SERVER command from remote server. Server initiating
903 // the connection sends the first SERVER command, listening server
904 // replies with theirs if its happy, then if the initiator is happy,
905 // it starts to send its net sync, which starts the merge, otherwise
906 // it sends an ERROR.
907 if (command == "PASS")
909 /* Silently ignored */
911 else if (command == "SERVER")
913 return this->Inbound_Server(params);
915 else if (command == "ERROR")
917 return this->Error(params);
919 else if (command == "USER")
921 this->WriteLine("ERROR :Client connections to this port are prohibited.");
924 else if (command == "CAPAB")
926 return this->Capab(params);
928 else if ((command == "U") || (command == "S"))
930 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
935 std::string error("ERROR :Invalid command in negotiation phase: ");
936 error.append(command.c_str());
937 this->WriteLine(error);
942 // Waiting for start of other side's netmerge to say they liked our
944 if (command == "SERVER")
946 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
950 else if ((command == "U") || (command == "S"))
952 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
955 else if (command == "BURST")
957 if (params.size() && Utils->EnableTimeSync)
959 /* If a time stamp is provided, apply synchronization */
961 time_t them = atoi(params[0].c_str());
962 time_t us = Instance->Time(true);
963 int delta = them - us;
964 if ((params.size() == 2) && (params[1] == "FORCE"))
966 if ((delta < -600) || (delta > 600))
968 this->Instance->SNO->WriteToSnoMask('l',"\2ERROR\2: Your clocks are out by %d seconds (this is more than ten minutes). Link aborted, \2PLEASE SYNC YOUR CLOCKS!\2",abs(delta));
969 this->WriteLine("ERROR :Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than ten minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
973 if (force || (us > them))
975 this->Instance->SetTimeDelta(them - us);
976 // Send this new timestamp to any other servers
977 Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
981 // Override the timestamp
982 this->WriteLine(":" + Utils->TreeRoot->GetName() + " TIMESET " + ConvToStr(us));
985 this->LinkState = CONNECTED;
986 Node = new TreeServer(this->Utils,this->Instance,InboundServerName,InboundDescription,Utils->TreeRoot,this);
987 Utils->TreeRoot->AddChild(Node);
989 params.push_back(InboundServerName);
990 params.push_back("*");
991 params.push_back("1");
992 params.push_back(":"+InboundDescription);
993 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,InboundServerName);
994 this->bursting = true;
997 else if (command == "ERROR")
999 return this->Error(params);
1001 else if (command == "CAPAB")
1003 return this->Capab(params);
1008 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
1012 if (command == "SERVER")
1014 // another server we connected to, which was in WAIT_AUTH_1 state,
1015 // has just sent us their credentials. If we get this far, theyre
1016 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1017 // if we're happy with this, we should send our netburst which
1018 // kickstarts the merge.
1019 return this->Outbound_Reply_Server(params);
1021 else if (command == "ERROR")
1023 return this->Error(params);
1027 // This is the 'authenticated' state, when all passwords
1028 // have been exchanged and anything past this point is taken
1033 std::string direction = prefix;
1034 userrec* t = this->Instance->FindNick(prefix);
1037 direction = t->server;
1039 TreeServer* route_back_again = Utils->BestRouteTo(direction);
1040 if ((!route_back_again) || (route_back_again->GetSocket() != this))
1042 if (route_back_again)
1043 Instance->Log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
1047 * When there is activity on the socket, reset the ping counter so
1048 * that we're not wasting bandwidth pinging an active server.
1050 route_back_again->SetNextPingTime(time(NULL) + 60);
1051 route_back_again->SetPingFlag();
1054 if (command == "SVSMODE")
1056 /* Services expects us to implement
1057 * SVSMODE. In inspircd its the same as
1062 std::string target = "";
1063 /* Yes, know, this is a mess. Its reasonably fast though as we're
1064 * working with std::string here.
1066 if ((command == "NICK") && (params.size() > 1))
1068 return this->IntroduceClient(prefix,params);
1070 else if (command == "FJOIN")
1072 return this->ForceJoin(prefix,params);
1074 else if (command == "STATS")
1076 return this->Stats(prefix, params);
1078 else if (command == "MOTD")
1080 return this->Motd(prefix, params);
1082 else if (command == "ADMIN")
1084 return this->Admin(prefix, params);
1086 else if (command == "SERVER")
1088 return this->RemoteServer(prefix,params);
1090 else if (command == "ERROR")
1092 return this->Error(params);
1094 else if (command == "OPERTYPE")
1096 return this->OperType(prefix,params);
1098 else if (command == "FMODE")
1100 return this->ForceMode(prefix,params);
1102 else if (command == "KILL")
1104 return this->RemoteKill(prefix,params);
1106 else if (command == "FTOPIC")
1108 return this->ForceTopic(prefix,params);
1110 else if (command == "REHASH")
1112 return this->RemoteRehash(prefix,params);
1114 else if (command == "METADATA")
1116 return this->MetaData(prefix,params);
1118 else if (command == "REMSTATUS")
1120 return this->RemoveStatus(prefix,params);
1122 else if (command == "PING")
1125 * We just got a ping from a server that's bursting.
1126 * This can't be right, so set them to not bursting, and
1127 * apply their lines.
1131 this->bursting = false;
1132 Instance->XLines->apply_lines(Utils->lines_to_apply);
1133 Utils->lines_to_apply = 0;
1137 prefix = this->GetName();
1139 return this->LocalPing(prefix,params);
1141 else if (command == "PONG")
1144 * We just got a pong from a server that's bursting.
1145 * This can't be right, so set them to not bursting, and
1146 * apply their lines.
1150 this->bursting = false;
1151 Instance->XLines->apply_lines(Utils->lines_to_apply);
1152 Utils->lines_to_apply = 0;
1156 prefix = this->GetName();
1158 return this->LocalPong(prefix,params);
1160 else if (command == "VERSION")
1162 return this->ServerVersion(prefix,params);
1164 else if (command == "FHOST")
1166 return this->ChangeHost(prefix,params);
1168 else if (command == "FNAME")
1170 return this->ChangeName(prefix,params);
1172 else if (command == "ADDLINE")
1174 return this->AddLine(prefix,params);
1176 else if (command == "SVSNICK")
1180 prefix = this->GetName();
1182 return this->ForceNick(prefix,params);
1184 else if (command == "RSQUIT")
1186 return this->RemoteSquit(prefix, params);
1188 else if (command == "IDLE")
1190 return this->Whois(prefix,params);
1192 else if (command == "PUSH")
1194 return this->Push(prefix,params);
1196 else if (command == "TIMESET")
1198 return this->HandleSetTime(prefix, params);
1200 else if (command == "TIME")
1202 return this->Time(prefix,params);
1204 else if ((command == "KICK") && (Utils->IsServer(prefix)))
1206 std::string sourceserv = this->myhost;
1207 if (params.size() == 3)
1209 userrec* user = this->Instance->FindNick(params[1]);
1210 chanrec* chan = this->Instance->FindChan(params[0]);
1213 if (!chan->ServerKickUser(user, params[2].c_str(), false))
1214 /* Yikes, the channels gone! */
1218 if (this->InboundServerName != "")
1220 sourceserv = this->InboundServerName;
1222 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1224 else if (command == "SVSJOIN")
1228 prefix = this->GetName();
1230 return this->ServiceJoin(prefix,params);
1232 else if (command == "SQUIT")
1234 if (params.size() == 2)
1236 this->Squit(Utils->FindServer(params[0]),params[1]);
1240 else if (command == "OPERNOTICE")
1242 std::string sourceserv = this->myhost;
1243 if (this->InboundServerName != "")
1244 sourceserv = this->InboundServerName;
1245 if (params.size() >= 1)
1246 Instance->WriteOpers("*** From " + sourceserv + ": " + params[0]);
1247 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1249 else if (command == "MODENOTICE")
1251 std::string sourceserv = this->myhost;
1252 if (this->InboundServerName != "")
1253 sourceserv = this->InboundServerName;
1254 if (params.size() >= 2)
1256 Instance->WriteMode(params[0].c_str(), WM_AND, "*** From %s: %s", sourceserv.c_str(), params[1].c_str());
1258 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1260 else if (command == "SNONOTICE")
1262 std::string sourceserv = this->myhost;
1263 if (this->InboundServerName != "")
1264 sourceserv = this->InboundServerName;
1265 if (params.size() >= 2)
1267 Instance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + sourceserv + ": "+ params[1]);
1269 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1271 else if (command == "ENDBURST")
1273 this->bursting = false;
1274 Instance->XLines->apply_lines(Utils->lines_to_apply);
1275 Utils->lines_to_apply = 0;
1276 std::string sourceserv = this->myhost;
1277 if (this->InboundServerName != "")
1279 sourceserv = this->InboundServerName;
1281 this->Instance->SNO->WriteToSnoMask('l',"Received end of netburst from \2%s\2",sourceserv.c_str());
1283 Event rmode((char*)sourceserv.c_str(), (Module*)Utils->Creator, "new_server");
1284 rmode.Send(Instance);
1290 // not a special inter-server command.
1291 // Emulate the actual user doing the command,
1292 // this saves us having a huge ugly parser.
1293 userrec* who = this->Instance->FindNick(prefix);
1294 std::string sourceserv = this->myhost;
1295 if (this->InboundServerName != "")
1297 sourceserv = this->InboundServerName;
1299 if ((!who) && (command == "MODE"))
1301 if (Utils->IsServer(prefix))
1303 const char* modelist[127];
1304 for (size_t i = 0; i < params.size(); i++)
1305 modelist[i] = params[i].c_str();
1306 userrec* fake = new userrec(Instance);
1307 fake->SetFd(FD_MAGIC_NUMBER);
1308 this->Instance->SendMode(modelist, params.size(), fake);
1311 /* Hot potato! pass it on! */
1312 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1317 if ((command == "NICK") && (params.size() > 0))
1319 /* On nick messages, check that the nick doesnt
1320 * already exist here. If it does, kill their copy,
1323 userrec* x = this->Instance->FindNick(params[0]);
1324 if ((x) && (x != who))
1326 std::deque<std::string> p;
1327 p.push_back(params[0]);
1328 p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
1329 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
1331 p.push_back(prefix);
1332 p.push_back("Nickname collision");
1333 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
1334 userrec::QuitUser(this->Instance,x,"Nickname collision ("+prefix+" -> "+params[0]+")");
1335 userrec* y = this->Instance->FindNick(prefix);
1338 userrec::QuitUser(this->Instance,y,"Nickname collision");
1340 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1344 target = who->server;
1345 const char* strparams[127];
1346 for (unsigned int q = 0; q < params.size(); q++)
1348 strparams[q] = params[q].c_str();
1350 switch (this->Instance->CallCommandHandler(command.c_str(), strparams, params.size(), who))
1353 this->WriteLine("ERROR :Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
1360 /* CMD_SUCCESS and CMD_USER_DELETED fall through here */
1366 // its not a user. Its either a server, or somethings screwed up.
1367 if (Utils->IsServer(prefix))
1368 target = this->Instance->Config->ServerName;
1372 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1381 std::string TreeSocket::GetName()
1383 std::string sourceserv = this->myhost;
1384 if (this->InboundServerName != "")
1386 sourceserv = this->InboundServerName;
1391 void TreeSocket::OnTimeout()
1393 if (this->LinkState == CONNECTING)
1395 this->Instance->SNO->WriteToSnoMask('l',"CONNECT: Connection to \002"+myhost+"\002 timed out.");
1396 Link* MyLink = Utils->FindLink(myhost);
1398 Utils->DoFailOver(MyLink);
1402 void TreeSocket::OnClose()
1404 // Connection closed.
1405 // If the connection is fully up (state CONNECTED)
1406 // then propogate a netsplit to all peers.
1407 std::string quitserver = this->myhost;
1408 if (this->InboundServerName != "")
1410 quitserver = this->InboundServerName;
1412 TreeServer* s = Utils->FindServer(quitserver);
1415 Squit(s,"Remote host closed the connection");
1418 if (quitserver != "")
1419 this->Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' failed.",quitserver.c_str());
1422 int TreeSocket::OnIncomingConnection(int newsock, char* ip)
1424 /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
1425 * or discovering if this port is the server port, we don't allow connections from any
1426 * IPs for which we don't have a link block.
1430 found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), ip) != Utils->ValidIPs.end());
1433 for (vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
1434 if (irc::sockets::MatchCIDR(ip, (*i).c_str()))
1439 this->Instance->SNO->WriteToSnoMask('l',"Server connection from %s denied (no link blocks with that IP address)", ip);
1445 TreeSocket* s = new TreeSocket(this->Utils, this->Instance, newsock, ip, this->Hook);
1446 s = s; /* Whinge whinge whinge, thats all GCC ever does. */