1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
14 #include "configreader.h"
18 #include "commands/cmd_whois.h"
19 #include "commands/cmd_stats.h"
24 #include "transport.h"
25 #include "socketengine.h"
27 #include "m_spanningtree/main.h"
28 #include "m_spanningtree/utils.h"
29 #include "m_spanningtree/treeserver.h"
30 #include "m_spanningtree/link.h"
31 #include "m_spanningtree/treesocket.h"
32 #include "m_spanningtree/resolvers.h"
33 #include "m_spanningtree/handshaketimer.h"
35 /* $ModDep: m_spanningtree/timesynctimer.h m_spanningtree/resolvers.h m_spanningtree/main.h m_spanningtree/utils.h m_spanningtree/treeserver.h m_spanningtree/link.h m_spanningtree/treesocket.h */
37 /** Because most of the I/O gubbins are encapsulated within
38 * InspSocket, we just call the superclass constructor for
39 * most of the action, and append a few of our own values
42 TreeSocket::TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime, Module* HookMod)
43 : InspSocket(SI, host, port, listening, maxtime), Utils(Util), Hook(HookMod)
46 this->LinkState = LISTENER;
47 theirchallenge = ourchallenge = "";
48 if (listening && Hook)
49 InspSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
52 TreeSocket::TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime, const std::string &ServerName, const std::string &bindto, Module* HookMod)
53 : InspSocket(SI, host, port, listening, maxtime, bindto), Utils(Util), Hook(HookMod)
56 theirchallenge = ourchallenge = "";
57 this->LinkState = CONNECTING;
59 InspSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
62 /** When a listening socket gives us a new file descriptor,
63 * we must associate it with a socket without creating a new
64 * connection. This constructor is used for this purpose.
66 TreeSocket::TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, int newfd, char* ip, Module* HookMod)
67 : InspSocket(SI, newfd, ip), Utils(Util), Hook(HookMod)
69 this->LinkState = WAIT_AUTH_1;
70 theirchallenge = ourchallenge = "";
71 /* If we have a transport module hooked to the parent, hook the same module to this
72 * socket, and set a timer waiting for handshake before we send CAPAB etc.
76 InspSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
77 Instance->Timers->AddTimer(new HandshakeTimer(Instance, this, &(Utils->LinkBlocks[0]), this->Utils));
81 /* Otherwise, theres no lower layer transport in plain TCP/IP,
82 * so just send the capabilities right now.
84 this->SendCapabilities();
88 ServerState TreeSocket::GetLinkState()
90 return this->LinkState;
93 Module* TreeSocket::GetHook()
98 TreeSocket::~TreeSocket()
101 InspSocketUnhookRequest(this, (Module*)Utils->Creator, Hook).Send();
104 const std::string& TreeSocket::GetOurChallenge()
106 return this->ourchallenge;
109 void TreeSocket::SetOurChallenge(const std::string &c)
111 this->ourchallenge = c;
114 const std::string& TreeSocket::GetTheirChallenge()
116 return this->theirchallenge;
119 void TreeSocket::SetTheirChallenge(const std::string &c)
121 this->theirchallenge = c;
124 /** When an outbound connection finishes connecting, we receive
125 * this event, and must send our SERVER string to the other
126 * side. If the other side is happy, as outlined in the server
127 * to server docs on the inspircd.org site, the other side
128 * will then send back its own server string.
130 bool TreeSocket::OnConnected()
132 if (this->LinkState == CONNECTING)
134 /* we do not need to change state here. */
135 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
137 if (x->Name == this->myhost)
139 this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] started.");
142 InspSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
143 this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] using transport \2"+x->Hook+"\2");
146 this->SendCapabilities();
147 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
149 Instance->Timers->AddTimer(new HandshakeTimer(Instance, this, &(*x), this->Utils));
151 this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+x->SendPass+" 0 :"+this->Instance->Config->ServerDesc);*/
156 /* There is a (remote) chance that between the /CONNECT and the connection
157 * being accepted, some muppet has removed the <link> block and rehashed.
158 * If that happens the connection hangs here until it's closed. Unlikely
159 * and rather harmless.
161 this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2 lost link tag(!)");
165 void TreeSocket::OnError(InspSocketError e)
167 /* We don't handle this method, because all our
168 * dirty work is done in OnClose() (see below)
169 * which is still called on error conditions too.
171 if (e == I_ERR_CONNECT)
173 this->Instance->SNO->WriteToSnoMask('l',"Connection failed: Connection to \002"+myhost+"\002 refused");
174 Link* MyLink = Utils->FindLink(myhost);
176 Utils->DoFailOver(MyLink);
180 int TreeSocket::OnDisconnect()
182 /* For the same reason as above, we don't
183 * handle OnDisconnect()
188 /** Recursively send the server tree with distances as hops.
189 * This is used during network burst to inform the other server
190 * (and any of ITS servers too) of what servers we know about.
191 * If at any point any of these servers already exist on the other
192 * end, our connection may be terminated. The hopcounts given
193 * by this function are relative, this doesn't matter so long as
194 * they are all >1, as all the remote servers re-calculate them
195 * to be relative too, with themselves as hop 0.
197 void TreeSocket::SendServers(TreeServer* Current, TreeServer* s, int hops)
200 for (unsigned int q = 0; q < Current->ChildCount(); q++)
202 TreeServer* recursive_server = Current->GetChild(q);
203 if (recursive_server != s)
205 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
206 this->WriteLine(command);
207 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
208 /* down to next level */
209 this->SendServers(recursive_server, s, hops+1);
214 std::string TreeSocket::MyCapabilities()
216 std::vector<std::string> modlist;
217 std::string capabilities = "";
218 for (int i = 0; i <= this->Instance->GetModuleCount(); i++)
220 if (this->Instance->modules[i]->GetVersion().Flags & VF_COMMON)
221 modlist.push_back(this->Instance->Config->module_names[i]);
223 sort(modlist.begin(),modlist.end());
224 for (unsigned int i = 0; i < modlist.size(); i++)
227 capabilities = capabilities + ",";
228 capabilities = capabilities + modlist[i];
233 std::string TreeSocket::RandString(unsigned int length)
236 for (unsigned int i = 0; i < length; i++)
237 out += static_cast<char>((rand() % 26) + 65);
241 void TreeSocket::SendCapabilities()
243 irc::commasepstream modulelist(MyCapabilities());
244 this->WriteLine("CAPAB START");
246 /* Send module names, split at 509 length */
247 std::string item = "*";
248 std::string line = "CAPAB MODULES ";
249 while ((item = modulelist.GetToken()) != "")
251 if (line.length() + item.length() + 1 > 509)
253 this->WriteLine(line);
254 line = "CAPAB MODULES ";
257 if (line != "CAPAB MODULES ")
262 if (line != "CAPAB MODULES ")
263 this->WriteLine(line);
270 #ifdef SUPPORT_IP6LINKS
273 this->SetOurChallenge(RandString(20));
274 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)+" CHALLENGE="+this->GetOurChallenge());
276 this->WriteLine("CAPAB END");
279 /* Check a comma seperated list for an item */
280 bool TreeSocket::HasItem(const std::string &list, const std::string &item)
282 irc::commasepstream seplist(list);
283 std::string item2 = "*";
284 while ((item2 = seplist.GetToken()) != "")
292 /* Isolate and return the elements that are different between two comma seperated lists */
293 std::string TreeSocket::ListDifference(const std::string &one, const std::string &two)
295 irc::commasepstream list_one(one);
296 std::string item = "*";
297 std::string result = "";
298 while ((item = list_one.GetToken()) != "")
300 if (!HasItem(two, item))
309 bool TreeSocket::Capab(const std::deque<std::string> ¶ms)
311 if (params.size() < 1)
313 this->WriteLine("ERROR :Invalid number of parameters for CAPAB - Mismatched version");
316 if (params[0] == "START")
318 this->ModuleList = "";
319 this->CapKeys.clear();
321 else if (params[0] == "END")
323 std::string reason = "";
325 #ifdef SUPPORT_IP6LINKS
328 /* Compare ModuleList and check CapKeys...
329 * Maybe this could be tidier? -- Brain
331 if ((this->ModuleList != this->MyCapabilities()) && (this->ModuleList.length()))
333 std::string diff = ListDifference(this->ModuleList, this->MyCapabilities());
336 diff = "your server:" + ListDifference(this->MyCapabilities(), this->ModuleList);
340 diff = "this server:" + diff;
342 if (diff.length() == 12)
343 reason = "Module list in CAPAB is not alphabetically ordered, cannot compare lists.";
345 reason = "Modules loaded on these servers are not correctly matched, these modules are not loaded on " + diff;
347 if (((this->CapKeys.find("IP6SUPPORT") == this->CapKeys.end()) && (ip6support)) || ((this->CapKeys.find("IP6SUPPORT") != this->CapKeys.end()) && (this->CapKeys.find("IP6SUPPORT")->second != ConvToStr(ip6support))))
348 reason = "We don't both support linking to IPV6 servers";
349 if (((this->CapKeys.find("IP6NATIVE") != this->CapKeys.end()) && (this->CapKeys.find("IP6NATIVE")->second == "1")) && (!ip6support))
350 reason = "The remote server is IPV6 native, and we don't support linking to IPV6 servers";
351 if (((this->CapKeys.find("NICKMAX") == this->CapKeys.end()) || ((this->CapKeys.find("NICKMAX") != this->CapKeys.end()) && (this->CapKeys.find("NICKMAX")->second != ConvToStr(NICKMAX)))))
352 reason = "Maximum nickname lengths differ or remote nickname length not specified";
353 if (((this->CapKeys.find("PROTOCOL") == this->CapKeys.end()) || ((this->CapKeys.find("PROTOCOL") != this->CapKeys.end()) && (this->CapKeys.find("PROTOCOL")->second != ConvToStr(ProtocolVersion)))))
355 if (this->CapKeys.find("PROTOCOL") != this->CapKeys.end())
357 reason = "Mismatched protocol versions "+this->CapKeys.find("PROTOCOL")->second+" and "+ConvToStr(ProtocolVersion);
361 reason = "Protocol version not specified";
364 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))))
365 reason = "We don't both have halfop support enabled/disabled identically";
366 if (((this->CapKeys.find("IDENTMAX") == this->CapKeys.end()) || ((this->CapKeys.find("IDENTMAX") != this->CapKeys.end()) && (this->CapKeys.find("IDENTMAX")->second != ConvToStr(IDENTMAX)))))
367 reason = "Maximum ident lengths differ or remote ident length not specified";
368 if (((this->CapKeys.find("CHANMAX") == this->CapKeys.end()) || ((this->CapKeys.find("CHANMAX") != this->CapKeys.end()) && (this->CapKeys.find("CHANMAX")->second != ConvToStr(CHANMAX)))))
369 reason = "Maximum channel lengths differ or remote channel length not specified";
370 if (((this->CapKeys.find("MAXMODES") == this->CapKeys.end()) || ((this->CapKeys.find("MAXMODES") != this->CapKeys.end()) && (this->CapKeys.find("MAXMODES")->second != ConvToStr(MAXMODES)))))
371 reason = "Maximum modes per line differ or remote modes per line not specified";
372 if (((this->CapKeys.find("MAXQUIT") == this->CapKeys.end()) || ((this->CapKeys.find("MAXQUIT") != this->CapKeys.end()) && (this->CapKeys.find("MAXQUIT")->second != ConvToStr(MAXQUIT)))))
373 reason = "Maximum quit lengths differ or remote quit length not specified";
374 if (((this->CapKeys.find("MAXTOPIC") == this->CapKeys.end()) || ((this->CapKeys.find("MAXTOPIC") != this->CapKeys.end()) && (this->CapKeys.find("MAXTOPIC")->second != ConvToStr(MAXTOPIC)))))
375 reason = "Maximum topic lengths differ or remote topic length not specified";
376 if (((this->CapKeys.find("MAXKICK") == this->CapKeys.end()) || ((this->CapKeys.find("MAXKICK") != this->CapKeys.end()) && (this->CapKeys.find("MAXKICK")->second != ConvToStr(MAXKICK)))))
377 reason = "Maximum kick lengths differ or remote kick length not specified";
378 if (((this->CapKeys.find("MAXGECOS") == this->CapKeys.end()) || ((this->CapKeys.find("MAXGECOS") != this->CapKeys.end()) && (this->CapKeys.find("MAXGECOS")->second != ConvToStr(MAXGECOS)))))
379 reason = "Maximum GECOS (fullname) lengths differ or remote GECOS length not specified";
380 if (((this->CapKeys.find("MAXAWAY") == this->CapKeys.end()) || ((this->CapKeys.find("MAXAWAY") != this->CapKeys.end()) && (this->CapKeys.find("MAXAWAY")->second != ConvToStr(MAXAWAY)))))
381 reason = "Maximum awaymessage lengths differ or remote awaymessage length not specified";
383 /* Challenge response, store their challenge for our password */
384 std::map<std::string,std::string>::iterator n = this->CapKeys.find("CHALLENGE");
385 if (n != this->CapKeys.end())
387 /* Challenge-response is on now */
388 this->SetTheirChallenge(n->second);
393 this->WriteLine("ERROR :CAPAB negotiation failed: "+reason);
397 else if ((params[0] == "MODULES") && (params.size() == 2))
399 if (!this->ModuleList.length())
401 this->ModuleList.append(params[1]);
405 this->ModuleList.append(",");
406 this->ModuleList.append(params[1]);
410 else if ((params[0] == "CAPABILITIES") && (params.size() == 2))
412 irc::tokenstream capabs(params[1]);
415 while ((more = capabs.GetToken(item)))
417 /* Process each key/value pair */
418 std::string::size_type equals = item.rfind('=');
419 if (equals != std::string::npos)
421 std::string var = item.substr(0, equals);
422 std::string value = item.substr(equals+1, item.length());
423 CapKeys[var] = value;
430 /** This function forces this server to quit, removing this server
431 * and any users on it (and servers and users below that, etc etc).
432 * It's very slow and pretty clunky, but luckily unless your network
433 * is having a REAL bad hair day, this function shouldnt be called
434 * too many times a month ;-)
436 void TreeSocket::SquitServer(std::string &from, TreeServer* Current)
438 /* recursively squit the servers attached to 'Current'.
439 * We're going backwards so we don't remove users
440 * while we still need them ;)
442 for (unsigned int q = 0; q < Current->ChildCount(); q++)
444 TreeServer* recursive_server = Current->GetChild(q);
445 this->SquitServer(from,recursive_server);
447 /* Now we've whacked the kids, whack self */
449 num_lost_users += Current->QuitUsers(from);
452 /** This is a wrapper function for SquitServer above, which
453 * does some validation first and passes on the SQUIT to all
454 * other remaining servers.
456 void TreeSocket::Squit(TreeServer* Current, const std::string &reason)
458 if ((Current) && (Current != Utils->TreeRoot))
460 Event rmode((char*)Current->GetName().c_str(), (Module*)Utils->Creator, "lost_server");
461 rmode.Send(Instance);
463 std::deque<std::string> params;
464 params.push_back(Current->GetName());
465 params.push_back(":"+reason);
466 Utils->DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
467 if (Current->GetParent() == Utils->TreeRoot)
469 this->Instance->WriteOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
473 this->Instance->WriteOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
475 num_lost_servers = 0;
477 std::string from = Current->GetParent()->GetName()+" "+Current->GetName();
478 SquitServer(from, Current);
480 Current->GetParent()->DelChild(Current);
482 this->Instance->WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
486 Instance->Log(DEFAULT,"Squit from unknown server");
490 /** FMODE command - server mode with timestamp checks */
491 bool TreeSocket::ForceMode(const std::string &source, std::deque<std::string> ¶ms)
493 /* Chances are this is a 1.0 FMODE without TS */
494 if (params.size() < 3)
496 /* No modes were in the command, probably a channel with no modes set on it */
501 std::string sourceserv;
502 /* Are we dealing with an FMODE from a user, or from a server? */
503 userrec* who = this->Instance->FindNick(source);
506 /* FMODE from a user, set sourceserv to the users server name */
507 sourceserv = who->server;
511 /* FMODE from a server, create a fake user to receive mode feedback */
512 who = new userrec(this->Instance);
513 who->SetFd(FD_MAGIC_NUMBER);
514 smode = true; /* Setting this flag tells us we should free the userrec later */
515 sourceserv = source; /* Set sourceserv to the actual source string */
517 const char* modelist[64];
520 memset(&modelist,0,sizeof(modelist));
521 for (unsigned int q = 0; (q < params.size()) && (q < 64); q++)
525 /* The timestamp is in this position.
526 * We don't want to pass that up to the
527 * server->client protocol!
529 TS = atoi(params[q].c_str());
533 /* Everything else is fine to append to the modelist */
534 modelist[n++] = params[q].c_str();
538 /* Extract the TS value of the object, either userrec or chanrec */
539 userrec* dst = this->Instance->FindNick(params[0]);
540 chanrec* chan = NULL;
548 chan = this->Instance->FindChan(params[0]);
554 /* Oops, channel doesnt exist! */
558 /* TS is equal or less: Merge the mode changes into ours and pass on.
564 this->Instance->SendMode(modelist, n, who);
568 this->Instance->CallCommandHandler("MODE", modelist, n, who);
570 /* HOT POTATO! PASS IT ON! */
571 Utils->DoOneToAllButSender(source,"FMODE",params,sourceserv);
573 /* If the TS is greater than ours, we drop the mode and dont pass it anywhere.
582 /** FTOPIC command */
583 bool TreeSocket::ForceTopic(const std::string &source, std::deque<std::string> ¶ms)
585 if (params.size() != 4)
587 time_t ts = atoi(params[1].c_str());
588 std::string nsource = source;
589 chanrec* c = this->Instance->FindChan(params[0]);
592 if ((ts >= c->topicset) || (!*c->topic))
594 std::string oldtopic = c->topic;
595 strlcpy(c->topic,params[3].c_str(),MAXTOPIC);
596 strlcpy(c->setby,params[2].c_str(),127);
598 /* if the topic text is the same as the current topic,
599 * dont bother to send the TOPIC command out, just silently
600 * update the set time and set nick.
602 if (oldtopic != params[3])
604 userrec* user = this->Instance->FindNick(source);
607 c->WriteChannelWithServ(source.c_str(), "TOPIC %s :%s", c->name, c->topic);
611 c->WriteChannel(user, "TOPIC %s :%s", c->name, c->topic);
612 nsource = user->server;
614 /* all done, send it on its way */
615 params[3] = ":" + params[3];
616 Utils->DoOneToAllButSender(source,"FTOPIC",params,nsource);
624 /** FJOIN, similar to TS6 SJOIN, but not quite. */
625 bool TreeSocket::ForceJoin(const std::string &source, std::deque<std::string> ¶ms)
627 /* 1.1 FJOIN works as follows:
629 * Each FJOIN is sent along with a timestamp, and the side with the lowest
630 * timestamp 'wins'. From this point on we will refer to this side as the
631 * winner. The side with the higher timestamp loses, from this point on we
632 * will call this side the loser or losing side. This should be familiar to
633 * anyone who's dealt with dreamforge or TS6 before.
635 * When two sides of a split heal and this occurs, the following things
638 * If the timestamps are exactly equal, both sides merge their privilages
639 * and users, as in InspIRCd 1.0 and ircd2.8. The channels have not been
640 * re-created during a split, this is safe to do.
643 * If the timestamps are NOT equal, the losing side removes all privilage
644 * modes from all of its users that currently exist in the channel, before
645 * introducing new users into the channel which are listed in the FJOIN
646 * command's parameters. This means, all modes +ohv, and privilages added
647 * by modules, such as +qa. The losing side then LOWERS its timestamp value
648 * of the channel to match that of the winning side, and the modes of the
649 * users of the winning side are merged in with the losing side. The loser
650 * then sends out a set of FMODE commands which 'confirm' that it just
651 * removed all privilage modes from its existing users, which allows for
652 * services packages to still work correctly without needing to know the
653 * timestamping rules which InspIRCd follows. In TS6 servers this is always
654 * a problem, and services packages must contain code which explicitly
655 * behaves as TS6 does, removing ops from the losing side of a split where
656 * neccessary within its internal records, as this state information is
657 * not explicitly echoed out in that protocol.
659 * The winning side on the other hand will ignore all user modes from the
660 * losing side, so only its own modes get applied. Life is simple for those
661 * who succeed at internets. :-)
663 * NOTE: Unlike TS6 and dreamforge and other protocols which have SJOIN,
664 * FJOIN does not contain the simple-modes such as +iklmnsp. Why not,
665 * you ask? Well, quite simply because we don't need to. They'll be sent
666 * after the FJOIN by FMODE, and FMODE is timestamped, so in the event
667 * the losing side sends any modes for the channel which shouldnt win,
668 * they wont as their timestamp will be too high :-)
671 if (params.size() < 3)
674 char first[MAXBUF]; /* The first parameter of the mode command */
675 char modestring[MAXBUF]; /* The mode sequence (2nd parameter) of the mode command */
676 char* mode_users[127]; /* The values used by the mode command */
677 memset(&mode_users,0,sizeof(mode_users)); /* Initialize mode parameters */
678 mode_users[0] = first; /* Set this up to be our on-stack value */
679 mode_users[1] = modestring; /* Same here as above */
680 strcpy(modestring,"+"); /* Initialize the mode sequence to just '+' */
681 unsigned int modectr = 2; /* Pointer to the third mode parameter (e.g. the one after the +-sequence) */
683 userrec* who = NULL; /* User we are currently checking */
684 std::string channel = params[0]; /* Channel name, as a string */
685 time_t TS = atoi(params[1].c_str()); /* Timestamp given to us for remote side */
686 std::string nicklist = params[2];
687 bool created = false;
689 /* Try and find the channel */
690 chanrec* chan = this->Instance->FindChan(channel);
692 /* Initialize channel name in the mode parameters */
693 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
695 /* default TS is a high value, which if we dont have this
696 * channel will let the other side apply their modes.
698 time_t ourTS = Instance->Time(true)+600;
699 /* Does this channel exist? if it does, get its REAL timestamp */
703 created = true; /* don't perform deops, and set TS to correct time after processing. */
705 /* do this first, so our mode reversals are correctly received by other servers
706 * if there is a TS collision.
708 params[2] = ":" + params[2];
709 Utils->DoOneToAllButSender(source,"FJOIN",params,source);
711 /* In 1.1, if they have the newer channel, we immediately clear
712 * all status modes from our users. We then accept their modes.
713 * If WE have the newer channel its the other side's job to do this.
714 * Note that this causes the losing server to send out confirming
719 std::deque<std::string> param_list;
720 /* Lower the TS here */
721 if (Utils->AnnounceTSChange && chan)
722 chan->WriteChannelWithServ(Instance->Config->ServerName,
723 "NOTICE %s :TS for %s changed from %lu to %lu", chan->name, chan->name, ourTS, TS);
725 /* Zap all the privilage modes on our side, if the channel exists here */
728 param_list.push_back(channel);
731 this->RemoveStatus(Instance->Config->ServerName, param_list);
734 /* Put the final parameter of the FJOIN into a tokenstream ready to split it */
735 irc::tokenstream users(nicklist);
738 /* Now, process every 'prefixes,nick' pair */
739 while (users.GetToken(item))
742 const char* usr = item.c_str();
743 /* Safety check just to make sure someones not sent us an FJOIN full of spaces
744 * (is this even possible?) */
747 const char* permissions = usr;
749 char* nm = new char[MAXBUF];
751 /* Iterate through all the prefix values, convert them from prefixes
752 * to mode letters, and append them to the mode sequence
754 while ((*permissions) && (*permissions != ',') && (ntimes < MAXBUF))
756 ModeHandler* mh = Instance->Modes->FindPrefix(*permissions);
759 /* This is a valid prefix */
761 *tnm++ = mh->GetModeChar();
765 /* Not a valid prefix...
766 * danger bill bobbertson! (that's will robinsons older brother ;-) ...)
768 this->Instance->WriteOpers("ERROR: We received a user with an unknown prefix '%c'. Closed connection to avoid a desync.",*permissions);
769 this->WriteLine(std::string("ERROR :Invalid prefix '")+(*permissions)+"' in FJOIN");
775 /* Null terminate modes */
777 /* Advance past the comma, to the nick */
779 /* Check the user actually exists */
780 who = this->Instance->FindNick(usr);
783 /* Check that the user's 'direction' is correct
784 * based on the server sending the FJOIN. We must
785 * check each nickname in turn, because the origin of
786 * the FJOIN may be different to the origin of the nicks
787 * in the command itself.
789 TreeServer* route_back_again = Utils->BestRouteTo(who->server);
790 if ((!route_back_again) || (route_back_again->GetSocket() != this))
792 /* Oh dear oh dear. */
797 /* NOTE: Moved this below the fake direction check, so that modes
798 * arent put into the mode list for users that were collided, and
799 * may reconnect from the other side or our side before the split
803 /* Did they get any modes? How many times? */
804 strlcat(modestring, nm, MAXBUF);
805 for (int k = 0; k < ntimes; k++)
806 mode_users[modectr++] = strdup(usr);
807 /* Free temporary buffer used for mode sequence */
810 /* Finally, we can actually place the user into the channel.
811 * We're sure its right. Final answer, phone a friend.
814 chanrec::JoinUser(this->Instance, who, channel.c_str(), true, "", TS);
816 chanrec::JoinUser(this->Instance, who, channel.c_str(), true, "");
817 /* Have we already queued up MAXMODES modes with parameters
818 * (+qaohv) ready to be sent to the server?
820 if (modectr >= (MAXMODES-1))
822 /* Only actually give the users any status if we lost
823 * the FJOIN or drew (equal timestamps).
824 * It isn't actually possible for ourTS to be > TS here,
825 * only possible to actually have ourTS == TS, or
826 * ourTS < TS, because if we lost, we already lowered
827 * our TS above before we entered this loop. We only
828 * check >= as a safety measure, in case someone stuffed
829 * up. If someone DID stuff up, it was most likely me.
830 * Note: I do not like baseball bats in the face...
834 this->Instance->SendMode((const char**)mode_users,modectr,who);
836 /* Something stuffed up, and for some reason, the timestamp is
837 * NOT lowered right now and should be. Lower it. Usually this
838 * code won't be executed, doubtless someone will remove it some
843 Instance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",chan->name,ourTS,TS);
849 /* Reset all this back to defaults, and
850 * free any ram we have left allocated.
852 strcpy(mode_users[1],"+");
853 for (unsigned int f = 2; f < modectr; f++)
860 /* Remember to free this */
862 /* If we got here, there's a nick in FJOIN which doesnt exist on this server.
863 * We don't try to process the nickname here (that WOULD cause a segfault because
864 * we'd be playing with null pointers) however, we DO pass the nickname on, just
865 * in case somehow we're desynched, so that other users which might be able to see
866 * the nickname get their fair chance to process it.
868 Instance->Log(SPARSE,"Warning! Invalid user %s in FJOIN to channel %s IGNORED", usr, channel.c_str());
874 /* there werent enough modes built up to flush it during FJOIN,
875 * or, there are a number left over. flush them out.
877 if ((modectr > 2) && (who) && (chan))
881 /* Our channel is newer than theirs. Evil deeds must be afoot. */
882 this->Instance->SendMode((const char**)mode_users,modectr,who);
883 /* Yet again, we can't actually get a true value here, if everything else
884 * is working as it should.
888 Instance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",chan->name,ourTS,TS);
894 /* Free anything we have left to free */
895 for (unsigned int f = 2; f < modectr; f++)
898 /* All done. That wasnt so bad was it, you can wipe
899 * the sweat from your forehead now. :-)
905 bool TreeSocket::IntroduceClient(const std::string &source, std::deque<std::string> ¶ms)
907 /** Do we have enough parameters:
908 * NICK age nick host dhost ident +modes ip :gecos
910 if (params.size() != 8)
912 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[1]+"?)");
916 time_t age = atoi(params[0].c_str());
917 const char* tempnick = params[1].c_str();
919 /** Check parameters for validity before introducing the client, discovered by dmb.
920 * XXX: Can we make this neater?
924 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction (Invalid TS?)");
927 else if (params[1].length() > NICKMAX)
929 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[1]+" > NICKMAX?)");
932 else if (params[2].length() > 64)
934 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[2]+" > 64?)");
937 else if (params[3].length() > 64)
939 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[3]+" > 64?)");
942 else if (params[4].length() > IDENTMAX)
944 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[4]+" > IDENTMAX?)");
947 else if (params[7].length() > MAXGECOS)
949 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[7]+" > MAXGECOS?)");
953 /** Our client looks ok, lets introduce it now
955 Instance->Log(DEBUG,"New remote client %s",tempnick);
956 user_hash::iterator iter = this->Instance->clientlist->find(tempnick);
958 if (iter != this->Instance->clientlist->end())
961 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+tempnick+" :Nickname collision");
962 userrec::QuitUser(this->Instance, iter->second, "Nickname collision");
966 userrec* _new = new userrec(this->Instance);
967 (*(this->Instance->clientlist))[tempnick] = _new;
968 _new->SetFd(FD_MAGIC_NUMBER);
969 strlcpy(_new->nick, tempnick,NICKMAX-1);
970 strlcpy(_new->host, params[2].c_str(),63);
971 strlcpy(_new->dhost, params[3].c_str(),63);
972 _new->server = this->Instance->FindServerNamePtr(source.c_str());
973 strlcpy(_new->ident, params[4].c_str(),IDENTMAX);
974 strlcpy(_new->fullname, params[7].c_str(),MAXGECOS);
975 _new->registered = REG_ALL;
978 /* we need to remove the + from the modestring, so we can do our stuff */
979 std::string::size_type pos_after_plus = params[5].find_first_not_of('+');
980 if (pos_after_plus != std::string::npos)
981 params[5] = params[5].substr(pos_after_plus);
983 for (std::string::iterator v = params[5].begin(); v != params[5].end(); v++)
985 _new->modes[(*v)-65] = 1;
986 /* For each mode thats set, increase counter */
987 ModeHandler* mh = Instance->Modes->FindMode(*v, MODETYPE_USER);
992 /* now we've done with modes processing, put the + back for remote servers */
993 params[5] = "+" + params[5];
995 #ifdef SUPPORT_IP6LINKS
996 if (params[6].find_first_of(":") != std::string::npos)
997 _new->SetSockAddr(AF_INET6, params[6].c_str(), 0);
1000 _new->SetSockAddr(AF_INET, params[6].c_str(), 0);
1002 Instance->AddGlobalClone(_new);
1004 if (!this->Instance->SilentULine(_new->server))
1005 this->Instance->SNO->WriteToSnoMask('C',"Client connecting at %s: %s!%s@%s [%s]",_new->server,_new->nick,_new->ident,_new->host, _new->GetIPString());
1007 params[7] = ":" + params[7];
1008 Utils->DoOneToAllButSender(source,"NICK", params, source);
1010 // Increment the Source Servers User Count..
1011 TreeServer* SourceServer = Utils->FindServer(source);
1014 SourceServer->AddUserCount();
1017 FOREACH_MOD_I(Instance,I_OnPostConnect,OnPostConnect(_new));
1022 /** Send one or more FJOINs for a channel of users.
1023 * If the length of a single line is more than 480-NICKMAX
1024 * in length, it is split over multiple lines.
1026 void TreeSocket::SendFJoins(TreeServer* Current, chanrec* c)
1030 std::string individual_halfops = std::string(":")+this->Instance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age);
1032 size_t dlen, curlen;
1033 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1035 char* ptr = list + dlen;
1037 CUList *ulist = c->GetUsers();
1038 std::string modes = "";
1039 std::string params = "";
1041 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1043 // The first parameter gets a : before it
1044 size_t ptrlen = snprintf(ptr, MAXBUF, " %s%s,%s", !numusers ? ":" : "", c->GetAllPrefixChars(i->second), i->second->nick);
1051 if (curlen > (480-NICKMAX))
1053 buffer.append(list).append("\r\n");
1054 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1062 buffer.append(list).append("\r\n");
1064 /* Sorry for the hax. Because newly created channels assume +nt,
1065 * if this channel doesnt have +nt, explicitly send -n and -t for the missing modes.
1067 bool inverted = false;
1068 if (!c->IsModeSet('n'))
1073 if (!c->IsModeSet('t'))
1083 buffer.append(":").append(this->Instance->Config->ServerName).append(" FMODE ").append(c->name).append(" ").append(ConvToStr(c->age)).append(" +").append(c->ChanModes(true)).append("\r\n");
1086 for (BanList::iterator b = c->bans.begin(); b != c->bans.end(); b++)
1088 int size = strlen(b->data) + 2;
1089 int currsize = linesize + size;
1090 if (currsize <= 350)
1093 params.append(" ").append(b->data);
1096 if ((params.length() >= MAXMODES) || (currsize > 350))
1098 /* Wrap at MAXMODES */
1099 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");
1106 /* Only send these if there are any */
1108 buffer.append(":").append(this->Instance->Config->ServerName).append(" FMODE ").append(c->name).append(" ").append(ConvToStr(c->age)).append(" +").append(modes).append(params);
1110 this->WriteLine(buffer);
1113 /** Send G, Q, Z and E lines */
1114 void TreeSocket::SendXLines(TreeServer* Current)
1118 std::string n = this->Instance->Config->ServerName;
1119 const char* sn = n.c_str();
1120 /* Yes, these arent too nice looking, but they get the job done */
1121 for (std::vector<ZLine*>::iterator i = Instance->XLines->zlines.begin(); i != Instance->XLines->zlines.end(); i++)
1123 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);
1124 buffer.append(data);
1126 for (std::vector<QLine*>::iterator i = Instance->XLines->qlines.begin(); i != Instance->XLines->qlines.end(); i++)
1128 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);
1129 buffer.append(data);
1131 for (std::vector<GLine*>::iterator i = Instance->XLines->glines.begin(); i != Instance->XLines->glines.end(); i++)
1133 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);
1134 buffer.append(data);
1136 for (std::vector<ELine*>::iterator i = Instance->XLines->elines.begin(); i != Instance->XLines->elines.end(); i++)
1138 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);
1139 buffer.append(data);
1141 for (std::vector<ZLine*>::iterator i = Instance->XLines->pzlines.begin(); i != Instance->XLines->pzlines.end(); i++)
1143 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);
1144 buffer.append(data);
1146 for (std::vector<QLine*>::iterator i = Instance->XLines->pqlines.begin(); i != Instance->XLines->pqlines.end(); i++)
1148 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);
1149 buffer.append(data);
1151 for (std::vector<GLine*>::iterator i = Instance->XLines->pglines.begin(); i != Instance->XLines->pglines.end(); i++)
1153 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);
1154 buffer.append(data);
1156 for (std::vector<ELine*>::iterator i = Instance->XLines->pelines.begin(); i != Instance->XLines->pelines.end(); i++)
1158 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);
1159 buffer.append(data);
1162 if (!buffer.empty())
1163 this->WriteLine(buffer);
1166 /** Send channel modes and topics */
1167 void TreeSocket::SendChannelModes(TreeServer* Current)
1170 std::deque<std::string> list;
1171 std::string n = this->Instance->Config->ServerName;
1172 const char* sn = n.c_str();
1173 for (chan_hash::iterator c = this->Instance->chanlist->begin(); c != this->Instance->chanlist->end(); c++)
1175 SendFJoins(Current, c->second);
1176 if (*c->second->topic)
1178 snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",sn,c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
1179 this->WriteLine(data);
1181 FOREACH_MOD_I(this->Instance,I_OnSyncChannel,OnSyncChannel(c->second,(Module*)Utils->Creator,(void*)this));
1183 c->second->GetExtList(list);
1184 for (unsigned int j = 0; j < list.size(); j++)
1186 FOREACH_MOD_I(this->Instance,I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)Utils->Creator,(void*)this,list[j]));
1191 /** send all users and their oper state/modes */
1192 void TreeSocket::SendUsers(TreeServer* Current)
1195 std::deque<std::string> list;
1196 std::string dataline;
1197 for (user_hash::iterator u = this->Instance->clientlist->begin(); u != this->Instance->clientlist->end(); u++)
1199 if (u->second->registered == REG_ALL)
1201 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);
1202 this->WriteLine(data);
1203 if (*u->second->oper)
1205 snprintf(data,MAXBUF,":%s OPERTYPE %s", u->second->nick, u->second->oper);
1206 this->WriteLine(data);
1208 if (*u->second->awaymsg)
1210 snprintf(data,MAXBUF,":%s AWAY :%s", u->second->nick, u->second->awaymsg);
1211 this->WriteLine(data);
1213 FOREACH_MOD_I(this->Instance,I_OnSyncUser,OnSyncUser(u->second,(Module*)Utils->Creator,(void*)this));
1215 u->second->GetExtList(list);
1217 for (unsigned int j = 0; j < list.size(); j++)
1219 FOREACH_MOD_I(this->Instance,I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)Utils->Creator,(void*)this,list[j]));
1225 /** This function is called when we want to send a netburst to a local
1226 * server. There is a set order we must do this, because for example
1227 * users require their servers to exist, and channels require their
1228 * users to exist. You get the idea.
1230 void TreeSocket::DoBurst(TreeServer* s)
1232 std::string burst = "BURST "+ConvToStr(Instance->Time(true));
1233 std::string endburst = "ENDBURST";
1234 // Because by the end of the netburst, it could be gone!
1235 std::string name = s->GetName();
1236 this->Instance->SNO->WriteToSnoMask('l',"Bursting to \2"+name+"\2.");
1237 this->WriteLine(burst);
1238 /* send our version string */
1239 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" VERSION :"+this->Instance->GetVersionString());
1240 /* Send server tree */
1241 this->SendServers(Utils->TreeRoot,s,1);
1242 /* Send users and their oper status */
1244 /* Send everything else (channel modes, xlines etc) */
1245 this->SendChannelModes(s);
1246 this->SendXLines(s);
1247 FOREACH_MOD_I(this->Instance,I_OnSyncOtherMetaData,OnSyncOtherMetaData((Module*)Utils->Creator,(void*)this));
1248 this->WriteLine(endburst);
1249 this->Instance->SNO->WriteToSnoMask('l',"Finished bursting to \2"+name+"\2.");
1252 /** This function is called when we receive data from a remote
1253 * server. We buffer the data in a std::string (it doesnt stay
1254 * there for long), reading using InspSocket::Read() which can
1255 * read up to 16 kilobytes in one operation.
1257 * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
1258 * THE SOCKET OBJECT FOR US.
1260 bool TreeSocket::OnDataReady()
1262 char* data = this->Read();
1263 /* Check that the data read is a valid pointer and it has some content */
1266 this->in_buffer.append(data);
1267 /* While there is at least one new line in the buffer,
1268 * do something useful (we hope!) with it.
1270 while (in_buffer.find("\n") != std::string::npos)
1272 std::string ret = in_buffer.substr(0,in_buffer.find("\n")-1);
1273 in_buffer = in_buffer.substr(in_buffer.find("\n")+1,in_buffer.length()-in_buffer.find("\n"));
1274 /* Use rfind here not find, as theres more
1275 * chance of the \r being near the end of the
1276 * string, not the start.
1278 if (ret.find("\r") != std::string::npos)
1279 ret = in_buffer.substr(0,in_buffer.find("\r")-1);
1280 /* Process this one, abort if it
1281 * didnt return true.
1283 if (!this->ProcessLine(ret))
1290 /* EAGAIN returns an empty but non-NULL string, so this
1291 * evaluates to TRUE for EAGAIN but to FALSE for EOF.
1293 return (data && !*data);