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 /* $ModDesc: Provides a spanning tree server link protocol */
16 #include "configreader.h"
20 #include "commands/cmd_whois.h"
21 #include "commands/cmd_stats.h"
26 #include "transport.h"
28 #include "m_spanningtree/utils.h"
29 #include "m_spanningtree/treeserver.h"
31 /** If you make a change which breaks the protocol, increment this.
32 * If you completely change the protocol, completely change the number.
34 * IMPORTANT: If you make changes, document your changes here, without fail:
35 * http://www.inspircd.org/wiki/List_of_protocol_changes_between_versions
37 * Failure to document your protocol changes will result in a painfully
38 * painful death by pain. You have been warned.
40 const long ProtocolVersion = 1103;
43 * The server list in InspIRCd is maintained as two structures
44 * which hold the data in different ways. Most of the time, we
45 * want to very quicky obtain three pieces of information:
47 * (1) The information on a server
48 * (2) The information on the server we must send data through
49 * to actually REACH the server we're after
50 * (3) Potentially, the child/parent objects of this server
52 * The InspIRCd spanning protocol provides easy access to these
53 * by storing the data firstly in a recursive structure, where
54 * each item references its parent item, and a dynamic list
55 * of child items, and another structure which stores the items
56 * hashed, linearly. This means that if we want to find a server
57 * by name quickly, we can look it up in the hash, avoiding
58 * any O(n) lookups. If however, during a split or sync, we want
59 * to apply an operation to a server, and any of its child objects
60 * we can resort to recursion to walk the tree structure.
61 * Any socket can have one of five states at any one time.
62 * The LISTENER state indicates a socket which is listening
63 * for connections. It cannot receive data itself, only incoming
65 * The CONNECTING state indicates an outbound socket which is
66 * waiting to be writeable.
67 * The WAIT_AUTH_1 state indicates the socket is outbound and
68 * has successfully connected, but has not yet sent and received
70 * The WAIT_AUTH_2 state indicates that the socket is inbound
71 * (allocated by a LISTENER) but has not yet sent and received
73 * The CONNECTED state represents a fully authorized, fully
76 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
78 /* Foward declarations */
82 class ModuleSpanningTree;
84 /** The Link class might as well be a struct,
85 * but this is C++ and we don't believe in structs (!).
86 * It holds the entire information of one <link>
87 * tag from the main config file. We maintain a list
88 * of them, and populate the list on rehash/load.
90 class Link : public classbase
98 unsigned long AutoConnect;
99 time_t NextConnectTime;
100 bool HiddenFromStats;
101 std::string FailOver;
106 class HandshakeTimer : public InspTimer
112 SpanningTreeUtilities* Utils;
115 HandshakeTimer(InspIRCd* Inst, TreeSocket* s, Link* l, SpanningTreeUtilities* u);
116 virtual void Tick(time_t TIME);
122 class cmd_rconnect : public command_t
125 SpanningTreeUtilities* Utils;
127 cmd_rconnect (InspIRCd* Instance, Module* Callback, SpanningTreeUtilities* Util) : command_t(Instance, "RCONNECT", 'o', 2), Creator(Callback), Utils(Util)
129 this->source = "m_spanningtree.so";
130 syntax = "<remote-server-mask> <target-server-mask>";
133 CmdResult Handle (const char** parameters, int pcnt, userrec *user)
137 if (!Utils->FindServer(parameters[0]))
139 user->WriteServ("NOTICE %s :*** RCONNECT: Server \002%s\002 isn't connected to the network!", user->nick, parameters[0]);
143 user->WriteServ("NOTICE %s :*** RCONNECT: Sending remote connect to \002%s\002 to connect server \002%s\002.",user->nick,parameters[0],parameters[1]);
146 /* Is this aimed at our server? */
147 if (ServerInstance->MatchText(ServerInstance->Config->ServerName,parameters[0]))
149 /* Yes, initiate the given connect */
150 ServerInstance->SNO->WriteToSnoMask('l',"Remote CONNECT from %s matching \002%s\002, connecting server \002%s\002",user->nick,parameters[0],parameters[1]);
152 para[0] = parameters[1];
153 std::string original_command = std::string("CONNECT ") + parameters[1];
154 Creator->OnPreCommand("CONNECT", para, 1, user, true, original_command);
163 /** Every SERVER connection inbound or outbound is represented by
164 * an object of type TreeSocket.
165 * TreeSockets, being inherited from InspSocket, can be tied into
166 * the core socket engine, and we cn therefore receive activity events
167 * for them, just like activex objects on speed. (yes really, that
168 * is a technical term!) Each of these which relates to a locally
169 * connected server is assocated with it, by hooking it onto a
170 * TreeSocket class using its constructor. In this way, we can
171 * maintain a list of servers, some of which are directly connected,
172 * some of which are not.
174 class TreeSocket : public InspSocket
176 SpanningTreeUtilities* Utils;
178 std::string in_buffer;
179 ServerState LinkState;
180 std::string InboundServerName;
181 std::string InboundDescription;
183 int num_lost_servers;
185 bool LastPingWasGood;
187 unsigned int keylength;
188 std::string ModuleList;
189 std::map<std::string,std::string> CapKeys;
194 /** Because most of the I/O gubbins are encapsulated within
195 * InspSocket, we just call the superclass constructor for
196 * most of the action, and append a few of our own values
199 TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime, Module* HookMod = NULL)
200 : InspSocket(SI, host, port, listening, maxtime), Utils(Util), Hook(HookMod)
203 this->LinkState = LISTENER;
204 if (listening && Hook)
205 InspSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
208 TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName, Module* HookMod = NULL)
209 : InspSocket(SI, host, port, listening, maxtime), Utils(Util), Hook(HookMod)
212 this->LinkState = CONNECTING;
215 InspSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
218 /** When a listening socket gives us a new file descriptor,
219 * we must associate it with a socket without creating a new
220 * connection. This constructor is used for this purpose.
222 TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, int newfd, char* ip, Module* HookMod = NULL)
223 : InspSocket(SI, newfd, ip), Utils(Util), Hook(HookMod)
225 this->LinkState = WAIT_AUTH_1;
227 /* If we have a transport module hooked to the parent, hook the same module to this
228 * socket, and set a timer waiting for handshake before we send CAPAB etc.
232 InspSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
233 Instance->Timers->AddTimer(new HandshakeTimer(Instance, this, &(Utils->LinkBlocks[0]), this->Utils));
237 /* Otherwise, theres no lower layer transport in plain TCP/IP,
238 * so just send the capabilities right now.
240 this->SendCapabilities();
244 ServerState GetLinkState()
246 return this->LinkState;
257 InspSocketUnhookRequest(this, (Module*)Utils->Creator, Hook).Send();
260 /** When an outbound connection finishes connecting, we receive
261 * this event, and must send our SERVER string to the other
262 * side. If the other side is happy, as outlined in the server
263 * to server docs on the inspircd.org site, the other side
264 * will then send back its own server string.
266 virtual bool OnConnected()
268 if (this->LinkState == CONNECTING)
270 /* we do not need to change state here. */
271 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
273 if (x->Name == this->myhost)
275 this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] started.");
279 InspSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
280 this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] using transport \2"+x->Hook+"\2");
283 this->SendCapabilities();
285 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
287 Instance->Timers->AddTimer(new HandshakeTimer(Instance, this, &(*x), this->Utils));
289 this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+x->SendPass+" 0 :"+this->Instance->Config->ServerDesc);
295 /* There is a (remote) chance that between the /CONNECT and the connection
296 * being accepted, some muppet has removed the <link> block and rehashed.
297 * If that happens the connection hangs here until it's closed. Unlikely
298 * and rather harmless.
300 this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2 lost link tag(!)");
304 virtual void OnError(InspSocketError e)
306 /* We don't handle this method, because all our
307 * dirty work is done in OnClose() (see below)
308 * which is still called on error conditions too.
310 if (e == I_ERR_CONNECT)
312 this->Instance->SNO->WriteToSnoMask('l',"Connection failed: Connection to \002"+myhost+"\002 refused");
313 Link* MyLink = Utils->FindLink(myhost);
315 Utils->DoFailOver(MyLink);
319 virtual int OnDisconnect()
321 /* For the same reason as above, we don't
322 * handle OnDisconnect()
327 /** Recursively send the server tree with distances as hops.
328 * This is used during network burst to inform the other server
329 * (and any of ITS servers too) of what servers we know about.
330 * If at any point any of these servers already exist on the other
331 * end, our connection may be terminated. The hopcounts given
332 * by this function are relative, this doesn't matter so long as
333 * they are all >1, as all the remote servers re-calculate them
334 * to be relative too, with themselves as hop 0.
336 void SendServers(TreeServer* Current, TreeServer* s, int hops)
339 for (unsigned int q = 0; q < Current->ChildCount(); q++)
341 TreeServer* recursive_server = Current->GetChild(q);
342 if (recursive_server != s)
344 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
345 this->WriteLine(command);
346 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
347 /* down to next level */
348 this->SendServers(recursive_server, s, hops+1);
353 std::string MyCapabilities()
355 std::vector<std::string> modlist;
356 std::string capabilities = "";
358 for (int i = 0; i <= this->Instance->GetModuleCount(); i++)
360 if (this->Instance->modules[i]->GetVersion().Flags & VF_COMMON)
361 modlist.push_back(this->Instance->Config->module_names[i]);
363 sort(modlist.begin(),modlist.end());
364 for (unsigned int i = 0; i < modlist.size(); i++)
367 capabilities = capabilities + ",";
368 capabilities = capabilities + modlist[i];
373 void SendCapabilities()
375 irc::commasepstream modulelist(MyCapabilities());
377 this->WriteLine("CAPAB START");
379 /* Send module names, split at 509 length */
380 std::string item = "*";
381 std::string line = "CAPAB MODULES ";
382 while ((item = modulelist.GetToken()) != "")
384 if (line.length() + item.length() + 1 > 509)
386 this->WriteLine(line);
387 line = "CAPAB MODULES ";
390 if (line != "CAPAB MODULES ")
395 if (line != "CAPAB MODULES ")
396 this->WriteLine(line);
403 #ifdef SUPPORT_IP6LINKS
406 this->WriteLine("CAPAB CAPABILITIES :NICKMAX="+ConvToStr(NICKMAX)+" HALFOP="+ConvToStr(this->Instance->Config->AllowHalfop)+" CHANMAX="+ConvToStr(CHANMAX)+" MAXMODES="+ConvToStr(MAXMODES)+" IDENTMAX="+ConvToStr(IDENTMAX)+" MAXQUIT="+ConvToStr(MAXQUIT)+" MAXTOPIC="+ConvToStr(MAXTOPIC)+" MAXKICK="+ConvToStr(MAXKICK)+" MAXGECOS="+ConvToStr(MAXGECOS)+" MAXAWAY="+ConvToStr(MAXAWAY)+" IP6NATIVE="+ConvToStr(ip6)+" IP6SUPPORT="+ConvToStr(ip6support)+" PROTOCOL="+ConvToStr(ProtocolVersion));
408 this->WriteLine("CAPAB END");
411 /* Check a comma seperated list for an item */
412 bool HasItem(const std::string &list, const std::string &item)
414 irc::commasepstream seplist(list);
416 std::string item2 = "*";
417 while ((item2 = seplist.GetToken()) != "")
426 /* Isolate and return the elements that are different between two comma seperated lists */
427 std::string ListDifference(const std::string &one, const std::string &two)
429 irc::commasepstream list_one(one);
430 std::string item = "*";
431 std::string result = "";
432 while ((item = list_one.GetToken()) != "")
434 if (!HasItem(two, item))
443 bool Capab(const std::deque<std::string> ¶ms)
445 if (params.size() < 1)
447 this->WriteLine("ERROR :Invalid number of parameters for CAPAB - Mismatched version");
451 if (params[0] == "START")
453 this->ModuleList = "";
454 this->CapKeys.clear();
456 else if (params[0] == "END")
458 std::string reason = "";
460 #ifdef SUPPORT_IP6LINKS
463 /* Compare ModuleList and check CapKeys...
464 * Maybe this could be tidier? -- Brain
466 if ((this->ModuleList != this->MyCapabilities()) && (this->ModuleList.length()))
468 std::string diff = ListDifference(this->ModuleList, this->MyCapabilities());
471 diff = "your server:" + ListDifference(this->MyCapabilities(), this->ModuleList);
475 diff = "this server:" + diff;
477 if (diff.length() == 12)
478 reason = "Module list in CAPAB is not alphabetically ordered, cannot compare lists.";
480 reason = "Modules loaded on these servers are not correctly matched, these modules are not loaded on " + diff;
483 if (((this->CapKeys.find("IP6SUPPORT") == this->CapKeys.end()) && (ip6support)) || ((this->CapKeys.find("IP6SUPPORT") != this->CapKeys.end()) && (this->CapKeys.find("IP6SUPPORT")->second != ConvToStr(ip6support))))
484 reason = "We don't both support linking to IPV6 servers";
486 if (((this->CapKeys.find("IP6NATIVE") != this->CapKeys.end()) && (this->CapKeys.find("IP6NATIVE")->second == "1")) && (!ip6support))
487 reason = "The remote server is IPV6 native, and we don't support linking to IPV6 servers";
489 if (((this->CapKeys.find("NICKMAX") == this->CapKeys.end()) || ((this->CapKeys.find("NICKMAX") != this->CapKeys.end()) && (this->CapKeys.find("NICKMAX")->second != ConvToStr(NICKMAX)))))
490 reason = "Maximum nickname lengths differ or remote nickname length not specified";
492 if (((this->CapKeys.find("PROTOCOL") == this->CapKeys.end()) || ((this->CapKeys.find("PROTOCOL") != this->CapKeys.end()) && (this->CapKeys.find("PROTOCOL")->second != ConvToStr(ProtocolVersion)))))
494 if (this->CapKeys.find("PROTOCOL") != this->CapKeys.end())
496 reason = "Mismatched protocol versions "+this->CapKeys.find("PROTOCOL")->second+" and "+ConvToStr(ProtocolVersion);
500 reason = "Protocol version not specified";
504 if (((this->CapKeys.find("HALFOP") == this->CapKeys.end()) && (Instance->Config->AllowHalfop)) || ((this->CapKeys.find("HALFOP") != this->CapKeys.end()) && (this->CapKeys.find("HALFOP")->second != ConvToStr(Instance->Config->AllowHalfop))))
505 reason = "We don't both have halfop support enabled/disabled identically";
507 if (((this->CapKeys.find("IDENTMAX") == this->CapKeys.end()) || ((this->CapKeys.find("IDENTMAX") != this->CapKeys.end()) && (this->CapKeys.find("IDENTMAX")->second != ConvToStr(IDENTMAX)))))
508 reason = "Maximum ident lengths differ or remote ident length not specified";
510 if (((this->CapKeys.find("CHANMAX") == this->CapKeys.end()) || ((this->CapKeys.find("CHANMAX") != this->CapKeys.end()) && (this->CapKeys.find("CHANMAX")->second != ConvToStr(CHANMAX)))))
511 reason = "Maximum channel lengths differ or remote channel length not specified";
513 if (((this->CapKeys.find("MAXMODES") == this->CapKeys.end()) || ((this->CapKeys.find("MAXMODES") != this->CapKeys.end()) && (this->CapKeys.find("MAXMODES")->second != ConvToStr(MAXMODES)))))
514 reason = "Maximum modes per line differ or remote modes per line not specified";
516 if (((this->CapKeys.find("MAXQUIT") == this->CapKeys.end()) || ((this->CapKeys.find("MAXQUIT") != this->CapKeys.end()) && (this->CapKeys.find("MAXQUIT")->second != ConvToStr(MAXQUIT)))))
517 reason = "Maximum quit lengths differ or remote quit length not specified";
519 if (((this->CapKeys.find("MAXTOPIC") == this->CapKeys.end()) || ((this->CapKeys.find("MAXTOPIC") != this->CapKeys.end()) && (this->CapKeys.find("MAXTOPIC")->second != ConvToStr(MAXTOPIC)))))
520 reason = "Maximum topic lengths differ or remote topic length not specified";
522 if (((this->CapKeys.find("MAXKICK") == this->CapKeys.end()) || ((this->CapKeys.find("MAXKICK") != this->CapKeys.end()) && (this->CapKeys.find("MAXKICK")->second != ConvToStr(MAXKICK)))))
523 reason = "Maximum kick lengths differ or remote kick length not specified";
525 if (((this->CapKeys.find("MAXGECOS") == this->CapKeys.end()) || ((this->CapKeys.find("MAXGECOS") != this->CapKeys.end()) && (this->CapKeys.find("MAXGECOS")->second != ConvToStr(MAXGECOS)))))
526 reason = "Maximum GECOS (fullname) lengths differ or remote GECOS length not specified";
528 if (((this->CapKeys.find("MAXAWAY") == this->CapKeys.end()) || ((this->CapKeys.find("MAXAWAY") != this->CapKeys.end()) && (this->CapKeys.find("MAXAWAY")->second != ConvToStr(MAXAWAY)))))
529 reason = "Maximum awaymessage lengths differ or remote awaymessage length not specified";
533 this->WriteLine("ERROR :CAPAB negotiation failed: "+reason);
537 else if ((params[0] == "MODULES") && (params.size() == 2))
539 if (!this->ModuleList.length())
541 this->ModuleList.append(params[1]);
545 this->ModuleList.append(",");
546 this->ModuleList.append(params[1]);
549 else if ((params[0] == "CAPABILITIES") && (params.size() == 2))
551 irc::tokenstream capabs(params[1]);
552 std::string item = "*";
553 while ((item = capabs.GetToken()) != "")
555 /* Process each key/value pair */
556 std::string::size_type equals = item.rfind('=');
557 if (equals != std::string::npos)
559 std::string var = item.substr(0, equals);
560 std::string value = item.substr(equals+1, item.length());
561 CapKeys[var] = value;
569 /** This function forces this server to quit, removing this server
570 * and any users on it (and servers and users below that, etc etc).
571 * It's very slow and pretty clunky, but luckily unless your network
572 * is having a REAL bad hair day, this function shouldnt be called
573 * too many times a month ;-)
575 void SquitServer(std::string &from, TreeServer* Current)
577 /* recursively squit the servers attached to 'Current'.
578 * We're going backwards so we don't remove users
579 * while we still need them ;)
581 for (unsigned int q = 0; q < Current->ChildCount(); q++)
583 TreeServer* recursive_server = Current->GetChild(q);
584 this->SquitServer(from,recursive_server);
586 /* Now we've whacked the kids, whack self */
588 num_lost_users += Current->QuitUsers(from);
591 /** This is a wrapper function for SquitServer above, which
592 * does some validation first and passes on the SQUIT to all
593 * other remaining servers.
595 void Squit(TreeServer* Current, const std::string &reason)
597 if ((Current) && (Current != Utils->TreeRoot))
599 Event rmode((char*)Current->GetName().c_str(), (Module*)Utils->Creator, "lost_server");
600 rmode.Send(Instance);
602 std::deque<std::string> params;
603 params.push_back(Current->GetName());
604 params.push_back(":"+reason);
605 Utils->DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
606 if (Current->GetParent() == Utils->TreeRoot)
608 this->Instance->WriteOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
612 this->Instance->WriteOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
614 num_lost_servers = 0;
616 std::string from = Current->GetParent()->GetName()+" "+Current->GetName();
617 SquitServer(from, Current);
619 Current->GetParent()->DelChild(Current);
621 this->Instance->WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
625 Instance->Log(DEFAULT,"Squit from unknown server");
629 /** FMODE command - server mode with timestamp checks */
630 bool ForceMode(const std::string &source, std::deque<std::string> ¶ms)
632 /* Chances are this is a 1.0 FMODE without TS */
633 if (params.size() < 3)
635 /* No modes were in the command, probably a channel with no modes set on it */
640 std::string sourceserv;
642 /* Are we dealing with an FMODE from a user, or from a server? */
643 userrec* who = this->Instance->FindNick(source);
646 /* FMODE from a user, set sourceserv to the users server name */
647 sourceserv = who->server;
651 /* FMODE from a server, create a fake user to receive mode feedback */
652 who = new userrec(this->Instance);
653 who->SetFd(FD_MAGIC_NUMBER);
654 smode = true; /* Setting this flag tells us we should free the userrec later */
655 sourceserv = source; /* Set sourceserv to the actual source string */
657 const char* modelist[64];
660 memset(&modelist,0,sizeof(modelist));
661 for (unsigned int q = 0; (q < params.size()) && (q < 64); q++)
665 /* The timestamp is in this position.
666 * We don't want to pass that up to the
667 * server->client protocol!
669 TS = atoi(params[q].c_str());
673 /* Everything else is fine to append to the modelist */
674 modelist[n++] = params[q].c_str();
678 /* Extract the TS value of the object, either userrec or chanrec */
679 userrec* dst = this->Instance->FindNick(params[0]);
680 chanrec* chan = NULL;
688 chan = this->Instance->FindChan(params[0]);
694 /* Oops, channel doesnt exist! */
698 /* TS is equal: Merge the mode changes, use voooodoooooo on modes
703 ModeHandler* mh = NULL;
704 unsigned long paramptr = 3;
705 std::string to_bounce = "";
706 std::string to_keep = "";
707 std::vector<std::string> params_to_keep;
708 std::string params_to_bounce = "";
712 char old_bounce_change = 0;
713 /* Merge modes, basically do special stuff to mode with params */
714 for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
727 /* We only care about whats being set,
728 * not whats being unset
730 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
732 if ((mh) && (mh->GetNumParams(adding) > 0) && (!mh->IsListMode()))
734 /* We only want to do special things to
735 * modes with parameters, we are going to rewrite
739 adding ? cur_change = '+' : cur_change = '-';
741 ret = mh->ModeSet(smode ? NULL : who, dst, chan, params[paramptr]);
743 /* The mode is set here, check which we should keep */
746 bool which_to_keep = mh->CheckTimeStamp(TS, ourTS, params[paramptr], ret.second, chan);
748 if (which_to_keep == true)
750 /* Keep ours, bounce theirs:
751 * Send back ours to them and
752 * drop their mode changs
754 adding ? cur_change = '+' : cur_change = '-';
755 if (cur_change != old_bounce_change)
756 to_bounce += cur_change;
758 old_bounce_change = cur_change;
760 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
761 params_to_bounce.append(" ").append(ret.second);
765 /* Keep theirs: Accept their mode change,
768 adding ? cur_change = '+' : cur_change = '-';
769 if (cur_change != old_change)
770 to_keep += cur_change;
772 old_change = cur_change;
774 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
775 params_to_keep.push_back(params[paramptr]);
780 /* Mode isnt set here, we want it */
781 adding ? cur_change = '+' : cur_change = '-';
782 if (cur_change != old_change)
783 to_keep += cur_change;
785 old_change = cur_change;
787 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
788 params_to_keep.push_back(params[paramptr]);
795 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
799 adding ? cur_change = '+' : cur_change = '-';
801 /* Just keep this, safe to merge with no checks
802 * it has no parameters
805 if (cur_change != old_change)
806 to_keep += cur_change;
808 old_change = cur_change;
810 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
812 params_to_keep.push_back(params[paramptr++]);
819 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
823 /* Taking a mode away */
824 adding ? cur_change = '+' : cur_change = '-';
826 if (cur_change != old_change)
827 to_keep += cur_change;
829 old_change = cur_change;
831 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
832 params_to_keep.push_back(params[paramptr++]);
839 if (to_bounce.length())
841 std::deque<std::string> newparams;
842 newparams.push_back(params[0]);
843 newparams.push_back(ConvToStr(ourTS));
844 newparams.push_back(to_bounce+params_to_bounce);
845 Utils->DoOneToOne(this->Instance->Config->ServerName,"FMODE",newparams,sourceserv);
848 if (to_keep.length())
852 modelist[0] = params[0].c_str();
853 modelist[1] = to_keep.c_str();
855 if (params_to_keep.size() > 0)
857 for (q = 0; (q < params_to_keep.size()) && (q < 64); q++)
859 modelist[n++] = params_to_keep[q].c_str();
865 this->Instance->SendMode(modelist, n, who);
869 this->Instance->CallCommandHandler("MODE", modelist, n, who);
872 /* HOT POTATO! PASS IT ON! */
873 Utils->DoOneToAllButSender(source,"FMODE",params,sourceserv);
877 /* U-lined servers always win regardless of their TS */
878 if ((TS > ourTS) && (!this->Instance->ULine(source.c_str())))
880 /* Bounce the mode back to its sender.* We use our lower TS, so the other end
881 * SHOULD accept it, if its clock is right.
883 * NOTE: We should check that we arent bouncing anything thats already set at this end.
884 * If we are, bounce +ourmode to 'reinforce' it. This prevents desyncs.
885 * e.g. They send +l 50, we have +l 10 set. rather than bounce -l 50, we bounce +l 10.
887 * Thanks to jilles for pointing out this one-hell-of-an-issue before i even finished
888 * writing the code. It took me a while to come up with this solution.
890 * XXX: BE SURE YOU UNDERSTAND THIS CODE FULLY BEFORE YOU MESS WITH IT.
893 std::deque<std::string> newparams; /* New parameter list we send back */
894 newparams.push_back(params[0]); /* Target, user or channel */
895 newparams.push_back(ConvToStr(ourTS)); /* Timestamp value of the target */
896 newparams.push_back(""); /* This contains the mode string. For now
897 * it's empty, we fill it below.
900 /* Intelligent mode bouncing. Don't just invert, reinforce any modes which are already
901 * set to avoid a desync here.
903 std::string modebounce = "";
906 ModeHandler* mh = NULL;
909 for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
911 /* Iterate over all mode chars in the sent set */
914 /* Adding or subtracting modes? */
922 /* Find the mode handler for this mode */
923 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
925 /* Got a mode handler?
926 * This also prevents us bouncing modes we have no handler for.
933 /* Does the mode require a parameter right now?
934 * If it does, fetch it if we can
936 if ((mh->GetNumParams(adding) > 0) && (t < params.size()))
939 /* Call the ModeSet method to determine if its set with the
940 * given parameter here or not.
942 ret = mh->ModeSet(smode ? NULL : who, dst, chan, p);
944 /* XXX: Really. Dont ask.
945 * Determine from if its set combined with what the current
946 * 'state' is (adding or not) as to wether we should 'invert'
947 * or 'reinforce' the mode change
949 (!ret.first ? (adding ? cur_change = '-' : cur_change = '+') : (!adding ? cur_change = '-' : cur_change = '+'));
951 /* Quickly determine if we have 'flipped' from + to -,
952 * or - to +, to prevent unneccessary +/- chars in the
953 * output string that waste bandwidth
955 if (cur_change != old_change)
956 modebounce += cur_change;
957 old_change = cur_change;
959 /* Add the mode character to the output string */
960 modebounce += mh->GetModeChar();
962 /* We got a parameter back from ModeHandler::ModeSet,
963 * are we supposed to be sending one out right now?
965 if (ret.second.length())
967 if (mh->GetNumParams(cur_change == '+') > 0)
968 /* Yes we're supposed to be sending out
969 * the parameter. Make sure it goes
971 newparams.push_back(ret.second);
979 /* Update the parameters for FMODE with the new 'bounced' string */
980 newparams[2] = modebounce;
981 /* Only send it back the way it came, no need to send it anywhere else */
982 Utils->DoOneToOne(this->Instance->Config->ServerName,"FMODE",newparams,sourceserv);
986 /* The server was ulined, but something iffy is up with the TS.
987 * Sound the alarm bells!
989 if ((this->Instance->ULine(sourceserv.c_str())) && (TS > ourTS))
991 this->Instance->WriteOpers("\2WARNING!\2 U-Lined server '%s' has bad TS for '%s' (accepted change): \2SYNC YOUR CLOCKS\2 to avoid this notice",sourceserv.c_str(),params[0].c_str());
993 /* Allow the mode, route it to either server or user command handling */
995 this->Instance->SendMode(modelist,n,who);
997 this->Instance->CallCommandHandler("MODE", modelist, n, who);
999 /* HOT POTATO! PASS IT ON! */
1000 Utils->DoOneToAllButSender(source,"FMODE",params,sourceserv);
1002 /* Are we supposed to free the userrec? */
1009 /** FTOPIC command */
1010 bool ForceTopic(const std::string &source, std::deque<std::string> ¶ms)
1012 if (params.size() != 4)
1014 time_t ts = atoi(params[1].c_str());
1015 std::string nsource = source;
1017 chanrec* c = this->Instance->FindChan(params[0]);
1020 if ((ts >= c->topicset) || (!*c->topic))
1022 std::string oldtopic = c->topic;
1023 strlcpy(c->topic,params[3].c_str(),MAXTOPIC);
1024 strlcpy(c->setby,params[2].c_str(),NICKMAX-1);
1026 /* if the topic text is the same as the current topic,
1027 * dont bother to send the TOPIC command out, just silently
1028 * update the set time and set nick.
1030 if (oldtopic != params[3])
1032 userrec* user = this->Instance->FindNick(source);
1035 c->WriteChannelWithServ(source.c_str(), "TOPIC %s :%s", c->name, c->topic);
1039 c->WriteChannel(user, "TOPIC %s :%s", c->name, c->topic);
1040 nsource = user->server;
1042 /* all done, send it on its way */
1043 params[3] = ":" + params[3];
1044 Utils->DoOneToAllButSender(source,"FTOPIC",params,nsource);
1053 /** FJOIN, similar to TS6 SJOIN, but not quite. */
1054 bool ForceJoin(const std::string &source, std::deque<std::string> ¶ms)
1056 /* 1.1 FJOIN works as follows:
1058 * Each FJOIN is sent along with a timestamp, and the side with the lowest
1059 * timestamp 'wins'. From this point on we will refer to this side as the
1060 * winner. The side with the higher timestamp loses, from this point on we
1061 * will call this side the loser or losing side. This should be familiar to
1062 * anyone who's dealt with dreamforge or TS6 before.
1064 * When two sides of a split heal and this occurs, the following things
1067 * If the timestamps are exactly equal, both sides merge their privilages
1068 * and users, as in InspIRCd 1.0 and ircd2.8. The channels have not been
1069 * re-created during a split, this is safe to do.
1072 * If the timestamps are NOT equal, the losing side removes all privilage
1073 * modes from all of its users that currently exist in the channel, before
1074 * introducing new users into the channel which are listed in the FJOIN
1075 * command's parameters. This means, all modes +ohv, and privilages added
1076 * by modules, such as +qa. The losing side then LOWERS its timestamp value
1077 * of the channel to match that of the winning side, and the modes of the
1078 * users of the winning side are merged in with the losing side. The loser
1079 * then sends out a set of FMODE commands which 'confirm' that it just
1080 * removed all privilage modes from its existing users, which allows for
1081 * services packages to still work correctly without needing to know the
1082 * timestamping rules which InspIRCd follows. In TS6 servers this is always
1083 * a problem, and services packages must contain code which explicitly
1084 * behaves as TS6 does, removing ops from the losing side of a split where
1085 * neccessary within its internal records, as this state information is
1086 * not explicitly echoed out in that protocol.
1088 * The winning side on the other hand will ignore all user modes from the
1089 * losing side, so only its own modes get applied. Life is simple for those
1090 * who succeed at internets. :-)
1092 * NOTE: Unlike TS6 and dreamforge and other protocols which have SJOIN,
1093 * FJOIN does not contain the simple-modes such as +iklmnsp. Why not,
1094 * you ask? Well, quite simply because we don't need to. They'll be sent
1095 * after the FJOIN by FMODE, and FMODE is timestamped, so in the event
1096 * the losing side sends any modes for the channel which shouldnt win,
1097 * they wont as their timestamp will be too high :-)
1100 if (params.size() < 3)
1103 char first[MAXBUF]; /* The first parameter of the mode command */
1104 char modestring[MAXBUF]; /* The mode sequence (2nd parameter) of the mode command */
1105 char* mode_users[127]; /* The values used by the mode command */
1106 memset(&mode_users,0,sizeof(mode_users)); /* Initialize mode parameters */
1107 mode_users[0] = first; /* Set this up to be our on-stack value */
1108 mode_users[1] = modestring; /* Same here as above */
1109 strcpy(modestring,"+"); /* Initialize the mode sequence to just '+' */
1110 unsigned int modectr = 2; /* Pointer to the third mode parameter (e.g. the one after the +-sequence) */
1112 userrec* who = NULL; /* User we are currently checking */
1113 std::string channel = params[0]; /* Channel name, as a string */
1114 time_t TS = atoi(params[1].c_str()); /* Timestamp given to us for remote side */
1115 bool created = false;
1117 /* Try and find the channel */
1118 chanrec* chan = this->Instance->FindChan(channel);
1120 /* Initialize channel name in the mode parameters */
1121 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
1123 /* default TS is a high value, which if we dont have this
1124 * channel will let the other side apply their modes.
1126 time_t ourTS = Instance->Time(true)+600;
1128 /* Does this channel exist? if it does, get its REAL timestamp */
1132 created = true; /* don't perform deops, and set TS to correct time after processing. */
1134 /* In 1.1, if they have the newer channel, we immediately clear
1135 * all status modes from our users. We then accept their modes.
1136 * If WE have the newer channel its the other side's job to do this.
1137 * Note that this causes the losing server to send out confirming
1142 std::deque<std::string> param_list;
1144 /* Lower the TS here */
1145 if (Utils->AnnounceTSChange && chan)
1146 chan->WriteChannelWithServ(Instance->Config->ServerName,
1147 "NOTICE %s :TS for %s changed from %lu to %lu", chan->name, chan->name, ourTS, TS);
1150 /* Zap all the privilage modes on our side, if the channel exists here */
1153 param_list.push_back(channel);
1154 /* Do this first! */
1156 this->RemoveStatus(Instance->Config->ServerName, param_list);
1160 /* Put the final parameter of the FJOIN into a tokenstream ready to split it */
1161 irc::tokenstream users(params[2]);
1162 std::string item = "*";
1164 /* do this first, so our mode reversals are correctly received by other servers
1165 * if there is a TS collision.
1167 params[2] = ":" + params[2];
1168 Utils->DoOneToAllButSender(source,"FJOIN",params,source);
1170 /* Now, process every 'prefixes,nick' pair */
1173 /* Find next user */
1174 item = users.GetToken();
1176 const char* usr = item.c_str();
1178 /* Safety check just to make sure someones not sent us an FJOIN full of spaces
1179 * (is this even possible?) */
1182 const char* permissions = usr;
1184 char* nm = new char[MAXBUF];
1187 /* Iterate through all the prefix values, convert them from prefixes
1188 * to mode letters, and append them to the mode sequence
1190 while ((*permissions) && (*permissions != ',') && (ntimes < MAXBUF))
1192 ModeHandler* mh = Instance->Modes->FindPrefix(*permissions);
1195 /* This is a valid prefix */
1197 *tnm++ = mh->GetModeChar();
1201 /* Not a valid prefix...
1202 * danger bill bobbertson! (that's will robinsons older brother ;-) ...)
1204 this->Instance->WriteOpers("ERROR: We received a user with an unknown prefix '%c'. Closed connection to avoid a desync.",*permissions);
1205 this->WriteLine(std::string("ERROR :Invalid prefix '")+(*permissions)+"' in FJOIN");
1212 /* Null terminate modes */
1214 /* Advance past the comma, to the nick */
1217 /* Check the user actually exists */
1218 who = this->Instance->FindNick(usr);
1221 /* Did they get any modes? How many times? */
1222 strlcat(modestring, nm, MAXBUF);
1223 for (int k = 0; k < ntimes; k++)
1224 mode_users[modectr++] = strdup(usr);
1226 /* Free temporary buffer used for mode sequence */
1229 /* Check that the user's 'direction' is correct
1230 * based on the server sending the FJOIN. We must
1231 * check each nickname in turn, because the origin of
1232 * the FJOIN may be different to the origin of the nicks
1233 * in the command itself.
1235 TreeServer* route_back_again = Utils->BestRouteTo(who->server);
1236 if ((!route_back_again) || (route_back_again->GetSocket() != this))
1238 /* Oh dear oh dear. */
1241 /* Finally, we can actually place the user into the channel.
1242 * We're sure its right. Final answer, phone a friend.
1244 chanrec::JoinUser(this->Instance, who, channel.c_str(), true, "");
1246 /* Have we already queued up MAXMODES modes with parameters
1247 * (+qaohv) ready to be sent to the server?
1249 if (modectr >= (MAXMODES-1))
1251 /* Only actually give the users any status if we lost
1252 * the FJOIN or drew (equal timestamps).
1253 * It isn't actually possible for ourTS to be > TS here,
1254 * only possible to actually have ourTS == TS, or
1255 * ourTS < TS, because if we lost, we already lowered
1256 * our TS above before we entered this loop. We only
1257 * check >= as a safety measure, in case someone stuffed
1258 * up. If someone DID stuff up, it was most likely me.
1259 * Note: I do not like baseball bats in the face...
1263 this->Instance->SendMode((const char**)mode_users,modectr,who);
1265 /* Something stuffed up, and for some reason, the timestamp is
1266 * NOT lowered right now and should be. Lower it. Usually this
1267 * code won't be executed, doubtless someone will remove it some
1272 Instance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",chan->name,ourTS,TS);
1278 /* Reset all this back to defaults, and
1279 * free any ram we have left allocated.
1281 strcpy(mode_users[1],"+");
1282 for (unsigned int f = 2; f < modectr; f++)
1283 free(mode_users[f]);
1289 /* Remember to free this */
1291 /* If we got here, there's a nick in FJOIN which doesnt exist on this server.
1292 * We don't try to process the nickname here (that WOULD cause a segfault because
1293 * we'd be playing with null pointers) however, we DO pass the nickname on, just
1294 * in case somehow we're desynched, so that other users which might be able to see
1295 * the nickname get their fair chance to process it.
1297 Instance->Log(SPARSE,"Warning! Invalid user in FJOIN to channel %s IGNORED", channel.c_str());
1303 /* there werent enough modes built up to flush it during FJOIN,
1304 * or, there are a number left over. flush them out.
1306 if ((modectr > 2) && (who) && (chan))
1310 /* Our channel is newer than theirs. Evil deeds must be afoot. */
1311 this->Instance->SendMode((const char**)mode_users,modectr,who);
1312 /* Yet again, we can't actually get a true value here, if everything else
1313 * is working as it should.
1317 Instance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",chan->name,ourTS,TS);
1323 /* Free anything we have left to free */
1324 for (unsigned int f = 2; f < modectr; f++)
1325 free(mode_users[f]);
1328 /* if we newly created the channel, set it's TS properly. */
1331 /* find created channel .. */
1332 chan = this->Instance->FindChan(channel);
1334 /* w00t said this shouldnt be needed but it is.
1335 * This isnt strictly true, as chan can be NULL
1336 * if a nick collision has occured and therefore
1337 * the channel was never created.
1342 /* All done. That wasnt so bad was it, you can wipe
1343 * the sweat from your forehead now. :-)
1349 bool IntroduceClient(const std::string &source, std::deque<std::string> ¶ms)
1351 if (params.size() < 8)
1353 if (params.size() > 8)
1355 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[1]+"?)");
1358 // NICK age nick host dhost ident +modes ip :gecos
1360 time_t age = atoi(params[0].c_str());
1362 const char* tempnick = params[1].c_str();
1363 Instance->Log(DEBUG,"New remote client %s",tempnick);
1365 user_hash::iterator iter = this->Instance->clientlist->find(tempnick);
1367 if (iter != this->Instance->clientlist->end())
1370 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+tempnick+" :Nickname collision");
1371 userrec::QuitUser(this->Instance, iter->second, "Nickname collision");
1375 userrec* _new = new userrec(this->Instance);
1376 (*(this->Instance->clientlist))[tempnick] = _new;
1377 _new->SetFd(FD_MAGIC_NUMBER);
1378 strlcpy(_new->nick, tempnick,NICKMAX-1);
1379 strlcpy(_new->host, params[2].c_str(),63);
1380 strlcpy(_new->dhost, params[3].c_str(),63);
1381 _new->server = this->Instance->FindServerNamePtr(source.c_str());
1382 strlcpy(_new->ident, params[4].c_str(),IDENTMAX);
1383 strlcpy(_new->fullname, params[7].c_str(),MAXGECOS);
1384 _new->registered = REG_ALL;
1388 * we need to remove the + from the modestring, so we can do our stuff
1390 std::string::size_type pos_after_plus = params[5].find_first_not_of('+');
1391 if (pos_after_plus != std::string::npos)
1392 params[5] = params[5].substr(pos_after_plus);
1395 for (std::string::iterator v = params[5].begin(); v != params[5].end(); v++)
1397 _new->modes[(*v)-65] = 1;
1398 /* For each mode thats set, increase counter */
1399 ModeHandler* mh = Instance->Modes->FindMode(*v, MODETYPE_USER);
1404 /* now we've done with modes processing, put the + back for remote servers */
1405 params[5] = "+" + params[5];
1407 #ifdef SUPPORT_IP6LINKS
1408 if (params[6].find_first_of(":") != std::string::npos)
1409 _new->SetSockAddr(AF_INET6, params[6].c_str(), 0);
1412 _new->SetSockAddr(AF_INET, params[6].c_str(), 0);
1414 Instance->AddGlobalClone(_new);
1416 this->Instance->SNO->WriteToSnoMask('C',"Client connecting at %s: %s!%s@%s [%s]",_new->server,_new->nick,_new->ident,_new->host, _new->GetIPString());
1418 params[7] = ":" + params[7];
1419 Utils->DoOneToAllButSender(source,"NICK", params, source);
1421 // Increment the Source Servers User Count..
1422 TreeServer* SourceServer = Utils->FindServer(source);
1425 SourceServer->AddUserCount();
1428 FOREACH_MOD_I(Instance,I_OnPostConnect,OnPostConnect(_new));
1433 /** Send one or more FJOINs for a channel of users.
1434 * If the length of a single line is more than 480-NICKMAX
1435 * in length, it is split over multiple lines.
1437 void SendFJoins(TreeServer* Current, chanrec* c)
1441 std::string individual_halfops = std::string(":")+this->Instance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age);
1443 size_t dlen, curlen;
1444 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1446 char* ptr = list + dlen;
1448 CUList *ulist = c->GetUsers();
1449 std::string modes = "";
1450 std::string params = "";
1452 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1454 // The first parameter gets a : before it
1455 size_t ptrlen = snprintf(ptr, MAXBUF, " %s%s,%s", !numusers ? ":" : "", c->GetAllPrefixChars(i->second), i->second->nick);
1462 if (curlen > (480-NICKMAX))
1464 buffer.append(list).append("\r\n");
1466 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1474 buffer.append(list).append("\r\n");
1476 /* Sorry for the hax. Because newly created channels assume +nt,
1477 * if this channel doesnt have +nt, explicitly send -n and -t for the missing modes.
1479 bool inverted = false;
1480 if (!c->IsModeSet('n'))
1485 if (!c->IsModeSet('t'))
1495 for (BanList::iterator b = c->bans.begin(); b != c->bans.end(); b++)
1498 params.append(" ").append(b->data);
1500 if (params.length() >= MAXMODES)
1502 /* Wrap at MAXMODES */
1503 buffer.append(":").append(this->Instance->Config->ServerName).append(" FMODE ").append(c->name).append(" ").append(ConvToStr(c->age)).append(" +").append(modes).append(params).append("\r\n");
1509 buffer.append(":").append(this->Instance->Config->ServerName).append(" FMODE ").append(c->name).append(" ").append(ConvToStr(c->age)).append(" +").append(c->ChanModes(true));
1511 /* Only send these if there are any */
1513 buffer.append("\r\n").append(":").append(this->Instance->Config->ServerName).append(" FMODE ").append(c->name).append(" ").append(ConvToStr(c->age)).append(" +").append(modes).append(params);
1515 this->WriteLine(buffer);
1518 /** Send G, Q, Z and E lines */
1519 void SendXLines(TreeServer* Current)
1523 std::string n = this->Instance->Config->ServerName;
1524 const char* sn = n.c_str();
1526 /* Yes, these arent too nice looking, but they get the job done */
1527 for (std::vector<ZLine*>::iterator i = Instance->XLines->zlines.begin(); i != Instance->XLines->zlines.end(); i++)
1529 snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s\r\n",sn,(*i)->ipaddr,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
1530 buffer.append(data);
1532 for (std::vector<QLine*>::iterator i = Instance->XLines->qlines.begin(); i != Instance->XLines->qlines.end(); i++)
1534 snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s\r\n",sn,(*i)->nick,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
1535 buffer.append(data);
1537 for (std::vector<GLine*>::iterator i = Instance->XLines->glines.begin(); i != Instance->XLines->glines.end(); i++)
1539 snprintf(data,MAXBUF,":%s ADDLINE G %s@%s %s %lu %lu :%s\r\n",sn,(*i)->identmask,(*i)->hostmask,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
1540 buffer.append(data);
1542 for (std::vector<ELine*>::iterator i = Instance->XLines->elines.begin(); i != Instance->XLines->elines.end(); i++)
1544 snprintf(data,MAXBUF,":%s ADDLINE E %s@%s %s %lu %lu :%s\r\n",sn,(*i)->identmask,(*i)->hostmask,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
1545 buffer.append(data);
1547 for (std::vector<ZLine*>::iterator i = Instance->XLines->pzlines.begin(); i != Instance->XLines->pzlines.end(); i++)
1549 snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s\r\n",sn,(*i)->ipaddr,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
1550 buffer.append(data);
1552 for (std::vector<QLine*>::iterator i = Instance->XLines->pqlines.begin(); i != Instance->XLines->pqlines.end(); i++)
1554 snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s\r\n",sn,(*i)->nick,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
1555 buffer.append(data);
1557 for (std::vector<GLine*>::iterator i = Instance->XLines->pglines.begin(); i != Instance->XLines->pglines.end(); i++)
1559 snprintf(data,MAXBUF,":%s ADDLINE G %s@%s %s %lu %lu :%s\r\n",sn,(*i)->identmask,(*i)->hostmask,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
1560 buffer.append(data);
1562 for (std::vector<ELine*>::iterator i = Instance->XLines->pelines.begin(); i != Instance->XLines->pelines.end(); i++)
1564 snprintf(data,MAXBUF,":%s ADDLINE E %s@%s %s %lu %lu :%s\r\n",sn,(*i)->identmask,(*i)->hostmask,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
1565 buffer.append(data);
1568 if (!buffer.empty())
1569 this->WriteLine(buffer);
1572 /** Send channel modes and topics */
1573 void SendChannelModes(TreeServer* Current)
1576 std::deque<std::string> list;
1577 std::string n = this->Instance->Config->ServerName;
1578 const char* sn = n.c_str();
1579 for (chan_hash::iterator c = this->Instance->chanlist->begin(); c != this->Instance->chanlist->end(); c++)
1581 SendFJoins(Current, c->second);
1582 if (*c->second->topic)
1584 snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",sn,c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
1585 this->WriteLine(data);
1587 FOREACH_MOD_I(this->Instance,I_OnSyncChannel,OnSyncChannel(c->second,(Module*)Utils->Creator,(void*)this));
1589 c->second->GetExtList(list);
1590 for (unsigned int j = 0; j < list.size(); j++)
1592 FOREACH_MOD_I(this->Instance,I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)Utils->Creator,(void*)this,list[j]));
1597 /** send all users and their oper state/modes */
1598 void SendUsers(TreeServer* Current)
1601 std::deque<std::string> list;
1602 std::string dataline;
1603 for (user_hash::iterator u = this->Instance->clientlist->begin(); u != this->Instance->clientlist->end(); u++)
1605 if (u->second->registered == REG_ALL)
1607 snprintf(data,MAXBUF,":%s NICK %lu %s %s %s %s +%s %s :%s",u->second->server,(unsigned long)u->second->age,u->second->nick,u->second->host,u->second->dhost,u->second->ident,u->second->FormatModes(),u->second->GetIPString(),u->second->fullname);
1608 this->WriteLine(data);
1609 if (*u->second->oper)
1611 snprintf(data,MAXBUF,":%s OPERTYPE %s", u->second->nick, u->second->oper);
1612 this->WriteLine(data);
1614 if (*u->second->awaymsg)
1616 snprintf(data,MAXBUF,":%s AWAY :%s", u->second->nick, u->second->awaymsg);
1617 this->WriteLine(data);
1619 FOREACH_MOD_I(this->Instance,I_OnSyncUser,OnSyncUser(u->second,(Module*)Utils->Creator,(void*)this));
1621 u->second->GetExtList(list);
1622 for (unsigned int j = 0; j < list.size(); j++)
1624 FOREACH_MOD_I(this->Instance,I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)Utils->Creator,(void*)this,list[j]));
1630 /** This function is called when we want to send a netburst to a local
1631 * server. There is a set order we must do this, because for example
1632 * users require their servers to exist, and channels require their
1633 * users to exist. You get the idea.
1635 void DoBurst(TreeServer* s)
1637 std::string burst = "BURST "+ConvToStr(Instance->Time(true));
1638 std::string endburst = "ENDBURST";
1639 // Because by the end of the netburst, it could be gone!
1640 std::string name = s->GetName();
1641 this->Instance->SNO->WriteToSnoMask('l',"Bursting to \2"+name+"\2.");
1642 this->WriteLine(burst);
1643 /* send our version string */
1644 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" VERSION :"+this->Instance->GetVersionString());
1645 /* Send server tree */
1646 this->SendServers(Utils->TreeRoot,s,1);
1647 /* Send users and their oper status */
1649 /* Send everything else (channel modes, xlines etc) */
1650 this->SendChannelModes(s);
1651 this->SendXLines(s);
1652 FOREACH_MOD_I(this->Instance,I_OnSyncOtherMetaData,OnSyncOtherMetaData((Module*)Utils->Creator,(void*)this));
1653 this->WriteLine(endburst);
1654 this->Instance->SNO->WriteToSnoMask('l',"Finished bursting to \2"+name+"\2.");
1657 /** This function is called when we receive data from a remote
1658 * server. We buffer the data in a std::string (it doesnt stay
1659 * there for long), reading using InspSocket::Read() which can
1660 * read up to 16 kilobytes in one operation.
1662 * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
1663 * THE SOCKET OBJECT FOR US.
1665 virtual bool OnDataReady()
1667 char* data = this->Read();
1668 /* Check that the data read is a valid pointer and it has some content */
1671 this->in_buffer.append(data);
1672 /* While there is at least one new line in the buffer,
1673 * do something useful (we hope!) with it.
1675 while (in_buffer.find("\n") != std::string::npos)
1677 std::string ret = in_buffer.substr(0,in_buffer.find("\n")-1);
1678 in_buffer = in_buffer.substr(in_buffer.find("\n")+1,in_buffer.length()-in_buffer.find("\n"));
1679 /* Use rfind here not find, as theres more
1680 * chance of the \r being near the end of the
1681 * string, not the start.
1683 if (ret.find("\r") != std::string::npos)
1684 ret = in_buffer.substr(0,in_buffer.find("\r")-1);
1685 /* Process this one, abort if it
1686 * didnt return true.
1688 if (!this->ProcessLine(ret))
1695 /* EAGAIN returns an empty but non-NULL string, so this
1696 * evaluates to TRUE for EAGAIN but to FALSE for EOF.
1698 return (data && !*data);
1701 int WriteLine(std::string line)
1703 Instance->Log(DEBUG, "-> %s", line.c_str());
1704 line.append("\r\n");
1705 return this->Write(line);
1708 /* Handle ERROR command */
1709 bool Error(std::deque<std::string> ¶ms)
1711 if (params.size() < 1)
1713 this->Instance->SNO->WriteToSnoMask('l',"ERROR from %s: %s",(InboundServerName != "" ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
1714 /* we will return false to cause the socket to close. */
1718 /** remote MOTD. leet, huh? */
1719 bool Motd(const std::string &prefix, std::deque<std::string> ¶ms)
1721 if (params.size() > 0)
1723 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
1725 /* It's for our server */
1726 string_list results;
1727 userrec* source = this->Instance->FindNick(prefix);
1731 std::deque<std::string> par;
1732 par.push_back(prefix);
1735 if (!Instance->Config->MOTD.size())
1737 par[1] = std::string("::")+Instance->Config->ServerName+" 422 "+source->nick+" :Message of the day file is missing.";
1738 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
1742 par[1] = std::string("::")+Instance->Config->ServerName+" 375 "+source->nick+" :"+Instance->Config->ServerName+" message of the day";
1743 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
1745 for (unsigned int i = 0; i < Instance->Config->MOTD.size(); i++)
1747 par[1] = std::string("::")+Instance->Config->ServerName+" 372 "+source->nick+" :- "+Instance->Config->MOTD[i];
1748 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
1751 par[1] = std::string("::")+Instance->Config->ServerName+" 376 "+source->nick+" End of message of the day.";
1752 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
1758 userrec* source = this->Instance->FindNick(prefix);
1760 Utils->DoOneToOne(prefix, "MOTD", params, params[0]);
1766 /** remote ADMIN. leet, huh? */
1767 bool Admin(const std::string &prefix, std::deque<std::string> ¶ms)
1769 if (params.size() > 0)
1771 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
1773 /* It's for our server */
1774 string_list results;
1775 userrec* source = this->Instance->FindNick(prefix);
1779 std::deque<std::string> par;
1780 par.push_back(prefix);
1783 par[1] = std::string("::")+Instance->Config->ServerName+" 256 "+source->nick+" :Administrative info for "+Instance->Config->ServerName;
1784 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
1786 par[1] = std::string("::")+Instance->Config->ServerName+" 257 "+source->nick+" :Name - "+Instance->Config->AdminName;
1787 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
1789 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :Nickname - "+Instance->Config->AdminNick;
1790 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
1792 par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :E-Mail - "+Instance->Config->AdminEmail;
1793 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
1799 userrec* source = this->Instance->FindNick(prefix);
1801 Utils->DoOneToOne(prefix, "ADMIN", params, params[0]);
1807 bool Stats(const std::string &prefix, std::deque<std::string> ¶ms)
1809 /* Get the reply to a STATS query if it matches this servername,
1810 * and send it back as a load of PUSH queries
1812 if (params.size() > 1)
1814 if (this->Instance->MatchText(this->Instance->Config->ServerName, params[1]))
1816 /* It's for our server */
1817 string_list results;
1818 userrec* source = this->Instance->FindNick(prefix);
1821 std::deque<std::string> par;
1822 par.push_back(prefix);
1824 DoStats(this->Instance, *(params[0].c_str()), source, results);
1825 for (size_t i = 0; i < results.size(); i++)
1827 par[1] = "::" + results[i];
1828 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
1835 userrec* source = this->Instance->FindNick(prefix);
1837 Utils->DoOneToOne(prefix, "STATS", params, params[1]);
1844 /** Because the core won't let users or even SERVERS set +o,
1845 * we use the OPERTYPE command to do this.
1847 bool OperType(const std::string &prefix, std::deque<std::string> ¶ms)
1849 if (params.size() != 1)
1851 std::string opertype = params[0];
1852 userrec* u = this->Instance->FindNick(prefix);
1855 u->modes[UM_OPERATOR] = 1;
1856 this->Instance->all_opers.push_back(u);
1857 strlcpy(u->oper,opertype.c_str(),NICKMAX-1);
1858 Utils->DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
1859 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()));
1865 /** Because Andy insists that services-compatible servers must
1866 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
1868 bool ForceNick(const std::string &prefix, std::deque<std::string> ¶ms)
1870 if (params.size() < 3)
1873 userrec* u = this->Instance->FindNick(params[0]);
1877 Utils->DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
1880 std::deque<std::string> par;
1881 par.push_back(params[1]);
1882 /* This is not required as one is sent in OnUserPostNick below
1884 //Utils->DoOneToMany(u->nick,"NICK",par);
1885 if (!u->ForceNickChange(params[1].c_str()))
1887 userrec::QuitUser(this->Instance, u, "Nickname collision");
1890 u->age = atoi(params[2].c_str());
1897 * Remote SQUIT (RSQUIT). Routing works similar to SVSNICK: Route it to the server that the target is connected to locally,
1898 * then let that server do the dirty work (squit it!). Example:
1899 * 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
1901 bool RemoteSquit(const std::string &prefix, std::deque<std::string> ¶ms)
1903 /* ok.. :w00t RSQUIT jupe.barafranca.com :reason here */
1904 if (params.size() < 2)
1907 TreeServer* s = Utils->FindServerMask(params[0]);
1911 if (s == Utils->TreeRoot)
1913 this->Instance->SNO->WriteToSnoMask('l',"What the fuck, I recieved a remote SQUIT for myself? :< (from %s", prefix.c_str());
1917 TreeSocket* sock = s->GetSocket();
1921 /* it's locally connected, KILL IT! */
1922 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());
1923 sock->Squit(s,"Server quit by " + prefix + ": " + params[1]);
1924 Instance->SE->DelFd(sock);
1930 /* route the rsquit */
1931 params[1] = ":" + params[1];
1932 Utils->DoOneToOne(prefix, "RSQUIT", params, params[0]);
1937 /* mother fucker! it doesn't exist */
1943 bool ServiceJoin(const std::string &prefix, std::deque<std::string> ¶ms)
1945 if (params.size() < 2)
1948 userrec* u = this->Instance->FindNick(params[0]);
1952 /* only join if it's local, otherwise just pass it on! */
1954 chanrec::JoinUser(this->Instance, u, params[1].c_str(), false);
1955 Utils->DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
1960 bool RemoteRehash(const std::string &prefix, std::deque<std::string> ¶ms)
1962 if (params.size() < 1)
1965 std::string servermask = params[0];
1967 if (this->Instance->MatchText(this->Instance->Config->ServerName,servermask))
1969 this->Instance->SNO->WriteToSnoMask('l',"Remote rehash initiated by \002"+prefix+"\002.");
1970 this->Instance->RehashServer();
1971 Utils->ReadConfiguration(false);
1972 InitializeDisabledCommands(Instance->Config->DisabledCommands, Instance);
1974 Utils->DoOneToAllButSender(prefix,"REHASH",params,prefix);
1978 bool RemoteKill(const std::string &prefix, std::deque<std::string> ¶ms)
1980 if (params.size() != 2)
1983 std::string nick = params[0];
1984 userrec* u = this->Instance->FindNick(prefix);
1985 userrec* who = this->Instance->FindNick(nick);
1989 /* Prepend kill source, if we don't have one */
1990 std::string sourceserv = prefix;
1993 sourceserv = u->server;
1995 if (*(params[1].c_str()) != '[')
1997 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
1999 std::string reason = params[1];
2000 params[1] = ":" + params[1];
2001 Utils->DoOneToAllButSender(prefix,"KILL",params,sourceserv);
2002 who->Write(":%s KILL %s :%s (%s)", sourceserv.c_str(), who->nick, sourceserv.c_str(), reason.c_str());
2003 userrec::QuitUser(this->Instance,who,reason);
2008 bool LocalPong(const std::string &prefix, std::deque<std::string> ¶ms)
2010 if (params.size() < 1)
2013 if (params.size() == 1)
2015 TreeServer* ServerSource = Utils->FindServer(prefix);
2018 ServerSource->SetPingFlag();
2023 std::string forwardto = params[1];
2024 if (forwardto == this->Instance->Config->ServerName)
2027 * this is a PONG for us
2028 * if the prefix is a user, check theyre local, and if they are,
2029 * dump the PONG reply back to their fd. If its a server, do nowt.
2030 * Services might want to send these s->s, but we dont need to yet.
2032 userrec* u = this->Instance->FindNick(prefix);
2036 u->WriteServ("PONG %s %s",params[0].c_str(),params[1].c_str());
2041 // not for us, pass it on :)
2042 Utils->DoOneToOne(prefix,"PONG",params,forwardto);
2049 bool MetaData(const std::string &prefix, std::deque<std::string> ¶ms)
2051 if (params.size() < 3)
2054 TreeServer* ServerSource = Utils->FindServer(prefix);
2058 if (params[0] == "*")
2060 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));
2062 else if (*(params[0].c_str()) == '#')
2064 chanrec* c = this->Instance->FindChan(params[0]);
2067 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
2070 else if (*(params[0].c_str()) != '#')
2072 userrec* u = this->Instance->FindNick(params[0]);
2075 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
2080 params[2] = ":" + params[2];
2081 Utils->DoOneToAllButSender(prefix,"METADATA",params,prefix);
2085 bool ServerVersion(const std::string &prefix, std::deque<std::string> ¶ms)
2087 if (params.size() < 1)
2090 TreeServer* ServerSource = Utils->FindServer(prefix);
2094 ServerSource->SetVersion(params[0]);
2096 params[0] = ":" + params[0];
2097 Utils->DoOneToAllButSender(prefix,"VERSION",params,prefix);
2101 bool ChangeHost(const std::string &prefix, std::deque<std::string> ¶ms)
2103 if (params.size() < 1)
2106 userrec* u = this->Instance->FindNick(prefix);
2110 u->ChangeDisplayedHost(params[0].c_str());
2111 Utils->DoOneToAllButSender(prefix,"FHOST",params,u->server);
2116 bool AddLine(const std::string &prefix, std::deque<std::string> ¶ms)
2118 if (params.size() < 6)
2121 bool propogate = false;
2123 if (!this->bursting)
2124 Utils->lines_to_apply = 0;
2126 switch (*(params[0].c_str()))
2129 propogate = Instance->XLines->add_zline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2130 Instance->XLines->zline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2132 Utils->lines_to_apply |= APPLY_ZLINES;
2135 propogate = Instance->XLines->add_qline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2136 Instance->XLines->qline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2138 Utils->lines_to_apply |= APPLY_QLINES;
2141 propogate = Instance->XLines->add_eline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2142 Instance->XLines->eline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2145 propogate = Instance->XLines->add_gline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2146 Instance->XLines->gline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2148 Utils->lines_to_apply |= APPLY_GLINES;
2151 propogate = Instance->XLines->add_kline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2153 Utils->lines_to_apply |= APPLY_KLINES;
2156 /* Just in case... */
2157 this->Instance->SNO->WriteToSnoMask('x',"\2WARNING\2: Invalid xline type '"+params[0]+"' sent by server "+prefix+", ignored!");
2162 /* Send it on its way */
2165 if (atoi(params[4].c_str()))
2167 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());
2171 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());
2173 params[5] = ":" + params[5];
2174 Utils->DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
2176 if (!this->bursting)
2178 Instance->XLines->apply_lines(Utils->lines_to_apply);
2179 Utils->lines_to_apply = 0;
2184 bool ChangeName(const std::string &prefix, std::deque<std::string> ¶ms)
2186 if (params.size() < 1)
2189 userrec* u = this->Instance->FindNick(prefix);
2193 u->ChangeName(params[0].c_str());
2194 params[0] = ":" + params[0];
2195 Utils->DoOneToAllButSender(prefix,"FNAME",params,u->server);
2200 bool Whois(const std::string &prefix, std::deque<std::string> ¶ms)
2202 if (params.size() < 1)
2205 userrec* u = this->Instance->FindNick(prefix);
2208 // an incoming request
2209 if (params.size() == 1)
2211 userrec* x = this->Instance->FindNick(params[0]);
2212 if ((x) && (IS_LOCAL(x)))
2214 userrec* x = this->Instance->FindNick(params[0]);
2215 char signon[MAXBUF];
2218 snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
2219 snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-Instance->Time(true)));
2220 std::deque<std::string> par;
2221 par.push_back(prefix);
2222 par.push_back(signon);
2223 par.push_back(idle);
2224 // ours, we're done, pass it BACK
2225 Utils->DoOneToOne(params[0],"IDLE",par,u->server);
2229 // not ours pass it on
2230 Utils->DoOneToOne(prefix,"IDLE",params,x->server);
2233 else if (params.size() == 3)
2235 std::string who_did_the_whois = params[0];
2236 userrec* who_to_send_to = this->Instance->FindNick(who_did_the_whois);
2237 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2239 // an incoming reply to a whois we sent out
2240 std::string nick_whoised = prefix;
2241 unsigned long signon = atoi(params[1].c_str());
2242 unsigned long idle = atoi(params[2].c_str());
2243 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2244 do_whois(this->Instance,who_to_send_to,u,signon,idle,nick_whoised.c_str());
2248 // not ours, pass it on
2249 Utils->DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
2256 bool Push(const std::string &prefix, std::deque<std::string> ¶ms)
2258 if (params.size() < 2)
2261 userrec* u = this->Instance->FindNick(params[0]);
2268 u->Write(params[1]);
2272 // continue the raw onwards
2273 params[1] = ":" + params[1];
2274 Utils->DoOneToOne(prefix,"PUSH",params,u->server);
2279 bool HandleSetTime(const std::string &prefix, std::deque<std::string> ¶ms)
2281 if (!params.size() || !Utils->EnableTimeSync)
2286 if ((params.size() == 2) && (params[1] == "FORCE"))
2289 time_t rts = atoi(params[0].c_str());
2290 time_t us = Instance->Time(true);
2294 Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
2296 else if (force || (rts < us))
2298 int old = Instance->SetTimeDelta(rts - us);
2299 Instance->Log(DEBUG, "%s TS (diff %d) from %s applied (old delta was %d)", (force) ? "Forced" : "Lower", rts - us, prefix.c_str(), old);
2301 Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
2305 Instance->Log(DEBUG, "Higher TS (diff %d) from %s overridden", us - rts, prefix.c_str());
2307 std::deque<std::string> oparams;
2308 oparams.push_back(ConvToStr(us));
2310 Utils->DoOneToMany(prefix, "TIMESET", oparams);
2316 bool Time(const std::string &prefix, std::deque<std::string> ¶ms)
2318 // :source.server TIME remote.server sendernick
2319 // :remote.server TIME source.server sendernick TS
2320 if (params.size() == 2)
2322 // someone querying our time?
2323 if (this->Instance->Config->ServerName == params[0])
2325 userrec* u = this->Instance->FindNick(params[1]);
2328 params.push_back(ConvToStr(Instance->Time(false)));
2330 Utils->DoOneToOne(this->Instance->Config->ServerName,"TIME",params,params[0]);
2335 // not us, pass it on
2336 userrec* u = this->Instance->FindNick(params[1]);
2338 Utils->DoOneToOne(prefix,"TIME",params,params[0]);
2341 else if (params.size() == 3)
2343 // a response to a previous TIME
2344 userrec* u = this->Instance->FindNick(params[1]);
2345 if ((u) && (IS_LOCAL(u)))
2347 time_t rawtime = atol(params[2].c_str());
2348 struct tm * timeinfo;
2349 timeinfo = localtime(&rawtime);
2351 snprintf(tms,26,"%s",asctime(timeinfo));
2353 u->WriteServ("391 %s %s :%s",u->nick,prefix.c_str(),tms);
2358 Utils->DoOneToOne(prefix,"TIME",params,u->server);
2364 bool LocalPing(const std::string &prefix, std::deque<std::string> ¶ms)
2366 if (params.size() < 1)
2369 if (params.size() == 1)
2371 std::string stufftobounce = params[0];
2372 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" PONG "+stufftobounce);
2377 std::string forwardto = params[1];
2378 if (forwardto == this->Instance->Config->ServerName)
2380 // this is a ping for us, send back PONG to the requesting server
2381 params[1] = params[0];
2382 params[0] = forwardto;
2383 Utils->DoOneToOne(forwardto,"PONG",params,params[1]);
2387 // not for us, pass it on :)
2388 Utils->DoOneToOne(prefix,"PING",params,forwardto);
2394 bool RemoveStatus(const std::string &prefix, std::deque<std::string> ¶ms)
2396 if (params.size() < 1)
2399 chanrec* c = Instance->FindChan(params[0]);
2403 irc::modestacker modestack(false);
2404 CUList *ulist = c->GetUsers();
2406 std::deque<std::string> stackresult;
2409 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
2411 std::string modesequence = Instance->Modes->ModeString(i->second, c);
2412 if (modesequence.length())
2414 irc::spacesepstream sep(modesequence);
2415 std::string modeletters = sep.GetToken();
2417 while (!modeletters.empty())
2419 char mletter = *(modeletters.begin());
2420 modestack.Push(mletter,sep.GetToken());
2421 modeletters.erase(modeletters.begin());
2426 while (modestack.GetStackedLine(stackresult))
2428 stackresult.push_front(ConvToStr(c->age));
2429 stackresult.push_front(c->name);
2430 Utils->DoOneToMany(Instance->Config->ServerName, "FMODE", stackresult);
2431 stackresult.erase(stackresult.begin() + 1);
2432 for (size_t z = 0; z < stackresult.size(); z++)
2434 y[z] = stackresult[z].c_str();
2436 userrec* n = new userrec(Instance);
2437 n->SetFd(FD_MAGIC_NUMBER);
2438 Instance->SendMode(y, stackresult.size(), n);
2445 bool RemoteServer(const std::string &prefix, std::deque<std::string> ¶ms)
2447 if (params.size() < 4)
2450 std::string servername = params[0];
2451 std::string password = params[1];
2452 // hopcount is not used for a remote server, we calculate this ourselves
2453 std::string description = params[3];
2454 TreeServer* ParentOfThis = Utils->FindServer(prefix);
2458 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
2461 TreeServer* CheckDupe = Utils->FindServer(servername);
2464 this->WriteLine("ERROR :Server "+servername+" already exists!");
2465 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+servername+"\2 denied, already exists");
2468 TreeServer* Node = new TreeServer(this->Utils,this->Instance,servername,description,ParentOfThis,NULL);
2469 ParentOfThis->AddChild(Node);
2470 params[3] = ":" + params[3];
2471 Utils->DoOneToAllButSender(prefix,"SERVER",params,prefix);
2472 this->Instance->SNO->WriteToSnoMask('l',"Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
2476 bool Outbound_Reply_Server(std::deque<std::string> ¶ms)
2478 if (params.size() < 4)
2481 irc::string servername = params[0].c_str();
2482 std::string sname = params[0];
2483 std::string password = params[1];
2484 int hops = atoi(params[2].c_str());
2488 this->WriteLine("ERROR :Server too far away for authentication");
2489 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2492 std::string description = params[3];
2493 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
2495 if ((x->Name == servername) && (x->RecvPass == password))
2497 TreeServer* CheckDupe = Utils->FindServer(sname);
2500 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
2501 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
2504 // Begin the sync here. this kickstarts the
2505 // other side, waiting in WAIT_AUTH_2 state,
2506 // into starting their burst, as it shows
2507 // that we're happy.
2508 this->LinkState = CONNECTED;
2509 // we should add the details of this server now
2510 // to the servers tree, as a child of the root
2512 TreeServer* Node = new TreeServer(this->Utils,this->Instance,sname,description,Utils->TreeRoot,this);
2513 Utils->TreeRoot->AddChild(Node);
2514 params[3] = ":" + params[3];
2515 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,sname);
2516 this->bursting = true;
2517 this->DoBurst(Node);
2521 this->WriteLine("ERROR :Invalid credentials");
2522 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
2526 bool Inbound_Server(std::deque<std::string> ¶ms)
2528 if (params.size() < 4)
2531 irc::string servername = params[0].c_str();
2532 std::string sname = params[0];
2533 std::string password = params[1];
2534 int hops = atoi(params[2].c_str());
2538 this->WriteLine("ERROR :Server too far away for authentication");
2539 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2542 std::string description = params[3];
2543 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
2545 if ((x->Name == servername) && (x->RecvPass == password))
2547 TreeServer* CheckDupe = Utils->FindServer(sname);
2550 this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
2551 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
2554 this->Instance->SNO->WriteToSnoMask('l',"Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
2558 std::string name = InspSocketNameRequest((Module*)Utils->Creator, this->Hook).Send();
2559 this->Instance->SNO->WriteToSnoMask('l',"Connection from \2"+sname+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] using transport \2"+name+"\2");
2562 this->InboundServerName = sname;
2563 this->InboundDescription = description;
2564 // this is good. Send our details: Our server name and description and hopcount of 0,
2565 // along with the sendpass from this block.
2566 this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+x->SendPass+" 0 :"+this->Instance->Config->ServerDesc);
2567 // move to the next state, we are now waiting for THEM.
2568 this->LinkState = WAIT_AUTH_2;
2572 this->WriteLine("ERROR :Invalid credentials");
2573 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
2577 void Split(const std::string &line, std::deque<std::string> &n)
2580 irc::tokenstream tokens(line);
2582 while ((param = tokens.GetToken()) != "")
2587 bool ProcessLine(std::string &line)
2589 std::deque<std::string> params;
2590 irc::string command;
2593 line = line.substr(0, line.find_first_of("\r\n"));
2598 Instance->Log(DEBUG, "<- %s", line.c_str());
2600 this->Split(line.c_str(),params);
2602 if ((params[0][0] == ':') && (params.size() > 1))
2604 prefix = params[0].substr(1);
2608 command = params[0].c_str();
2611 switch (this->LinkState)
2616 // Waiting for SERVER command from remote server. Server initiating
2617 // the connection sends the first SERVER command, listening server
2618 // replies with theirs if its happy, then if the initiator is happy,
2619 // it starts to send its net sync, which starts the merge, otherwise
2620 // it sends an ERROR.
2621 if (command == "PASS")
2623 /* Silently ignored */
2625 else if (command == "SERVER")
2627 return this->Inbound_Server(params);
2629 else if (command == "ERROR")
2631 return this->Error(params);
2633 else if (command == "USER")
2635 this->WriteLine("ERROR :Client connections to this port are prohibited.");
2638 else if (command == "CAPAB")
2640 return this->Capab(params);
2642 else if ((command == "U") || (command == "S"))
2644 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
2649 std::string error("ERROR :Invalid command in negotiation phase: ");
2650 error.append(command.c_str());
2651 this->WriteLine(error);
2656 // Waiting for start of other side's netmerge to say they liked our
2658 if (command == "SERVER")
2660 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
2664 else if ((command == "U") || (command == "S"))
2666 this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
2669 else if (command == "BURST")
2671 if (params.size() && Utils->EnableTimeSync)
2673 /* If a time stamp is provided, apply synchronization */
2675 time_t them = atoi(params[0].c_str());
2676 time_t us = Instance->Time(true);
2677 int delta = them - us;
2679 if ((params.size() == 2) && (params[1] == "FORCE"))
2682 if ((delta < -600) || (delta > 600))
2684 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));
2685 this->WriteLine("ERROR :Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than ten minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
2689 if (force || (us > them))
2691 this->Instance->SetTimeDelta(them - us);
2692 // Send this new timestamp to any other servers
2693 Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
2697 // Override the timestamp
2698 this->WriteLine(":" + Utils->TreeRoot->GetName() + " TIMESET " + ConvToStr(us));
2701 this->LinkState = CONNECTED;
2702 Node = new TreeServer(this->Utils,this->Instance,InboundServerName,InboundDescription,Utils->TreeRoot,this);
2703 Utils->TreeRoot->AddChild(Node);
2705 params.push_back(InboundServerName);
2706 params.push_back("*");
2707 params.push_back("1");
2708 params.push_back(":"+InboundDescription);
2709 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,InboundServerName);
2710 this->bursting = true;
2711 this->DoBurst(Node);
2713 else if (command == "ERROR")
2715 return this->Error(params);
2717 else if (command == "CAPAB")
2719 return this->Capab(params);
2724 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
2728 if (command == "SERVER")
2730 // another server we connected to, which was in WAIT_AUTH_1 state,
2731 // has just sent us their credentials. If we get this far, theyre
2732 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
2733 // if we're happy with this, we should send our netburst which
2734 // kickstarts the merge.
2735 return this->Outbound_Reply_Server(params);
2737 else if (command == "ERROR")
2739 return this->Error(params);
2743 // This is the 'authenticated' state, when all passwords
2744 // have been exchanged and anything past this point is taken
2749 std::string direction = prefix;
2750 userrec* t = this->Instance->FindNick(prefix);
2753 direction = t->server;
2755 TreeServer* route_back_again = Utils->BestRouteTo(direction);
2756 if ((!route_back_again) || (route_back_again->GetSocket() != this))
2758 if (route_back_again)
2759 Instance->Log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
2764 * When there is activity on the socket, reset the ping counter so
2765 * that we're not wasting bandwidth pinging an active server.
2767 route_back_again->SetNextPingTime(time(NULL) + 60);
2768 route_back_again->SetPingFlag();
2771 if (command == "SVSMODE")
2773 /* Services expects us to implement
2774 * SVSMODE. In inspircd its the same as
2779 std::string target = "";
2780 /* Yes, know, this is a mess. Its reasonably fast though as we're
2781 * working with std::string here.
2783 if ((command == "NICK") && (params.size() > 1))
2785 return this->IntroduceClient(prefix,params);
2787 else if (command == "FJOIN")
2789 return this->ForceJoin(prefix,params);
2791 else if (command == "STATS")
2793 return this->Stats(prefix, params);
2795 else if (command == "MOTD")
2797 return this->Motd(prefix, params);
2799 else if (command == "ADMIN")
2801 return this->Admin(prefix, params);
2803 else if (command == "SERVER")
2805 return this->RemoteServer(prefix,params);
2807 else if (command == "ERROR")
2809 return this->Error(params);
2811 else if (command == "OPERTYPE")
2813 return this->OperType(prefix,params);
2815 else if (command == "FMODE")
2817 return this->ForceMode(prefix,params);
2819 else if (command == "KILL")
2821 return this->RemoteKill(prefix,params);
2823 else if (command == "FTOPIC")
2825 return this->ForceTopic(prefix,params);
2827 else if (command == "REHASH")
2829 return this->RemoteRehash(prefix,params);
2831 else if (command == "METADATA")
2833 return this->MetaData(prefix,params);
2835 else if (command == "REMSTATUS")
2837 return this->RemoveStatus(prefix,params);
2839 else if (command == "PING")
2842 * We just got a ping from a server that's bursting.
2843 * This can't be right, so set them to not bursting, and
2844 * apply their lines.
2848 this->bursting = false;
2849 Instance->XLines->apply_lines(Utils->lines_to_apply);
2850 Utils->lines_to_apply = 0;
2854 prefix = this->GetName();
2856 return this->LocalPing(prefix,params);
2858 else if (command == "PONG")
2861 * We just got a pong from a server that's bursting.
2862 * This can't be right, so set them to not bursting, and
2863 * apply their lines.
2867 this->bursting = false;
2868 Instance->XLines->apply_lines(Utils->lines_to_apply);
2869 Utils->lines_to_apply = 0;
2873 prefix = this->GetName();
2875 return this->LocalPong(prefix,params);
2877 else if (command == "VERSION")
2879 return this->ServerVersion(prefix,params);
2881 else if (command == "FHOST")
2883 return this->ChangeHost(prefix,params);
2885 else if (command == "FNAME")
2887 return this->ChangeName(prefix,params);
2889 else if (command == "ADDLINE")
2891 return this->AddLine(prefix,params);
2893 else if (command == "SVSNICK")
2897 prefix = this->GetName();
2899 return this->ForceNick(prefix,params);
2901 else if (command == "RSQUIT")
2903 return this->RemoteSquit(prefix, params);
2905 else if (command == "IDLE")
2907 return this->Whois(prefix,params);
2909 else if (command == "PUSH")
2911 return this->Push(prefix,params);
2913 else if (command == "TIMESET")
2915 return this->HandleSetTime(prefix, params);
2917 else if (command == "TIME")
2919 return this->Time(prefix,params);
2921 else if ((command == "KICK") && (Utils->IsServer(prefix)))
2923 std::string sourceserv = this->myhost;
2924 if (params.size() == 3)
2926 userrec* user = this->Instance->FindNick(params[1]);
2927 chanrec* chan = this->Instance->FindChan(params[0]);
2930 if (!chan->ServerKickUser(user, params[2].c_str(), false))
2931 /* Yikes, the channels gone! */
2935 if (this->InboundServerName != "")
2937 sourceserv = this->InboundServerName;
2939 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
2941 else if (command == "SVSJOIN")
2945 prefix = this->GetName();
2947 return this->ServiceJoin(prefix,params);
2949 else if (command == "SQUIT")
2951 if (params.size() == 2)
2953 this->Squit(Utils->FindServer(params[0]),params[1]);
2957 else if (command == "OPERNOTICE")
2959 std::string sourceserv = this->myhost;
2961 if (this->InboundServerName != "")
2962 sourceserv = this->InboundServerName;
2964 if (params.size() >= 1)
2965 Instance->WriteOpers("*** From " + sourceserv + ": " + params[0]);
2967 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
2969 else if (command == "MODENOTICE")
2971 std::string sourceserv = this->myhost;
2972 if (this->InboundServerName != "")
2973 sourceserv = this->InboundServerName;
2974 if (params.size() >= 2)
2976 Instance->WriteMode(params[0].c_str(), WM_AND, "*** From %s: %s", sourceserv.c_str(), params[1].c_str());
2979 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
2981 else if (command == "SNONOTICE")
2983 std::string sourceserv = this->myhost;
2984 if (this->InboundServerName != "")
2985 sourceserv = this->InboundServerName;
2986 if (params.size() >= 2)
2988 Instance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + sourceserv + ": "+ params[1]);
2991 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
2993 else if (command == "ENDBURST")
2995 this->bursting = false;
2996 Instance->XLines->apply_lines(Utils->lines_to_apply);
2997 Utils->lines_to_apply = 0;
2998 std::string sourceserv = this->myhost;
2999 if (this->InboundServerName != "")
3001 sourceserv = this->InboundServerName;
3003 this->Instance->SNO->WriteToSnoMask('l',"Received end of netburst from \2%s\2",sourceserv.c_str());
3005 Event rmode((char*)sourceserv.c_str(), (Module*)Utils->Creator, "new_server");
3006 rmode.Send(Instance);
3012 // not a special inter-server command.
3013 // Emulate the actual user doing the command,
3014 // this saves us having a huge ugly parser.
3015 userrec* who = this->Instance->FindNick(prefix);
3016 std::string sourceserv = this->myhost;
3017 if (this->InboundServerName != "")
3019 sourceserv = this->InboundServerName;
3021 if ((!who) && (command == "MODE"))
3023 if (Utils->IsServer(prefix))
3025 const char* modelist[127];
3026 for (size_t i = 0; i < params.size(); i++)
3027 modelist[i] = params[i].c_str();
3029 userrec* fake = new userrec(Instance);
3030 fake->SetFd(FD_MAGIC_NUMBER);
3032 this->Instance->SendMode(modelist, params.size(), fake);
3036 /* Hot potato! pass it on! */
3037 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3042 if ((command == "NICK") && (params.size() > 0))
3044 /* On nick messages, check that the nick doesnt
3045 * already exist here. If it does, kill their copy,
3048 userrec* x = this->Instance->FindNick(params[0]);
3049 if ((x) && (x != who))
3051 std::deque<std::string> p;
3052 p.push_back(params[0]);
3053 p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
3054 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
3056 p.push_back(prefix);
3057 p.push_back("Nickname collision");
3058 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
3059 userrec::QuitUser(this->Instance,x,"Nickname collision ("+prefix+" -> "+params[0]+")");
3060 userrec* y = this->Instance->FindNick(prefix);
3063 userrec::QuitUser(this->Instance,y,"Nickname collision");
3065 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3069 target = who->server;
3070 const char* strparams[127];
3071 for (unsigned int q = 0; q < params.size(); q++)
3073 strparams[q] = params[q].c_str();
3075 switch (this->Instance->CallCommandHandler(command.c_str(), strparams, params.size(), who))
3078 this->WriteLine("ERROR :Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
3085 /* CMD_SUCCESS and CMD_USER_DELETED fall through here */
3091 // its not a user. Its either a server, or somethings screwed up.
3092 if (Utils->IsServer(prefix))
3093 target = this->Instance->Config->ServerName;
3097 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3106 virtual std::string GetName()
3108 std::string sourceserv = this->myhost;
3109 if (this->InboundServerName != "")
3111 sourceserv = this->InboundServerName;
3116 virtual void OnTimeout()
3118 if (this->LinkState == CONNECTING)
3120 this->Instance->SNO->WriteToSnoMask('l',"CONNECT: Connection to \002"+myhost+"\002 timed out.");
3121 Link* MyLink = Utils->FindLink(myhost);
3123 Utils->DoFailOver(MyLink);
3127 virtual void OnClose()
3129 // Connection closed.
3130 // If the connection is fully up (state CONNECTED)
3131 // then propogate a netsplit to all peers.
3132 std::string quitserver = this->myhost;
3133 if (this->InboundServerName != "")
3135 quitserver = this->InboundServerName;
3137 TreeServer* s = Utils->FindServer(quitserver);
3140 Squit(s,"Remote host closed the connection");
3143 if (quitserver != "")
3144 this->Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' failed.",quitserver.c_str());
3147 virtual int OnIncomingConnection(int newsock, char* ip)
3149 /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
3150 * or discovering if this port is the server port, we don't allow connections from any
3151 * IPs for which we don't have a link block.
3155 found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), ip) != Utils->ValidIPs.end());
3158 for (vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
3159 if (irc::sockets::MatchCIDR(ip, (*i).c_str()))
3164 this->Instance->SNO->WriteToSnoMask('l',"Server connection from %s denied (no link blocks with that IP address)", ip);
3170 TreeSocket* s = new TreeSocket(this->Utils, this->Instance, newsock, ip, this->Hook);
3172 s = s; /* Whinge whinge whinge, thats all GCC ever does. */
3177 /** This class is used to resolve server hostnames during /connect and autoconnect.
3178 * As of 1.1, the resolver system is seperated out from InspSocket, so we must do this
3179 * resolver step first ourselves if we need it. This is totally nonblocking, and will
3180 * callback to OnLookupComplete or OnError when completed. Once it has completed we
3181 * will have an IP address which we can then use to continue our connection.
3183 class ServernameResolver : public Resolver
3186 /** A copy of the Link tag info for what we're connecting to.
3187 * We take a copy, rather than using a pointer, just in case the
3188 * admin takes the tag away and rehashes while the domain is resolving.
3191 SpanningTreeUtilities* Utils;
3193 ServernameResolver(Module* me, SpanningTreeUtilities* Util, InspIRCd* Instance, const std::string &hostname, Link x, bool &cached) : Resolver(Instance, hostname, DNS_QUERY_FORWARD, cached, me), MyLink(x), Utils(Util)
3195 /* Nothing in here, folks */
3198 void OnLookupComplete(const std::string &result, unsigned int ttl, bool cached)
3200 /* Initiate the connection, now that we have an IP to use.
3201 * Passing a hostname directly to InspSocket causes it to
3202 * just bail and set its FD to -1.
3204 TreeServer* CheckDupe = Utils->FindServer(MyLink.Name.c_str());
3205 if (!CheckDupe) /* Check that nobody tried to connect it successfully while we were resolving */
3208 if ((!MyLink.Hook.empty()) && (Utils->hooks.find(MyLink.Hook.c_str()) == Utils->hooks.end()))
3211 TreeSocket* newsocket = new TreeSocket(this->Utils, ServerInstance, result,MyLink.Port,false,MyLink.Timeout ? MyLink.Timeout : 10,MyLink.Name.c_str(),
3212 MyLink.Hook.empty() ? NULL : Utils->hooks[MyLink.Hook.c_str()]);
3213 if (newsocket->GetFd() > -1)
3219 /* Something barfed, show the opers */
3220 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",MyLink.Name.c_str(),strerror(errno));
3222 Utils->DoFailOver(&MyLink);
3227 void OnError(ResolverError e, const std::string &errormessage)
3230 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: Unable to resolve hostname - %s",MyLink.Name.c_str(),errormessage.c_str());
3231 Utils->DoFailOver(&MyLink);
3235 /** Handle resolving of server IPs for the cache
3237 class SecurityIPResolver : public Resolver
3241 SpanningTreeUtilities* Utils;
3243 SecurityIPResolver(Module* me, SpanningTreeUtilities* U, InspIRCd* Instance, const std::string &hostname, Link x, bool &cached) : Resolver(Instance, hostname, DNS_QUERY_FORWARD, cached, me), MyLink(x), Utils(U)
3247 void OnLookupComplete(const std::string &result, unsigned int ttl, bool cached)
3249 Utils->ValidIPs.push_back(result);
3252 void OnError(ResolverError e, const std::string &errormessage)
3254 ServerInstance->Log(DEFAULT,"Could not resolve IP associated with Link '%s': %s",MyLink.Name.c_str(),errormessage.c_str());
3258 SpanningTreeUtilities::SpanningTreeUtilities(InspIRCd* Instance, ModuleSpanningTree* C) : ServerInstance(Instance), Creator(C)
3264 this->TreeRoot = new TreeServer(this, ServerInstance, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc);
3266 modulelist* ml = ServerInstance->FindInterface("InspSocketHook");
3268 /* Did we find any modules? */
3271 /* Yes, enumerate them all to find out the hook name */
3272 for (modulelist::iterator m = ml->begin(); m != ml->end(); m++)
3274 /* Make a request to it for its name, its implementing
3275 * InspSocketHook so we know its safe to do this
3277 std::string name = InspSocketNameRequest((Module*)Creator, *m).Send();
3278 /* Build a map of them */
3279 hooks[name.c_str()] = *m;
3280 hooknames.push_back(name);
3284 this->ReadConfiguration(true);
3287 SpanningTreeUtilities::~SpanningTreeUtilities()
3289 for (unsigned int i = 0; i < Bindings.size(); i++)
3291 ServerInstance->SE->DelFd(Bindings[i]);
3292 Bindings[i]->Close();
3293 DELETE(Bindings[i]);
3295 while (TreeRoot->ChildCount())
3297 TreeServer* child_server = TreeRoot->GetChild(0);
3300 TreeSocket* sock = child_server->GetSocket();
3301 ServerInstance->SE->DelFd(sock);
3309 void SpanningTreeUtilities::AddThisServer(TreeServer* server, TreeServerList &list)
3311 if (list.find(server) == list.end())
3312 list[server] = server;
3315 /** returns a list of DIRECT servernames for a specific channel */
3316 void SpanningTreeUtilities::GetListOfServersForChannel(chanrec* c, TreeServerList &list, char status, const CUList &exempt_list)
3322 ulist = c->GetOppedUsers();
3325 ulist = c->GetHalfoppedUsers();
3328 ulist = c->GetVoicedUsers();
3331 ulist = c->GetUsers();
3334 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
3336 if ((i->second->GetFd() < 0) && (exempt_list.find(i->second) == exempt_list.end()))
3338 TreeServer* best = this->BestRouteTo(i->second->server);
3340 AddThisServer(best,list);
3346 bool SpanningTreeUtilities::DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, std::deque<std::string> ¶ms)
3349 TreeServer* omitroute = this->BestRouteTo(omit);
3350 if ((command == "NOTICE") || (command == "PRIVMSG"))
3352 if (params.size() >= 2)
3355 if ((*(params[0].c_str()) == '@') || (*(params[0].c_str()) == '%') || (*(params[0].c_str()) == '+'))
3358 params[0] = params[0].substr(1, params[0].length()-1);
3360 if ((*(params[0].c_str()) != '#') && (*(params[0].c_str()) != '$'))
3362 // special routing for private messages/notices
3363 userrec* d = ServerInstance->FindNick(params[0]);
3366 std::deque<std::string> par;
3367 par.push_back(params[0]);
3368 par.push_back(":"+params[1]);
3369 this->DoOneToOne(prefix,command.c_str(),par,d->server);
3373 else if (*(params[0].c_str()) == '$')
3375 std::deque<std::string> par;
3376 par.push_back(params[0]);
3377 par.push_back(":"+params[1]);
3378 this->DoOneToAllButSender(prefix,command.c_str(),par,omitroute->GetName());
3383 chanrec* c = ServerInstance->FindChan(params[0]);
3384 userrec* u = ServerInstance->FindNick(prefix);
3388 TreeServerList list;
3389 FOREACH_MOD(I_OnBuildExemptList, OnBuildExemptList((command == "PRIVMSG" ? MSG_PRIVMSG : MSG_NOTICE), c, u, pfx, elist));
3390 GetListOfServersForChannel(c,list,pfx,elist);
3392 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
3394 TreeSocket* Sock = i->second->GetSocket();
3395 if ((Sock) && (i->second->GetName() != omit) && (omitroute != i->second))
3397 Sock->WriteLine(data);
3405 unsigned int items =this->TreeRoot->ChildCount();
3406 for (unsigned int x = 0; x < items; x++)
3408 TreeServer* Route = this->TreeRoot->GetChild(x);
3409 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3411 TreeSocket* Sock = Route->GetSocket();
3413 Sock->WriteLine(data);
3419 bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string omit)
3421 TreeServer* omitroute = this->BestRouteTo(omit);
3422 std::string FullLine = ":" + prefix + " " + command;
3423 unsigned int words = params.size();
3424 for (unsigned int x = 0; x < words; x++)
3426 FullLine = FullLine + " " + params[x];
3428 unsigned int items = this->TreeRoot->ChildCount();
3429 for (unsigned int x = 0; x < items; x++)
3431 TreeServer* Route = this->TreeRoot->GetChild(x);
3432 // Send the line IF:
3433 // The route has a socket (its a direct connection)
3434 // The route isnt the one to be omitted
3435 // The route isnt the path to the one to be omitted
3436 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3438 TreeSocket* Sock = Route->GetSocket();
3440 Sock->WriteLine(FullLine);
3446 bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms)
3448 std::string FullLine = ":" + prefix + " " + command;
3449 unsigned int words = params.size();
3450 for (unsigned int x = 0; x < words; x++)
3452 FullLine = FullLine + " " + params[x];
3454 unsigned int items = this->TreeRoot->ChildCount();
3455 for (unsigned int x = 0; x < items; x++)
3457 TreeServer* Route = this->TreeRoot->GetChild(x);
3458 if (Route && Route->GetSocket())
3460 TreeSocket* Sock = Route->GetSocket();
3462 Sock->WriteLine(FullLine);
3468 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, std::deque<std::string> ¶ms)
3470 std::string spfx = prefix;
3471 std::string scmd = command;
3472 return this->DoOneToMany(spfx, scmd, params);
3475 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, std::deque<std::string> ¶ms, std::string omit)
3477 std::string spfx = prefix;
3478 std::string scmd = command;
3479 return this->DoOneToAllButSender(spfx, scmd, params, omit);
3482 bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, std::deque<std::string> ¶ms, std::string target)
3484 TreeServer* Route = this->BestRouteTo(target);
3487 std::string FullLine = ":" + prefix + " " + command;
3488 unsigned int words = params.size();
3489 for (unsigned int x = 0; x < words; x++)
3491 FullLine = FullLine + " " + params[x];
3493 if (Route && Route->GetSocket())
3495 TreeSocket* Sock = Route->GetSocket();
3497 Sock->WriteLine(FullLine);
3507 void SpanningTreeUtilities::ReadConfiguration(bool rebind)
3509 ConfigReader* Conf = new ConfigReader(ServerInstance);
3512 for (int j =0; j < Conf->Enumerate("bind"); j++)
3514 std::string Type = Conf->ReadValue("bind","type",j);
3515 std::string IP = Conf->ReadValue("bind","address",j);
3516 std::string Port = Conf->ReadValue("bind","port",j);
3517 std::string transport = Conf->ReadValue("bind","transport",j);
3518 if (Type == "servers")
3520 irc::portparser portrange(Port, false);
3522 while ((portno = portrange.GetToken()))
3527 if ((!transport.empty()) && (hooks.find(transport.c_str()) == hooks.end()))
3529 ServerInstance->Log(DEFAULT,"m_spanningtree: WARNING: Can't find transport type '%s' for port %s:%s - maybe you forgot to load it BEFORE m_spanningtree in your config file? - Skipping this port binding",
3530 transport.c_str(), IP.c_str(), Port.c_str());
3534 TreeSocket* listener = new TreeSocket(this, ServerInstance, IP.c_str(), portno, true, 10, transport.empty() ? NULL : hooks[transport.c_str()]);
3535 if (listener->GetState() == I_LISTENING)
3537 ServerInstance->Log(DEFAULT,"m_spanningtree: Binding server port %s:%d successful!", IP.c_str(), portno);
3538 Bindings.push_back(listener);
3542 ServerInstance->Log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %s:%d",IP.c_str(), portno);
3550 FlatLinks = Conf->ReadFlag("options","flatlinks",0);
3551 HideULines = Conf->ReadFlag("options","hideulines",0);
3552 AnnounceTSChange = Conf->ReadFlag("options","announcets",0);
3553 EnableTimeSync = !(Conf->ReadFlag("options","notimesync",0));
3556 for (int j =0; j < Conf->Enumerate("link"); j++)
3559 std::string Allow = Conf->ReadValue("link","allowmask",j);
3560 L.Name = (Conf->ReadValue("link","name",j)).c_str();
3561 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
3562 L.FailOver = Conf->ReadValue("link","failover",j).c_str();
3563 L.Port = Conf->ReadInteger("link","port",j,true);
3564 L.SendPass = Conf->ReadValue("link","sendpass",j);
3565 L.RecvPass = Conf->ReadValue("link","recvpass",j);
3566 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
3567 L.HiddenFromStats = Conf->ReadFlag("link","hidden",j);
3568 L.Timeout = Conf->ReadInteger("link","timeout",j,true);
3569 L.Hook = Conf->ReadValue("link", "transport", j);
3571 if ((!L.Hook.empty()) && (hooks.find(L.Hook.c_str()) == hooks.end()))
3573 ServerInstance->Log(DEFAULT,"m_spanningtree: WARNING: Can't find transport type '%s' for link '%s' - maybe you forgot to load it BEFORE m_spanningtree in your config file? Skipping <link> tag completely.",
3574 L.Hook.c_str(), L.Name.c_str());
3579 L.NextConnectTime = time(NULL) + L.AutoConnect;
3580 /* Bugfix by brain, do not allow people to enter bad configurations */
3581 if (L.Name != ServerInstance->Config->ServerName)
3583 if ((L.IPAddr != "") && (L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
3585 ValidIPs.push_back(L.IPAddr);
3588 ValidIPs.push_back(Allow);
3590 /* Needs resolving */
3592 if (insp_aton(L.IPAddr.c_str(), &binip) < 1)
3597 SecurityIPResolver* sr = new SecurityIPResolver((Module*)this->Creator, this, ServerInstance, L.IPAddr, L, cached);
3598 ServerInstance->AddResolver(sr, cached);
3600 catch (ModuleException& e)
3605 LinkBlocks.push_back(L);
3611 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', IP address not defined!",L.Name.c_str());
3613 else if (L.RecvPass == "")
3615 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', recvpass not defined!",L.Name.c_str());
3617 else if (L.SendPass == "")
3619 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', sendpass not defined!",L.Name.c_str());
3621 else if (L.Name == "")
3623 ServerInstance->Log(DEFAULT,"Invalid configuration, link tag without a name!");
3627 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', no port specified!",L.Name.c_str());
3633 ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', link tag has the same server name as the local server!",L.Name.c_str());
3639 /** To create a timer which recurs every second, we inherit from InspTimer.
3640 * InspTimer is only one-shot however, so at the end of each Tick() we simply
3641 * insert another of ourselves into the pending queue :)
3643 class TimeSyncTimer : public InspTimer
3647 ModuleSpanningTree *Module;
3649 TimeSyncTimer(InspIRCd *Instance, ModuleSpanningTree *Mod);
3650 virtual void Tick(time_t TIME);
3653 HandshakeTimer::HandshakeTimer(InspIRCd* Inst, TreeSocket* s, Link* l, SpanningTreeUtilities* u) : InspTimer(1, time(NULL)), Instance(Inst), sock(s), lnk(l), Utils(u)
3655 thefd = sock->GetFd();
3658 void HandshakeTimer::Tick(time_t TIME)
3660 if (Instance->SE->GetRef(thefd) == sock)
3662 if (sock->GetHook() && InspSocketHSCompleteRequest(sock, (Module*)Utils->Creator, sock->GetHook()).Send())
3664 InspSocketAttachCertRequest(sock, (Module*)Utils->Creator, sock->GetHook()).Send();
3665 sock->SendCapabilities();
3666 if (sock->GetLinkState() == CONNECTING)
3668 sock->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+lnk->SendPass+" 0 :"+this->Instance->Config->ServerDesc);
3673 Instance->Timers->AddTimer(new HandshakeTimer(Instance, sock, lnk, Utils));
3678 class ModuleSpanningTree : public Module
3682 unsigned int max_local;
3683 unsigned int max_global;
3684 cmd_rconnect* command_rconnect;
3685 SpanningTreeUtilities* Utils;
3688 TimeSyncTimer *SyncTimer;
3690 ModuleSpanningTree(InspIRCd* Me)
3691 : Module::Module(Me), max_local(0), max_global(0)
3693 ServerInstance->UseInterface("InspSocketHook");
3695 Utils = new SpanningTreeUtilities(Me, this);
3697 command_rconnect = new cmd_rconnect(ServerInstance, this, Utils);
3698 ServerInstance->AddCommand(command_rconnect);
3700 if (Utils->EnableTimeSync)
3702 SyncTimer = new TimeSyncTimer(ServerInstance, this);
3703 ServerInstance->Timers->AddTimer(SyncTimer);
3709 void ShowLinks(TreeServer* Current, userrec* user, int hops)
3711 std::string Parent = Utils->TreeRoot->GetName();
3712 if (Current->GetParent())
3714 Parent = Current->GetParent()->GetName();
3716 for (unsigned int q = 0; q < Current->ChildCount(); q++)
3718 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str())))
3722 ShowLinks(Current->GetChild(q),user,hops+1);
3727 ShowLinks(Current->GetChild(q),user,hops+1);
3730 /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
3731 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetName().c_str())) && (!*user->oper))
3733 user->WriteServ("364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),(Utils->FlatLinks && (!*user->oper)) ? ServerInstance->Config->ServerName : Parent.c_str(),(Utils->FlatLinks && (!*user->oper)) ? 0 : hops,Current->GetDesc().c_str());
3736 int CountLocalServs()
3738 return Utils->TreeRoot->ChildCount();
3743 return Utils->serverlist.size();
3746 void HandleLinks(const char** parameters, int pcnt, userrec* user)
3748 ShowLinks(Utils->TreeRoot,user,0);
3749 user->WriteServ("365 %s * :End of /LINKS list.",user->nick);
3753 void HandleLusers(const char** parameters, int pcnt, userrec* user)
3755 unsigned int n_users = ServerInstance->UserCount();
3757 /* Only update these when someone wants to see them, more efficient */
3758 if ((unsigned int)ServerInstance->LocalUserCount() > max_local)
3759 max_local = ServerInstance->LocalUserCount();
3760 if (n_users > max_global)
3761 max_global = n_users;
3763 unsigned int ulined_count = 0;
3764 unsigned int ulined_local_count = 0;
3766 /* If ulined are hidden and we're not an oper, count the number of ulined servers hidden,
3767 * locally and globally (locally means directly connected to us)
3769 if ((Utils->HideULines) && (!*user->oper))
3771 for (server_hash::iterator q = Utils->serverlist.begin(); q != Utils->serverlist.end(); q++)
3773 if (ServerInstance->ULine(q->second->GetName().c_str()))
3776 if (q->second->GetParent() == Utils->TreeRoot)
3777 ulined_local_count++;
3782 user->WriteServ("251 %s :There are %d users and %d invisible on %d servers",user->nick,n_users-ServerInstance->InvisibleUserCount(),ServerInstance->InvisibleUserCount(),ulined_count ? this->CountServs() - ulined_count : this->CountServs());
3783 if (ServerInstance->OperCount())
3784 user->WriteServ("252 %s %d :operator(s) online",user->nick,ServerInstance->OperCount());
3785 if (ServerInstance->UnregisteredUserCount())
3786 user->WriteServ("253 %s %d :unknown connections",user->nick,ServerInstance->UnregisteredUserCount());
3787 if (ServerInstance->ChannelCount())
3788 user->WriteServ("254 %s %d :channels formed",user->nick,ServerInstance->ChannelCount());
3789 user->WriteServ("254 %s :I have %d clients and %d servers",user->nick,ServerInstance->LocalUserCount(),ulined_local_count ? this->CountLocalServs() - ulined_local_count : this->CountLocalServs());
3790 user->WriteServ("265 %s :Current Local Users: %d Max: %d",user->nick,ServerInstance->LocalUserCount(),max_local);
3791 user->WriteServ("266 %s :Current Global Users: %d Max: %d",user->nick,n_users,max_global);
3795 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
3797 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80], float &totusers, float &totservers)
3801 for (int t = 0; t < depth; t++)
3803 matrix[line][t] = ' ';
3806 // For Aligning, we need to work out exactly how deep this thing is, and produce
3807 // a 'Spacer' String to compensate.
3810 memset(spacer,' ',40);
3811 if ((40 - Current->GetName().length() - depth) > 1) {
3812 spacer[40 - Current->GetName().length() - depth] = '\0';
3821 if (ServerInstance->clientlist->size() == 0) {
3822 // If there are no users, WHO THE HELL DID THE /MAP?!?!?!
3827 percent = ((float)Current->GetUserCount() / (float)ServerInstance->clientlist->size()) * 100;
3829 snprintf(text, 80, "%s %s%5d [%5.2f%%]", Current->GetName().c_str(), spacer, Current->GetUserCount(), percent);
3830 totusers += Current->GetUserCount();
3832 strlcpy(&matrix[line][depth],text,80);
3834 for (unsigned int q = 0; q < Current->ChildCount(); q++)
3836 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str())))
3840 ShowMap(Current->GetChild(q),user,(Utils->FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
3845 ShowMap(Current->GetChild(q),user,(Utils->FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
3851 int HandleMotd(const char** parameters, int pcnt, userrec* user)
3855 /* Remote MOTD, the server is within the 1st parameter */
3856 std::deque<std::string> params;
3857 params.push_back(parameters[0]);
3859 /* Send it out remotely, generate no reply yet */
3860 TreeServer* s = Utils->FindServerMask(parameters[0]);
3863 Utils->DoOneToOne(user->nick, "MOTD", params, s->GetName());
3867 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
3874 int HandleAdmin(const char** parameters, int pcnt, userrec* user)
3878 /* Remote ADMIN, the server is within the 1st parameter */
3879 std::deque<std::string> params;
3880 params.push_back(parameters[0]);
3882 /* Send it out remotely, generate no reply yet */
3883 TreeServer* s = Utils->FindServerMask(parameters[0]);
3886 Utils->DoOneToOne(user->nick, "ADMIN", params, s->GetName());
3890 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
3897 int HandleStats(const char** parameters, int pcnt, userrec* user)
3901 /* Remote STATS, the server is within the 2nd parameter */
3902 std::deque<std::string> params;
3903 params.push_back(parameters[0]);
3904 params.push_back(parameters[1]);
3905 /* Send it out remotely, generate no reply yet */
3906 TreeServer* s = Utils->FindServerMask(parameters[1]);
3909 params[1] = s->GetName();
3910 Utils->DoOneToOne(user->nick, "STATS", params, s->GetName());
3914 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
3921 // Ok, prepare to be confused.
3922 // After much mulling over how to approach this, it struck me that
3923 // the 'usual' way of doing a /MAP isnt the best way. Instead of
3924 // keeping track of a ton of ascii characters, and line by line
3925 // under recursion working out where to place them using multiplications
3926 // and divisons, we instead render the map onto a backplane of characters
3927 // (a character matrix), then draw the branches as a series of "L" shapes
3928 // from the nodes. This is not only friendlier on CPU it uses less stack.
3930 void HandleMap(const char** parameters, int pcnt, userrec* user)
3932 // This array represents a virtual screen which we will
3933 // "scratch" draw to, as the console device of an irc
3934 // client does not provide for a proper terminal.
3936 float totservers = 0;
3937 char matrix[128][80];
3938 for (unsigned int t = 0; t < 128; t++)
3940 matrix[t][0] = '\0';
3943 // The only recursive bit is called here.
3944 ShowMap(Utils->TreeRoot,user,0,matrix,totusers,totservers);
3945 // Process each line one by one. The algorithm has a limit of
3946 // 128 servers (which is far more than a spanning tree should have
3947 // anyway, so we're ok). This limit can be raised simply by making
3948 // the character matrix deeper, 128 rows taking 10k of memory.
3949 for (int l = 1; l < line; l++)
3951 // scan across the line looking for the start of the
3952 // servername (the recursive part of the algorithm has placed
3953 // the servers at indented positions depending on what they
3955 int first_nonspace = 0;
3956 while (matrix[l][first_nonspace] == ' ')
3961 // Draw the `- (corner) section: this may be overwritten by
3962 // another L shape passing along the same vertical pane, becoming
3963 // a |- (branch) section instead.
3964 matrix[l][first_nonspace] = '-';
3965 matrix[l][first_nonspace-1] = '`';
3967 // Draw upwards until we hit the parent server, causing possibly
3968 // other corners (`-) to become branches (|-)
3969 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
3971 matrix[l2][first_nonspace-1] = '|';
3975 // dump the whole lot to the user. This is the easy bit, honest.
3976 for (int t = 0; t < line; t++)
3978 user->WriteServ("006 %s :%s",user->nick,&matrix[t][0]);
3980 float avg_users = totusers / totservers;
3981 user->WriteServ("270 %s :%.0f server%s and %.0f user%s, average %.2f users per server",user->nick,totservers,(totservers > 1 ? "s" : ""),totusers,(totusers > 1 ? "s" : ""),avg_users);
3982 user->WriteServ("007 %s :End of /MAP",user->nick);
3986 int HandleSquit(const char** parameters, int pcnt, userrec* user)
3988 TreeServer* s = Utils->FindServerMask(parameters[0]);
3991 if (s == Utils->TreeRoot)
3993 user->WriteServ("NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
3996 TreeSocket* sock = s->GetSocket();
3999 ServerInstance->SNO->WriteToSnoMask('l',"SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
4000 sock->Squit(s,std::string("Server quit by ") + user->GetFullRealHost());
4001 ServerInstance->SE->DelFd(sock);
4008 std::deque<std::string> params;
4009 params.push_back(parameters[0]);
4010 params.push_back(std::string(":Server quit by ") + user->GetFullRealHost());
4011 Utils->DoOneToOne(user->nick, "RSQUIT", params, parameters[0]);
4016 user->WriteServ("NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
4021 int HandleTime(const char** parameters, int pcnt, userrec* user)
4023 if ((IS_LOCAL(user)) && (pcnt))
4025 TreeServer* found = Utils->FindServerMask(parameters[0]);
4028 // we dont' override for local server
4029 if (found == Utils->TreeRoot)
4032 std::deque<std::string> params;
4033 params.push_back(found->GetName());
4034 params.push_back(user->nick);
4035 Utils->DoOneToOne(ServerInstance->Config->ServerName,"TIME",params,found->GetName());
4039 user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
4045 int HandleRemoteWhois(const char** parameters, int pcnt, userrec* user)
4047 if ((IS_LOCAL(user)) && (pcnt > 1))
4049 userrec* remote = ServerInstance->FindNick(parameters[1]);
4050 if ((remote) && (remote->GetFd() < 0))
4052 std::deque<std::string> params;
4053 params.push_back(parameters[1]);
4054 Utils->DoOneToOne(user->nick,"IDLE",params,remote->server);
4059 user->WriteServ("401 %s %s :No such nick/channel",user->nick, parameters[1]);
4060 user->WriteServ("318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
4067 void DoPingChecks(time_t curtime)
4069 for (unsigned int j = 0; j < Utils->TreeRoot->ChildCount(); j++)
4071 TreeServer* serv = Utils->TreeRoot->GetChild(j);
4072 TreeSocket* sock = serv->GetSocket();
4075 if (curtime >= serv->NextPingTime())
4077 if (serv->AnsweredLastPing())
4079 sock->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" PING "+serv->GetName());
4080 serv->SetNextPingTime(curtime + 60);
4084 // they didnt answer, boot them
4085 ServerInstance->SNO->WriteToSnoMask('l',"Server \002%s\002 pinged out",serv->GetName().c_str());
4086 sock->Squit(serv,"Ping timeout");
4087 ServerInstance->SE->DelFd(sock);
4097 void ConnectServer(Link* x)
4101 /* Do we already have an IP? If so, no need to resolve it. */
4102 if (insp_aton(x->IPAddr.c_str(), &binip) > 0)
4104 /* Gave a hook, but it wasnt one we know */
4105 if ((!x->Hook.empty()) && (Utils->hooks.find(x->Hook.c_str()) == Utils->hooks.end()))
4108 TreeSocket* newsocket = new TreeSocket(Utils, ServerInstance, x->IPAddr,x->Port,false,x->Timeout ? x->Timeout : 10,x->Name.c_str(), x->Hook.empty() ? NULL : Utils->hooks[x->Hook.c_str()]);
4109 if (newsocket->GetFd() > -1)
4111 /* Handled automatically on success */
4115 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
4117 Utils->DoFailOver(x);
4125 ServernameResolver* snr = new ServernameResolver((Module*)this, Utils, ServerInstance,x->IPAddr, *x, cached);
4126 ServerInstance->AddResolver(snr, cached);
4128 catch (ModuleException& e)
4130 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(), e.GetReason());
4131 Utils->DoFailOver(x);
4136 void AutoConnectServers(time_t curtime)
4138 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
4140 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
4142 x->NextConnectTime = curtime + x->AutoConnect;
4143 TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
4144 if (x->FailOver.length())
4146 TreeServer* CheckFailOver = Utils->FindServer(x->FailOver.c_str());
4149 /* The failover for this server is currently a member of the network.
4150 * The failover probably succeeded, where the main link did not.
4151 * Don't try the main link until the failover is gone again.
4158 // an autoconnected server is not connected. Check if its time to connect it
4159 ServerInstance->SNO->WriteToSnoMask('l',"AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
4160 this->ConnectServer(&(*x));
4166 int HandleVersion(const char** parameters, int pcnt, userrec* user)
4168 // we've already checked if pcnt > 0, so this is safe
4169 TreeServer* found = Utils->FindServerMask(parameters[0]);
4172 std::string Version = found->GetVersion();
4173 user->WriteServ("351 %s :%s",user->nick,Version.c_str());
4174 if (found == Utils->TreeRoot)
4176 ServerInstance->Config->Send005(user);
4181 user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
4186 int HandleConnect(const char** parameters, int pcnt, userrec* user)
4188 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
4190 if (ServerInstance->MatchText(x->Name.c_str(),parameters[0]))
4192 TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
4195 user->WriteServ("NOTICE %s :*** CONNECT: Connecting to server: \002%s\002 (%s:%d)",user->nick,x->Name.c_str(),(x->HiddenFromStats ? "<hidden>" : x->IPAddr.c_str()),x->Port);
4196 ConnectServer(&(*x));
4201 user->WriteServ("NOTICE %s :*** CONNECT: Server \002%s\002 already exists on the network and is connected via \002%s\002",user->nick,x->Name.c_str(),CheckDupe->GetParent()->GetName().c_str());
4206 user->WriteServ("NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
4210 void BroadcastTimeSync()
4212 std::deque<std::string> params;
4213 params.push_back(ConvToStr(ServerInstance->Time(true)));
4214 Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
4217 virtual int OnStats(char statschar, userrec* user, string_list &results)
4219 if ((statschar == 'c') || (statschar == 'n'))
4221 for (unsigned int i = 0; i < Utils->LinkBlocks.size(); i++)
4223 results.push_back(std::string(ServerInstance->Config->ServerName)+" 213 "+user->nick+" "+statschar+" *@"+(Utils->LinkBlocks[i].HiddenFromStats ? "<hidden>" : Utils->LinkBlocks[i].IPAddr)+" * "+Utils->LinkBlocks[i].Name.c_str()+" "+ConvToStr(Utils->LinkBlocks[i].Port)+" "+(Utils->LinkBlocks[i].Hook.empty() ? "plaintext" : Utils->LinkBlocks[i].Hook)+" "+(Utils->LinkBlocks[i].AutoConnect ? 'a' : '-')+'s');
4224 if (statschar == 'c')
4225 results.push_back(std::string(ServerInstance->Config->ServerName)+" 244 "+user->nick+" H * * "+Utils->LinkBlocks[i].Name.c_str());
4227 results.push_back(std::string(ServerInstance->Config->ServerName)+" 219 "+user->nick+" "+statschar+" :End of /STATS report");
4228 ServerInstance->SNO->WriteToSnoMask('t',"Notice: %s '%c' requested by %s (%s@%s)",(!strcmp(user->server,ServerInstance->Config->ServerName) ? "Stats" : "Remote stats"),statschar,user->nick,user->ident,user->host);
4234 virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated, const std::string &original_line)
4236 /* If the command doesnt appear to be valid, we dont want to mess with it. */
4240 if (command == "CONNECT")
4242 return this->HandleConnect(parameters,pcnt,user);
4244 else if (command == "STATS")
4246 return this->HandleStats(parameters,pcnt,user);
4248 else if (command == "MOTD")
4250 return this->HandleMotd(parameters,pcnt,user);
4252 else if (command == "ADMIN")
4254 return this->HandleAdmin(parameters,pcnt,user);
4256 else if (command == "SQUIT")
4258 return this->HandleSquit(parameters,pcnt,user);
4260 else if (command == "MAP")
4262 this->HandleMap(parameters,pcnt,user);
4265 else if ((command == "TIME") && (pcnt > 0))
4267 return this->HandleTime(parameters,pcnt,user);
4269 else if (command == "LUSERS")
4271 this->HandleLusers(parameters,pcnt,user);
4274 else if (command == "LINKS")
4276 this->HandleLinks(parameters,pcnt,user);
4279 else if (command == "WHOIS")
4284 return this->HandleRemoteWhois(parameters,pcnt,user);
4287 else if ((command == "VERSION") && (pcnt > 0))
4289 this->HandleVersion(parameters,pcnt,user);
4296 virtual void OnPostCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, CmdResult result, const std::string &original_line)
4298 if ((result == CMD_SUCCESS) && (ServerInstance->IsValidModuleCommand(command, pcnt, user)))
4300 // this bit of code cleverly routes all module commands
4301 // to all remote severs *automatically* so that modules
4302 // can just handle commands locally, without having
4303 // to have any special provision in place for remote
4304 // commands and linking protocols.
4305 std::deque<std::string> params;
4307 for (int j = 0; j < pcnt; j++)
4309 if (strchr(parameters[j],' '))
4311 params.push_back(":" + std::string(parameters[j]));
4315 params.push_back(std::string(parameters[j]));
4318 Utils->DoOneToMany(user->nick,command,params);
4322 virtual void OnGetServerDescription(const std::string &servername,std::string &description)
4324 TreeServer* s = Utils->FindServer(servername);
4327 description = s->GetDesc();
4331 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
4333 if (IS_LOCAL(source))
4335 std::deque<std::string> params;
4336 params.push_back(dest->nick);
4337 params.push_back(channel->name);
4338 Utils->DoOneToMany(source->nick,"INVITE",params);
4342 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, const std::string &topic)
4344 std::deque<std::string> params;
4345 params.push_back(chan->name);
4346 params.push_back(":"+topic);
4347 Utils->DoOneToMany(user->nick,"TOPIC",params);
4350 virtual void OnWallops(userrec* user, const std::string &text)
4354 std::deque<std::string> params;
4355 params.push_back(":"+text);
4356 Utils->DoOneToMany(user->nick,"WALLOPS",params);
4360 virtual void OnUserNotice(userrec* user, void* dest, int target_type, const std::string &text, char status, const CUList &exempt_list)
4362 if (target_type == TYPE_USER)
4364 userrec* d = (userrec*)dest;
4365 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
4367 std::deque<std::string> params;
4369 params.push_back(d->nick);
4370 params.push_back(":"+text);
4371 Utils->DoOneToOne(user->nick,"NOTICE",params,d->server);
4374 else if (target_type == TYPE_CHANNEL)
4378 chanrec *c = (chanrec*)dest;
4381 std::string cname = c->name;
4383 cname = status + cname;
4384 TreeServerList list;
4385 Utils->GetListOfServersForChannel(c,list,status,exempt_list);
4387 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
4389 TreeSocket* Sock = i->second->GetSocket();
4391 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+cname+" :"+text);
4396 else if (target_type == TYPE_SERVER)
4400 char* target = (char*)dest;
4401 std::deque<std::string> par;
4402 par.push_back(target);
4403 par.push_back(":"+text);
4404 Utils->DoOneToMany(user->nick,"NOTICE",par);
4409 virtual void OnUserMessage(userrec* user, void* dest, int target_type, const std::string &text, char status, const CUList &exempt_list)
4411 if (target_type == TYPE_USER)
4413 // route private messages which are targetted at clients only to the server
4414 // which needs to receive them
4415 userrec* d = (userrec*)dest;
4416 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
4418 std::deque<std::string> params;
4420 params.push_back(d->nick);
4421 params.push_back(":"+text);
4422 Utils->DoOneToOne(user->nick,"PRIVMSG",params,d->server);
4425 else if (target_type == TYPE_CHANNEL)
4429 chanrec *c = (chanrec*)dest;
4432 std::string cname = c->name;
4434 cname = status + cname;
4435 TreeServerList list;
4436 Utils->GetListOfServersForChannel(c,list,status,exempt_list);
4438 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
4440 TreeSocket* Sock = i->second->GetSocket();
4442 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+cname+" :"+text);
4447 else if (target_type == TYPE_SERVER)
4451 char* target = (char*)dest;
4452 std::deque<std::string> par;
4453 par.push_back(target);
4454 par.push_back(":"+text);
4455 Utils->DoOneToMany(user->nick,"PRIVMSG",par);
4460 virtual void OnBackgroundTimer(time_t curtime)
4462 AutoConnectServers(curtime);
4463 DoPingChecks(curtime);
4466 virtual void OnUserJoin(userrec* user, chanrec* channel)
4468 // Only do this for local users
4471 if (channel->GetUserCounter() == 1)
4473 std::deque<std::string> params;
4474 // set up their permissions and the channel TS with FJOIN.
4475 // All users are FJOINed now, because a module may specify
4476 // new joining permissions for the user.
4477 params.push_back(channel->name);
4478 params.push_back(ConvToStr(channel->age));
4479 params.push_back(std::string(channel->GetAllPrefixChars(user))+","+std::string(user->nick));
4480 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FJOIN",params);
4481 /* First user in, sync the modes for the channel */
4483 /* This is safe, all inspircd servers default to +nt */
4484 params.push_back("+nt");
4485 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FMODE",params);
4489 std::deque<std::string> params;
4490 params.push_back(channel->name);
4491 params.push_back(ConvToStr(channel->age));
4492 Utils->DoOneToMany(user->nick,"JOIN",params);
4497 virtual void OnChangeHost(userrec* user, const std::string &newhost)
4499 // only occurs for local clients
4500 if (user->registered != REG_ALL)
4502 std::deque<std::string> params;
4503 params.push_back(newhost);
4504 Utils->DoOneToMany(user->nick,"FHOST",params);
4507 virtual void OnChangeName(userrec* user, const std::string &gecos)
4509 // only occurs for local clients
4510 if (user->registered != REG_ALL)
4512 std::deque<std::string> params;
4513 params.push_back(gecos);
4514 Utils->DoOneToMany(user->nick,"FNAME",params);
4517 virtual void OnUserPart(userrec* user, chanrec* channel, const std::string &partmessage)
4521 std::deque<std::string> params;
4522 params.push_back(channel->name);
4523 if (partmessage != "")
4524 params.push_back(":"+partmessage);
4525 Utils->DoOneToMany(user->nick,"PART",params);
4529 virtual void OnUserConnect(userrec* user)
4531 char agestr[MAXBUF];
4534 std::deque<std::string> params;
4535 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
4536 params.push_back(agestr);
4537 params.push_back(user->nick);
4538 params.push_back(user->host);
4539 params.push_back(user->dhost);
4540 params.push_back(user->ident);
4541 params.push_back("+"+std::string(user->FormatModes()));
4542 params.push_back(user->GetIPString());
4543 params.push_back(":"+std::string(user->fullname));
4544 Utils->DoOneToMany(ServerInstance->Config->ServerName,"NICK",params);
4546 // User is Local, change needs to be reflected!
4547 TreeServer* SourceServer = Utils->FindServer(user->server);
4550 SourceServer->AddUserCount();
4556 virtual void OnUserQuit(userrec* user, const std::string &reason)
4558 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
4560 std::deque<std::string> params;
4561 params.push_back(":"+reason);
4562 Utils->DoOneToMany(user->nick,"QUIT",params);
4564 // Regardless, We need to modify the user Counts..
4565 TreeServer* SourceServer = Utils->FindServer(user->server);
4568 SourceServer->DelUserCount();
4573 virtual void OnUserPostNick(userrec* user, const std::string &oldnick)
4577 std::deque<std::string> params;
4578 params.push_back(user->nick);
4579 Utils->DoOneToMany(oldnick,"NICK",params);
4583 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, const std::string &reason)
4585 if ((source) && (IS_LOCAL(source)))
4587 std::deque<std::string> params;
4588 params.push_back(chan->name);
4589 params.push_back(user->nick);
4590 params.push_back(":"+reason);
4591 Utils->DoOneToMany(source->nick,"KICK",params);
4595 std::deque<std::string> params;
4596 params.push_back(chan->name);
4597 params.push_back(user->nick);
4598 params.push_back(":"+reason);
4599 Utils->DoOneToMany(ServerInstance->Config->ServerName,"KICK",params);
4603 virtual void OnRemoteKill(userrec* source, userrec* dest, const std::string &reason)
4605 std::deque<std::string> params;
4606 params.push_back(dest->nick);
4607 params.push_back(":"+reason);
4608 Utils->DoOneToMany(source->nick,"KILL",params);
4611 virtual void OnRehash(userrec* user, const std::string ¶meter)
4613 if (parameter != "")
4615 std::deque<std::string> params;
4616 params.push_back(parameter);
4617 Utils->DoOneToMany(user ? user->nick : ServerInstance->Config->ServerName, "REHASH", params);
4619 if (ServerInstance->MatchText(ServerInstance->Config->ServerName,parameter))
4621 ServerInstance->WriteOpers("*** Remote rehash initiated locally by \002%s\002", user ? user->nick : ServerInstance->Config->ServerName);
4622 ServerInstance->RehashServer();
4625 Utils->ReadConfiguration(false);
4626 InitializeDisabledCommands(ServerInstance->Config->DisabledCommands, ServerInstance);
4629 // note: the protocol does not allow direct umode +o except
4630 // via NICK with 8 params. sending OPERTYPE infers +o modechange
4632 virtual void OnOper(userrec* user, const std::string &opertype)
4636 std::deque<std::string> params;
4637 params.push_back(opertype);
4638 Utils->DoOneToMany(user->nick,"OPERTYPE",params);
4642 void OnLine(userrec* source, const std::string &host, bool adding, char linetype, long duration, const std::string &reason)
4646 /* Server-set lines */
4648 snprintf(data,MAXBUF,"%c %s %s %lu %lu :%s", linetype, host.c_str(), ServerInstance->Config->ServerName, (unsigned long)ServerInstance->Time(false),
4649 (unsigned long)duration, reason.c_str());
4650 std::deque<std::string> params;
4651 params.push_back(data);
4652 Utils->DoOneToMany(ServerInstance->Config->ServerName, "ADDLINE", params);
4656 if (IS_LOCAL(source))
4659 snprintf(type,8,"%cLINE",linetype);
4660 std::string stype = type;
4663 char sduration[MAXBUF];
4664 snprintf(sduration,MAXBUF,"%ld",duration);
4665 std::deque<std::string> params;
4666 params.push_back(host);
4667 params.push_back(sduration);
4668 params.push_back(":"+reason);
4669 Utils->DoOneToMany(source->nick,stype,params);
4673 std::deque<std::string> params;
4674 params.push_back(host);
4675 Utils->DoOneToMany(source->nick,stype,params);
4681 virtual void OnAddGLine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
4683 OnLine(source,hostmask,true,'G',duration,reason);
4686 virtual void OnAddZLine(long duration, userrec* source, const std::string &reason, const std::string &ipmask)
4688 OnLine(source,ipmask,true,'Z',duration,reason);
4691 virtual void OnAddQLine(long duration, userrec* source, const std::string &reason, const std::string &nickmask)
4693 OnLine(source,nickmask,true,'Q',duration,reason);
4696 virtual void OnAddELine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
4698 OnLine(source,hostmask,true,'E',duration,reason);
4701 virtual void OnDelGLine(userrec* source, const std::string &hostmask)
4703 OnLine(source,hostmask,false,'G',0,"");
4706 virtual void OnDelZLine(userrec* source, const std::string &ipmask)
4708 OnLine(source,ipmask,false,'Z',0,"");
4711 virtual void OnDelQLine(userrec* source, const std::string &nickmask)
4713 OnLine(source,nickmask,false,'Q',0,"");
4716 virtual void OnDelELine(userrec* source, const std::string &hostmask)
4718 OnLine(source,hostmask,false,'E',0,"");
4721 virtual void OnMode(userrec* user, void* dest, int target_type, const std::string &text)
4723 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
4725 if (target_type == TYPE_USER)
4727 userrec* u = (userrec*)dest;
4728 std::deque<std::string> params;
4729 params.push_back(u->nick);
4730 params.push_back(text);
4731 Utils->DoOneToMany(user->nick,"MODE",params);
4735 chanrec* c = (chanrec*)dest;
4736 std::deque<std::string> params;
4737 params.push_back(c->name);
4738 params.push_back(text);
4739 Utils->DoOneToMany(user->nick,"MODE",params);
4744 virtual void OnSetAway(userrec* user)
4748 std::deque<std::string> params;
4749 params.push_back(":"+std::string(user->awaymsg));
4750 Utils->DoOneToMany(user->nick,"AWAY",params);
4754 virtual void OnCancelAway(userrec* user)
4758 std::deque<std::string> params;
4760 Utils->DoOneToMany(user->nick,"AWAY",params);
4764 virtual void ProtoSendMode(void* opaque, int target_type, void* target, const std::string &modeline)
4766 TreeSocket* s = (TreeSocket*)opaque;
4769 if (target_type == TYPE_USER)
4771 userrec* u = (userrec*)target;
4772 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" FMODE "+u->nick+" "+ConvToStr(u->age)+" "+modeline);
4776 chanrec* c = (chanrec*)target;
4777 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age)+" "+modeline);
4782 virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, const std::string &extname, const std::string &extdata)
4784 TreeSocket* s = (TreeSocket*)opaque;
4787 if (target_type == TYPE_USER)
4789 userrec* u = (userrec*)target;
4790 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+u->nick+" "+extname+" :"+extdata);
4792 else if (target_type == TYPE_CHANNEL)
4794 chanrec* c = (chanrec*)target;
4795 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+c->name+" "+extname+" :"+extdata);
4798 if (target_type == TYPE_OTHER)
4800 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA * "+extname+" :"+extdata);
4804 virtual void OnEvent(Event* event)
4806 std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
4808 if (event->GetEventID() == "send_metadata")
4810 if (params->size() < 3)
4812 (*params)[2] = ":" + (*params)[2];
4813 Utils->DoOneToMany(ServerInstance->Config->ServerName,"METADATA",*params);
4815 else if (event->GetEventID() == "send_topic")
4817 if (params->size() < 2)
4819 (*params)[1] = ":" + (*params)[1];
4820 params->insert(params->begin() + 1,ServerInstance->Config->ServerName);
4821 params->insert(params->begin() + 1,ConvToStr(ServerInstance->Time(true)));
4822 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FTOPIC",*params);
4824 else if (event->GetEventID() == "send_mode")
4826 if (params->size() < 2)
4828 // Insert the TS value of the object, either userrec or chanrec
4830 userrec* a = ServerInstance->FindNick((*params)[0]);
4837 chanrec* a = ServerInstance->FindChan((*params)[0]);
4843 params->insert(params->begin() + 1,ConvToStr(ourTS));
4844 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FMODE",*params);
4846 else if (event->GetEventID() == "send_mode_explicit")
4848 if (params->size() < 2)
4850 Utils->DoOneToMany(ServerInstance->Config->ServerName,"MODE",*params);
4852 else if (event->GetEventID() == "send_opers")
4854 if (params->size() < 1)
4856 (*params)[0] = ":" + (*params)[0];
4857 Utils->DoOneToMany(ServerInstance->Config->ServerName,"OPERNOTICE",*params);
4859 else if (event->GetEventID() == "send_modeset")
4861 if (params->size() < 2)
4863 (*params)[1] = ":" + (*params)[1];
4864 Utils->DoOneToMany(ServerInstance->Config->ServerName,"MODENOTICE",*params);
4866 else if (event->GetEventID() == "send_snoset")
4868 if (params->size() < 2)
4870 (*params)[1] = ":" + (*params)[1];
4871 Utils->DoOneToMany(ServerInstance->Config->ServerName,"SNONOTICE",*params);
4873 else if (event->GetEventID() == "send_push")
4875 if (params->size() < 2)
4878 userrec *a = ServerInstance->FindNick((*params)[0]);
4883 (*params)[1] = ":" + (*params)[1];
4884 Utils->DoOneToOne(ServerInstance->Config->ServerName, "PUSH", *params, a->server);
4888 virtual ~ModuleSpanningTree()
4890 /* This will also free the listeners */
4893 ServerInstance->Timers->DelTimer(SyncTimer);
4895 ServerInstance->DoneWithInterface("InspSocketHook");
4898 virtual Version GetVersion()
4900 return Version(1,1,0,2,VF_VENDOR,API_VERSION);
4903 void Implements(char* List)
4905 List[I_OnPreCommand] = List[I_OnGetServerDescription] = List[I_OnUserInvite] = List[I_OnPostLocalTopicChange] = 1;
4906 List[I_OnWallops] = List[I_OnUserNotice] = List[I_OnUserMessage] = List[I_OnBackgroundTimer] = 1;
4907 List[I_OnUserJoin] = List[I_OnChangeHost] = List[I_OnChangeName] = List[I_OnUserPart] = List[I_OnUserConnect] = 1;
4908 List[I_OnUserQuit] = List[I_OnUserPostNick] = List[I_OnUserKick] = List[I_OnRemoteKill] = List[I_OnRehash] = 1;
4909 List[I_OnOper] = List[I_OnAddGLine] = List[I_OnAddZLine] = List[I_OnAddQLine] = List[I_OnAddELine] = 1;
4910 List[I_OnDelGLine] = List[I_OnDelZLine] = List[I_OnDelQLine] = List[I_OnDelELine] = List[I_ProtoSendMode] = List[I_OnMode] = 1;
4911 List[I_OnStats] = List[I_ProtoSendMetaData] = List[I_OnEvent] = List[I_OnSetAway] = List[I_OnCancelAway] = List[I_OnPostCommand] = 1;
4914 /* It is IMPORTANT that m_spanningtree is the last module in the chain
4915 * so that any activity it sees is FINAL, e.g. we arent going to send out
4916 * a NICK message before m_cloaking has finished putting the +x on the user,
4918 * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
4919 * the module call queue.
4921 Priority Prioritize()
4923 return PRIORITY_LAST;
4927 TimeSyncTimer::TimeSyncTimer(InspIRCd *Inst, ModuleSpanningTree *Mod) : InspTimer(43200, Inst->Time(), true), Instance(Inst), Module(Mod)
4931 void TimeSyncTimer::Tick(time_t TIME)
4933 Module->BroadcastTimeSync();
4936 void SpanningTreeUtilities::DoFailOver(Link* x)
4938 if (x->FailOver.length())
4940 if (x->FailOver == x->Name)
4942 ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Some muppet configured the failover for server \002%s\002 to point at itself. Not following it!", x->Name.c_str());
4945 Link* TryThisOne = this->FindLink(x->FailOver.c_str());
4948 ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Trying failover link for \002%s\002: \002%s\002...", x->Name.c_str(), TryThisOne->Name.c_str());
4949 Creator->ConnectServer(TryThisOne);
4953 ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Invalid failover server specified for server \002%s\002, will not follow!", x->Name.c_str());
4958 Link* SpanningTreeUtilities::FindLink(const std::string& name)
4960 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
4962 if (ServerInstance->MatchText(x->Name.c_str(), name.c_str()))
4970 class ModuleSpanningTreeFactory : public ModuleFactory
4973 ModuleSpanningTreeFactory()
4977 ~ModuleSpanningTreeFactory()
4981 virtual Module * CreateModule(InspIRCd* Me)
4983 return new ModuleSpanningTree(Me);
4989 extern "C" void * init_module( void )
4991 return new ModuleSpanningTreeFactory;