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 /* $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 */
24 int TreeSocket::WriteLine(std::string line)
26 Instance->Log(DEBUG, "-> %s", line.c_str());
28 return this->Write(line);
31 /* Handle ERROR command */
32 bool TreeSocket::Error(std::deque<std::string> ¶ms)
34 if (params.size() < 1)
36 this->Instance->SNO->WriteToSnoMask('l',"ERROR from %s: %s",(InboundServerName != "" ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
37 /* we will return false to cause the socket to close. */
41 /** remote MOTD. leet, huh? */
42 bool TreeSocket::Motd(const std::string &prefix, std::deque<std::string> ¶ms)
44 if (params.size() > 0)
46 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
48 /* It's for our server */
50 userrec* source = this->Instance->FindNick(prefix);
54 std::deque<std::string> par;
55 par.push_back(prefix);
58 if (!Instance->Config->MOTD.size())
60 par[1] = std::string("::")+Instance->Config->ServerName+" 422 "+source->nick+" :Message of the day file is missing.";
61 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
65 par[1] = std::string("::")+Instance->Config->ServerName+" 375 "+source->nick+" :"+Instance->Config->ServerName+" message of the day";
66 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
68 for (unsigned int i = 0; i < Instance->Config->MOTD.size(); i++)
70 par[1] = std::string("::")+Instance->Config->ServerName+" 372 "+source->nick+" :- "+Instance->Config->MOTD[i];
71 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
74 par[1] = std::string("::")+Instance->Config->ServerName+" 376 "+source->nick+" End of message of the day.";
75 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
81 userrec* source = this->Instance->FindNick(prefix);
83 Utils->DoOneToOne(prefix, "MOTD", params, params[0]);
89 /** remote ADMIN. leet, huh? */
90 bool TreeSocket::Admin(const std::string &prefix, std::deque<std::string> ¶ms)
92 if (params.size() > 0)
94 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
96 /* It's for our server */
98 userrec* source = this->Instance->FindNick(prefix);
101 std::deque<std::string> par;
102 par.push_back(prefix);
104 par[1] = std::string("::")+Instance->Config->ServerName+" 256 "+source->nick+" :Administrative info for "+Instance->Config->ServerName;
105 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
106 par[1] = std::string("::")+Instance->Config->ServerName+" 257 "+source->nick+" :Name - "+Instance->Config->AdminName;
107 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
108 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :Nickname - "+Instance->Config->AdminNick;
109 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
110 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :E-Mail - "+Instance->Config->AdminEmail;
111 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
117 userrec* source = this->Instance->FindNick(prefix);
119 Utils->DoOneToOne(prefix, "ADMIN", params, params[0]);
125 bool TreeSocket::Stats(const std::string &prefix, std::deque<std::string> ¶ms)
127 /* Get the reply to a STATS query if it matches this servername,
128 * and send it back as a load of PUSH queries
130 if (params.size() > 1)
132 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[1]))
134 /* It's for our server */
136 userrec* source = this->Instance->FindNick(prefix);
139 std::deque<std::string> par;
140 par.push_back(prefix);
142 DoStats(this->Instance, *(params[0].c_str()), source, results);
143 for (size_t i = 0; i < results.size(); i++)
145 par[1] = "::" + results[i];
146 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
153 userrec* source = this->Instance->FindNick(prefix);
155 Utils->DoOneToOne(prefix, "STATS", params, params[1]);
162 /** Because the core won't let users or even SERVERS set +o,
163 * we use the OPERTYPE command to do this.
165 bool TreeSocket::OperType(const std::string &prefix, std::deque<std::string> ¶ms)
167 if (params.size() != 1)
169 std::string opertype = params[0];
170 userrec* u = this->Instance->FindNick(prefix);
173 u->modes[UM_OPERATOR] = 1;
174 this->Instance->all_opers.push_back(u);
175 strlcpy(u->oper,opertype.c_str(),NICKMAX-1);
176 Utils->DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
177 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()));
182 /** Because Andy insists that services-compatible servers must
183 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
185 bool TreeSocket::ForceNick(const std::string &prefix, std::deque<std::string> ¶ms)
187 if (params.size() < 3)
190 userrec* u = this->Instance->FindNick(params[0]);
194 Utils->DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
197 std::deque<std::string> par;
198 par.push_back(params[1]);
199 if (!u->ForceNickChange(params[1].c_str()))
201 userrec::QuitUser(this->Instance, u, "Nickname collision");
204 u->age = atoi(params[2].c_str());
210 bool TreeSocket::OperQuit(const std::string &prefix, std::deque<std::string> ¶ms)
212 if (params.size() < 1)
215 userrec* u = this->Instance->FindNick(prefix);
219 Utils->DoOneToAllButSender(prefix,"OPERQUIT",params,prefix);
220 u->SetOperQuit(params[0]);
226 * Remote SQUIT (RSQUIT). Routing works similar to SVSNICK: Route it to the server that the target is connected to locally,
227 * then let that server do the dirty work (squit it!). Example:
228 * 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
230 bool TreeSocket::RemoteSquit(const std::string &prefix, std::deque<std::string> ¶ms)
232 /* ok.. :w00t RSQUIT jupe.barafranca.com :reason here */
233 if (params.size() < 2)
236 TreeServer* s = Utils->FindServerMask(params[0]);
240 if (s == Utils->TreeRoot)
242 this->Instance->SNO->WriteToSnoMask('l',"What the fuck, I recieved a remote SQUIT for myself? :< (from %s", prefix.c_str());
246 TreeSocket* sock = s->GetSocket();
250 /* it's locally connected, KILL IT! */
251 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());
252 sock->Squit(s,"Server quit by " + prefix + ": " + params[1]);
253 Instance->SE->DelFd(sock);
259 /* route the rsquit */
260 params[1] = ":" + params[1];
261 Utils->DoOneToOne(prefix, "RSQUIT", params, params[0]);
266 /* mother fucker! it doesn't exist */
272 bool TreeSocket::ServiceJoin(const std::string &prefix, std::deque<std::string> ¶ms)
274 if (params.size() < 2)
277 userrec* u = this->Instance->FindNick(params[0]);
281 /* only join if it's local, otherwise just pass it on! */
283 chanrec::JoinUser(this->Instance, u, params[1].c_str(), false);
284 Utils->DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
289 bool TreeSocket::RemoteRehash(const std::string &prefix, std::deque<std::string> ¶ms)
291 if (params.size() < 1)
294 std::string servermask = params[0];
296 if (this->Instance->MatchText(this->Instance->Config->ServerName,servermask))
298 this->Instance->SNO->WriteToSnoMask('l',"Remote rehash initiated by \002"+prefix+"\002.");
299 this->Instance->RehashServer();
300 Utils->ReadConfiguration(false);
301 InitializeDisabledCommands(Instance->Config->DisabledCommands, Instance);
303 Utils->DoOneToAllButSender(prefix,"REHASH",params,prefix);
307 bool TreeSocket::RemoteKill(const std::string &prefix, std::deque<std::string> ¶ms)
309 if (params.size() != 2)
312 std::string nick = params[0];
313 userrec* u = this->Instance->FindNick(prefix);
314 userrec* who = this->Instance->FindNick(nick);
318 /* Prepend kill source, if we don't have one */
319 std::string sourceserv = prefix;
322 sourceserv = u->server;
324 if (*(params[1].c_str()) != '[')
326 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
328 std::string reason = params[1];
329 params[1] = ":" + params[1];
330 Utils->DoOneToAllButSender(prefix,"KILL",params,sourceserv);
331 who->Write(":%s KILL %s :%s (%s)", sourceserv.c_str(), who->nick, sourceserv.c_str(), reason.c_str());
332 userrec::QuitUser(this->Instance,who,reason);
337 bool TreeSocket::LocalPong(const std::string &prefix, std::deque<std::string> ¶ms)
339 if (params.size() < 1)
342 if (params.size() == 1)
344 TreeServer* ServerSource = Utils->FindServer(prefix);
347 ServerSource->SetPingFlag();
352 std::string forwardto = params[1];
353 if (forwardto == this->Instance->Config->ServerName)
356 * this is a PONG for us
357 * if the prefix is a user, check theyre local, and if they are,
358 * dump the PONG reply back to their fd. If its a server, do nowt.
359 * Services might want to send these s->s, but we dont need to yet.
361 userrec* u = this->Instance->FindNick(prefix);
364 u->WriteServ("PONG %s %s",params[0].c_str(),params[1].c_str());
369 // not for us, pass it on :)
370 Utils->DoOneToOne(prefix,"PONG",params,forwardto);
377 bool TreeSocket::MetaData(const std::string &prefix, std::deque<std::string> ¶ms)
379 if (params.size() < 2)
382 params.push_back("");
383 TreeServer* ServerSource = Utils->FindServer(prefix);
386 if (params[0] == "*")
388 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));
390 else if (*(params[0].c_str()) == '#')
392 chanrec* c = this->Instance->FindChan(params[0]);
395 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
398 else if (*(params[0].c_str()) != '#')
400 userrec* u = this->Instance->FindNick(params[0]);
403 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
408 params[2] = ":" + params[2];
409 Utils->DoOneToAllButSender(prefix,"METADATA",params,prefix);
413 bool TreeSocket::ServerVersion(const std::string &prefix, std::deque<std::string> ¶ms)
415 if (params.size() < 1)
418 TreeServer* ServerSource = Utils->FindServer(prefix);
422 ServerSource->SetVersion(params[0]);
424 params[0] = ":" + params[0];
425 Utils->DoOneToAllButSender(prefix,"VERSION",params,prefix);
429 bool TreeSocket::ChangeHost(const std::string &prefix, std::deque<std::string> ¶ms)
431 if (params.size() < 1)
433 userrec* u = this->Instance->FindNick(prefix);
437 u->ChangeDisplayedHost(params[0].c_str());
438 Utils->DoOneToAllButSender(prefix,"FHOST",params,u->server);
443 bool TreeSocket::AddLine(const std::string &prefix, std::deque<std::string> ¶ms)
445 if (params.size() < 6)
447 bool propogate = false;
449 Utils->lines_to_apply = 0;
450 switch (*(params[0].c_str()))
453 propogate = Instance->XLines->add_zline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
454 Instance->XLines->zline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
456 Utils->lines_to_apply |= APPLY_ZLINES;
459 propogate = Instance->XLines->add_qline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
460 Instance->XLines->qline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
462 Utils->lines_to_apply |= APPLY_QLINES;
465 propogate = Instance->XLines->add_eline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
466 Instance->XLines->eline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
469 propogate = Instance->XLines->add_gline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
470 Instance->XLines->gline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
472 Utils->lines_to_apply |= APPLY_GLINES;
475 propogate = Instance->XLines->add_kline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
477 Utils->lines_to_apply |= APPLY_KLINES;
480 /* Just in case... */
481 this->Instance->SNO->WriteToSnoMask('x',"\2WARNING\2: Invalid xline type '"+params[0]+"' sent by server "+prefix+", ignored!");
485 /* Send it on its way */
488 if (atoi(params[4].c_str()))
490 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());
494 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());
496 params[5] = ":" + params[5];
497 Utils->DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
501 Instance->XLines->apply_lines(Utils->lines_to_apply);
502 Utils->lines_to_apply = 0;
507 bool TreeSocket::ChangeName(const std::string &prefix, std::deque<std::string> ¶ms)
509 if (params.size() < 1)
511 userrec* u = this->Instance->FindNick(prefix);
514 u->ChangeName(params[0].c_str());
515 params[0] = ":" + params[0];
516 Utils->DoOneToAllButSender(prefix,"FNAME",params,u->server);
521 bool TreeSocket::Whois(const std::string &prefix, std::deque<std::string> ¶ms)
523 if (params.size() < 1)
525 userrec* u = this->Instance->FindNick(prefix);
528 // an incoming request
529 if (params.size() == 1)
531 userrec* x = this->Instance->FindNick(params[0]);
532 if ((x) && (IS_LOCAL(x)))
534 userrec* x = this->Instance->FindNick(params[0]);
537 snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
538 snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-Instance->Time(true)));
539 std::deque<std::string> par;
540 par.push_back(prefix);
541 par.push_back(signon);
543 // ours, we're done, pass it BACK
544 Utils->DoOneToOne(params[0],"IDLE",par,u->server);
548 // not ours pass it on
549 Utils->DoOneToOne(prefix,"IDLE",params,x->server);
552 else if (params.size() == 3)
554 std::string who_did_the_whois = params[0];
555 userrec* who_to_send_to = this->Instance->FindNick(who_did_the_whois);
556 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
558 // an incoming reply to a whois we sent out
559 std::string nick_whoised = prefix;
560 unsigned long signon = atoi(params[1].c_str());
561 unsigned long idle = atoi(params[2].c_str());
562 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
563 do_whois(this->Instance,who_to_send_to,u,signon,idle,nick_whoised.c_str());
567 // not ours, pass it on
568 Utils->DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
575 bool TreeSocket::Push(const std::string &prefix, std::deque<std::string> ¶ms)
577 if (params.size() < 2)
579 userrec* u = this->Instance->FindNick(params[0]);
588 // continue the raw onwards
589 params[1] = ":" + params[1];
590 Utils->DoOneToOne(prefix,"PUSH",params,u->server);
595 bool TreeSocket::HandleSetTime(const std::string &prefix, std::deque<std::string> ¶ms)
597 if (!params.size() || !Utils->EnableTimeSync)
602 if ((params.size() == 2) && (params[1] == "FORCE"))
605 time_t rts = atoi(params[0].c_str());
606 time_t us = Instance->Time(true);
610 Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
612 else if (force || (rts < us))
614 int old = Instance->SetTimeDelta(rts - us);
615 Instance->Log(DEBUG, "%s TS (diff %d) from %s applied (old delta was %d)", (force) ? "Forced" : "Lower", rts - us, prefix.c_str(), old);
617 Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
621 Instance->Log(DEBUG, "Higher TS (diff %d) from %s overridden", us - rts, prefix.c_str());
623 std::deque<std::string> oparams;
624 oparams.push_back(ConvToStr(us));
626 Utils->DoOneToMany(prefix, "TIMESET", oparams);
632 bool TreeSocket::Time(const std::string &prefix, std::deque<std::string> ¶ms)
634 // :source.server TIME remote.server sendernick
635 // :remote.server TIME source.server sendernick TS
636 if (params.size() == 2)
638 // someone querying our time?
639 if (this->Instance->Config->ServerName == params[0])
641 userrec* u = this->Instance->FindNick(params[1]);
644 params.push_back(ConvToStr(Instance->Time(false)));
646 Utils->DoOneToOne(this->Instance->Config->ServerName,"TIME",params,params[0]);
651 // not us, pass it on
652 userrec* u = this->Instance->FindNick(params[1]);
654 Utils->DoOneToOne(prefix,"TIME",params,params[0]);
657 else if (params.size() == 3)
659 // a response to a previous TIME
660 userrec* u = this->Instance->FindNick(params[1]);
661 if ((u) && (IS_LOCAL(u)))
663 time_t rawtime = atol(params[2].c_str());
664 struct tm * timeinfo;
665 timeinfo = localtime(&rawtime);
667 snprintf(tms,26,"%s",asctime(timeinfo));
669 u->WriteServ("391 %s %s :%s",u->nick,prefix.c_str(),tms);
674 Utils->DoOneToOne(prefix,"TIME",params,u->server);
680 bool TreeSocket::LocalPing(const std::string &prefix, std::deque<std::string> ¶ms)
682 if (params.size() < 1)
684 if (params.size() == 1)
686 std::string stufftobounce = params[0];
687 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" PONG "+stufftobounce);
692 std::string forwardto = params[1];
693 if (forwardto == this->Instance->Config->ServerName)
695 // this is a ping for us, send back PONG to the requesting server
696 params[1] = params[0];
697 params[0] = forwardto;
698 Utils->DoOneToOne(forwardto,"PONG",params,params[1]);
702 // not for us, pass it on :)
703 Utils->DoOneToOne(prefix,"PING",params,forwardto);
709 /** TODO: This creates a total mess of output and needs to really use irc::modestacker.
711 bool TreeSocket::RemoveStatus(const std::string &prefix, std::deque<std::string> ¶ms)
713 if (params.size() < 1)
715 chanrec* c = Instance->FindChan(params[0]);
718 for (char modeletter = 'A'; modeletter <= 'z'; modeletter++)
720 ModeHandler* mh = Instance->Modes->FindMode(modeletter, MODETYPE_CHANNEL);
728 bool TreeSocket::RemoteServer(const std::string &prefix, std::deque<std::string> ¶ms)
730 if (params.size() < 4)
732 std::string servername = params[0];
733 std::string password = params[1];
734 // hopcount is not used for a remote server, we calculate this ourselves
735 std::string description = params[3];
736 TreeServer* ParentOfThis = Utils->FindServer(prefix);
739 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
742 TreeServer* CheckDupe = Utils->FindServer(servername);
745 this->WriteLine("ERROR :Server "+servername+" already exists!");
746 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+servername+"\2 denied, already exists");
749 TreeServer* Node = new TreeServer(this->Utils,this->Instance,servername,description,ParentOfThis,NULL);
750 ParentOfThis->AddChild(Node);
751 params[3] = ":" + params[3];
752 Utils->DoOneToAllButSender(prefix,"SERVER",params,prefix);
753 this->Instance->SNO->WriteToSnoMask('l',"Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
757 bool TreeSocket::Outbound_Reply_Server(std::deque<std::string> ¶ms)
759 if (params.size() < 4)
762 irc::string servername = params[0].c_str();
763 std::string sname = params[0];
764 std::string password = params[1];
765 int hops = atoi(params[2].c_str());
769 this->WriteLine("ERROR :Server too far away for authentication");
770 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
773 std::string description = params[3];
774 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
776 if ((x->Name == servername) && (x->RecvPass == password))
778 TreeServer* CheckDupe = Utils->FindServer(sname);
781 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
782 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
785 // Begin the sync here. this kickstarts the
786 // other side, waiting in WAIT_AUTH_2 state,
787 // into starting their burst, as it shows
789 this->LinkState = CONNECTED;
790 // we should add the details of this server now
791 // to the servers tree, as a child of the root
793 TreeServer* Node = new TreeServer(this->Utils,this->Instance,sname,description,Utils->TreeRoot,this);
794 Utils->TreeRoot->AddChild(Node);
795 params[3] = ":" + params[3];
796 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,sname);
797 this->bursting = true;
802 this->WriteLine("ERROR :Invalid credentials");
803 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
807 bool TreeSocket::Inbound_Server(std::deque<std::string> ¶ms)
809 if (params.size() < 4)
811 irc::string servername = params[0].c_str();
812 std::string sname = params[0];
813 std::string password = params[1];
814 int hops = atoi(params[2].c_str());
818 this->WriteLine("ERROR :Server too far away for authentication");
819 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
822 std::string description = params[3];
823 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
825 if ((x->Name == servername) && (x->RecvPass == password))
827 TreeServer* CheckDupe = Utils->FindServer(sname);
830 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
831 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
834 this->Instance->SNO->WriteToSnoMask('l',"Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
837 std::string name = InspSocketNameRequest((Module*)Utils->Creator, this->Hook).Send();
838 this->Instance->SNO->WriteToSnoMask('l',"Connection from \2"+sname+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] using transport \2"+name+"\2");
841 this->InboundServerName = sname;
842 this->InboundDescription = description;
843 // this is good. Send our details: Our server name and description and hopcount of 0,
844 // along with the sendpass from this block.
845 this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+x->SendPass+" 0 :"+this->Instance->Config->ServerDesc);
846 // move to the next state, we are now waiting for THEM.
847 this->LinkState = WAIT_AUTH_2;
851 this->WriteLine("ERROR :Invalid credentials");
852 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
856 void TreeSocket::Split(const std::string &line, std::deque<std::string> &n)
859 irc::tokenstream tokens(line);
861 while ((param = tokens.GetToken()) != "")
866 bool TreeSocket::ProcessLine(std::string &line)
868 std::deque<std::string> params;
872 line = line.substr(0, line.find_first_of("\r\n"));
877 Instance->Log(DEBUG, "<- %s", line.c_str());
879 this->Split(line.c_str(),params);
881 if ((params[0][0] == ':') && (params.size() > 1))
883 prefix = params[0].substr(1);
886 command = params[0].c_str();
888 switch (this->LinkState)
893 // Waiting for SERVER command from remote server. Server initiating
894 // the connection sends the first SERVER command, listening server
895 // replies with theirs if its happy, then if the initiator is happy,
896 // it starts to send its net sync, which starts the merge, otherwise
897 // it sends an ERROR.
898 if (command == "PASS")
900 /* Silently ignored */
902 else if (command == "SERVER")
904 return this->Inbound_Server(params);
906 else if (command == "ERROR")
908 return this->Error(params);
910 else if (command == "USER")
912 this->WriteLine("ERROR :Client connections to this port are prohibited.");
915 else if (command == "CAPAB")
917 return this->Capab(params);
919 else if ((command == "U") || (command == "S"))
921 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
926 std::string error("ERROR :Invalid command in negotiation phase: ");
927 error.append(command.c_str());
928 this->WriteLine(error);
933 // Waiting for start of other side's netmerge to say they liked our
935 if (command == "SERVER")
937 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
941 else if ((command == "U") || (command == "S"))
943 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
946 else if (command == "BURST")
948 if (params.size() && Utils->EnableTimeSync)
950 /* If a time stamp is provided, apply synchronization */
952 time_t them = atoi(params[0].c_str());
953 time_t us = Instance->Time(false);
954 int delta = them - us;
955 if ((params.size() == 2) && (params[1] == "FORCE"))
957 if ((delta < -600) || (delta > 600))
959 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));
960 this->WriteLine("ERROR :Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than ten minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
964 if (force || (us > them))
966 this->Instance->SetTimeDelta(them - us);
967 // Send this new timestamp to any other servers
968 Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
972 // Override the timestamp
973 this->WriteLine(":" + Utils->TreeRoot->GetName() + " TIMESET " + ConvToStr(us));
976 this->LinkState = CONNECTED;
977 Node = new TreeServer(this->Utils,this->Instance,InboundServerName,InboundDescription,Utils->TreeRoot,this);
978 Utils->TreeRoot->AddChild(Node);
980 params.push_back(InboundServerName);
981 params.push_back("*");
982 params.push_back("1");
983 params.push_back(":"+InboundDescription);
984 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,InboundServerName);
985 this->bursting = true;
988 else if (command == "ERROR")
990 return this->Error(params);
992 else if (command == "CAPAB")
994 return this->Capab(params);
999 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
1003 if (command == "SERVER")
1005 // another server we connected to, which was in WAIT_AUTH_1 state,
1006 // has just sent us their credentials. If we get this far, theyre
1007 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1008 // if we're happy with this, we should send our netburst which
1009 // kickstarts the merge.
1010 return this->Outbound_Reply_Server(params);
1012 else if (command == "ERROR")
1014 return this->Error(params);
1018 // This is the 'authenticated' state, when all passwords
1019 // have been exchanged and anything past this point is taken
1024 std::string direction = prefix;
1025 userrec* t = this->Instance->FindNick(prefix);
1028 direction = t->server;
1030 TreeServer* route_back_again = Utils->BestRouteTo(direction);
1031 if ((!route_back_again) || (route_back_again->GetSocket() != this))
1033 if (route_back_again)
1034 Instance->Log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
1038 * When there is activity on the socket, reset the ping counter so
1039 * that we're not wasting bandwidth pinging an active server.
1041 route_back_again->SetNextPingTime(time(NULL) + 60);
1042 route_back_again->SetPingFlag();
1045 if (command == "SVSMODE")
1047 /* Services expects us to implement
1048 * SVSMODE. In inspircd its the same as
1053 std::string target = "";
1054 /* Yes, know, this is a mess. Its reasonably fast though as we're
1055 * working with std::string here.
1057 if ((command == "NICK") && (params.size() >= 8))
1059 return this->IntroduceClient(prefix,params);
1061 else if (command == "FJOIN")
1063 return this->ForceJoin(prefix,params);
1065 else if (command == "STATS")
1067 return this->Stats(prefix, params);
1069 else if (command == "MOTD")
1071 return this->Motd(prefix, params);
1073 else if (command == "ADMIN")
1075 return this->Admin(prefix, params);
1077 else if (command == "SERVER")
1079 return this->RemoteServer(prefix,params);
1081 else if (command == "ERROR")
1083 return this->Error(params);
1085 else if (command == "OPERTYPE")
1087 return this->OperType(prefix,params);
1089 else if (command == "FMODE")
1091 return this->ForceMode(prefix,params);
1093 else if (command == "KILL")
1095 return this->RemoteKill(prefix,params);
1097 else if (command == "FTOPIC")
1099 return this->ForceTopic(prefix,params);
1101 else if (command == "REHASH")
1103 return this->RemoteRehash(prefix,params);
1105 else if (command == "METADATA")
1107 return this->MetaData(prefix,params);
1109 else if (command == "REMSTATUS")
1111 return this->RemoveStatus(prefix,params);
1113 else if (command == "PING")
1116 * We just got a ping from a server that's bursting.
1117 * This can't be right, so set them to not bursting, and
1118 * apply their lines.
1122 this->bursting = false;
1123 Instance->XLines->apply_lines(Utils->lines_to_apply);
1124 Utils->lines_to_apply = 0;
1128 prefix = this->GetName();
1130 return this->LocalPing(prefix,params);
1132 else if (command == "PONG")
1135 * We just got a pong from a server that's bursting.
1136 * This can't be right, so set them to not bursting, and
1137 * apply their lines.
1141 this->bursting = false;
1142 Instance->XLines->apply_lines(Utils->lines_to_apply);
1143 Utils->lines_to_apply = 0;
1147 prefix = this->GetName();
1149 return this->LocalPong(prefix,params);
1151 else if (command == "VERSION")
1153 return this->ServerVersion(prefix,params);
1155 else if (command == "FHOST")
1157 return this->ChangeHost(prefix,params);
1159 else if (command == "FNAME")
1161 return this->ChangeName(prefix,params);
1163 else if (command == "ADDLINE")
1165 return this->AddLine(prefix,params);
1167 else if (command == "SVSNICK")
1171 prefix = this->GetName();
1173 return this->ForceNick(prefix,params);
1175 else if (command == "OPERQUIT")
1177 return this->OperQuit(prefix,params);
1179 else if (command == "RSQUIT")
1181 return this->RemoteSquit(prefix, params);
1183 else if (command == "IDLE")
1185 return this->Whois(prefix,params);
1187 else if (command == "PUSH")
1189 return this->Push(prefix,params);
1191 else if (command == "TIMESET")
1193 return this->HandleSetTime(prefix, params);
1195 else if (command == "TIME")
1197 return this->Time(prefix,params);
1199 else if ((command == "KICK") && (Utils->IsServer(prefix)))
1201 std::string sourceserv = this->myhost;
1202 if (params.size() == 3)
1204 userrec* user = this->Instance->FindNick(params[1]);
1205 chanrec* chan = this->Instance->FindChan(params[0]);
1208 if (!chan->ServerKickUser(user, params[2].c_str(), false))
1209 /* Yikes, the channels gone! */
1213 if (this->InboundServerName != "")
1215 sourceserv = this->InboundServerName;
1217 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1219 else if (command == "SVSJOIN")
1223 prefix = this->GetName();
1225 return this->ServiceJoin(prefix,params);
1227 else if (command == "SQUIT")
1229 if (params.size() == 2)
1231 this->Squit(Utils->FindServer(params[0]),params[1]);
1235 else if (command == "OPERNOTICE")
1237 std::string sourceserv = this->myhost;
1238 if (this->InboundServerName != "")
1239 sourceserv = this->InboundServerName;
1240 if (params.size() >= 1)
1241 Instance->WriteOpers("*** From " + sourceserv + ": " + params[0]);
1242 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1244 else if (command == "MODENOTICE")
1246 std::string sourceserv = this->myhost;
1247 if (this->InboundServerName != "")
1248 sourceserv = this->InboundServerName;
1249 if (params.size() >= 2)
1251 Instance->WriteMode(params[0].c_str(), WM_AND, "*** From %s: %s", sourceserv.c_str(), params[1].c_str());
1253 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1255 else if (command == "SNONOTICE")
1257 std::string sourceserv = this->myhost;
1258 if (this->InboundServerName != "")
1259 sourceserv = this->InboundServerName;
1260 if (params.size() >= 2)
1262 Instance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + sourceserv + ": "+ params[1]);
1264 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
1266 else if (command == "ENDBURST")
1268 this->bursting = false;
1269 Instance->XLines->apply_lines(Utils->lines_to_apply);
1270 Utils->lines_to_apply = 0;
1271 std::string sourceserv = this->myhost;
1272 if (this->InboundServerName != "")
1274 sourceserv = this->InboundServerName;
1276 this->Instance->SNO->WriteToSnoMask('l',"Received end of netburst from \2%s\2",sourceserv.c_str());
1278 Event rmode((char*)sourceserv.c_str(), (Module*)Utils->Creator, "new_server");
1279 rmode.Send(Instance);
1285 // not a special inter-server command.
1286 // Emulate the actual user doing the command,
1287 // this saves us having a huge ugly parser.
1288 userrec* who = this->Instance->FindNick(prefix);
1289 std::string sourceserv = this->myhost;
1290 if (this->InboundServerName != "")
1292 sourceserv = this->InboundServerName;
1294 if ((!who) && (command == "MODE"))
1296 if (Utils->IsServer(prefix))
1298 const char* modelist[127];
1299 for (size_t i = 0; i < params.size(); i++)
1300 modelist[i] = params[i].c_str();
1301 userrec* fake = new userrec(Instance);
1302 fake->SetFd(FD_MAGIC_NUMBER);
1303 this->Instance->SendMode(modelist, params.size(), fake);
1306 /* Hot potato! pass it on! */
1307 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1312 if ((command == "NICK") && (params.size() > 0))
1314 /* On nick messages, check that the nick doesnt
1315 * already exist here. If it does, kill their copy,
1318 userrec* x = this->Instance->FindNick(params[0]);
1319 if ((x) && (x != who))
1321 std::deque<std::string> p;
1322 p.push_back(params[0]);
1323 p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
1324 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
1326 p.push_back(prefix);
1327 p.push_back("Nickname collision");
1328 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
1329 userrec::QuitUser(this->Instance,x,"Nickname collision ("+prefix+" -> "+params[0]+")");
1330 userrec* y = this->Instance->FindNick(prefix);
1333 userrec::QuitUser(this->Instance,y,"Nickname collision");
1335 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1339 target = who->server;
1340 const char* strparams[127];
1341 for (unsigned int q = 0; q < params.size(); q++)
1343 strparams[q] = params[q].c_str();
1345 switch (this->Instance->CallCommandHandler(command.c_str(), strparams, params.size(), who))
1348 this->WriteLine("ERROR :Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
1355 /* CMD_SUCCESS and CMD_USER_DELETED fall through here */
1361 // its not a user. Its either a server, or somethings screwed up.
1362 if (Utils->IsServer(prefix))
1363 target = this->Instance->Config->ServerName;
1367 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1376 std::string TreeSocket::GetName()
1378 std::string sourceserv = this->myhost;
1379 if (this->InboundServerName != "")
1381 sourceserv = this->InboundServerName;
1386 void TreeSocket::OnTimeout()
1388 if (this->LinkState == CONNECTING)
1390 this->Instance->SNO->WriteToSnoMask('l',"CONNECT: Connection to \002"+myhost+"\002 timed out.");
1391 Link* MyLink = Utils->FindLink(myhost);
1393 Utils->DoFailOver(MyLink);
1397 void TreeSocket::OnClose()
1399 // Connection closed.
1400 // If the connection is fully up (state CONNECTED)
1401 // then propogate a netsplit to all peers.
1402 std::string quitserver = this->myhost;
1403 if (this->InboundServerName != "")
1405 quitserver = this->InboundServerName;
1407 TreeServer* s = Utils->FindServer(quitserver);
1410 Squit(s,"Remote host closed the connection");
1413 if (quitserver != "")
1414 this->Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' failed.",quitserver.c_str());
1417 int TreeSocket::OnIncomingConnection(int newsock, char* ip)
1419 /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
1420 * or discovering if this port is the server port, we don't allow connections from any
1421 * IPs for which we don't have a link block.
1425 found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), ip) != Utils->ValidIPs.end());
1428 for (vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
1429 if (irc::sockets::MatchCIDR(ip, (*i).c_str()))
1434 this->Instance->SNO->WriteToSnoMask('l',"Server connection from %s denied (no link blocks with that IP address)", ip);
1440 TreeSocket* s = new TreeSocket(this->Utils, this->Instance, newsock, ip, this->Hook);
1441 s = s; /* Whinge whinge whinge, thats all GCC ever does. */