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 std::string TreeSocket::MakePass(const std::string &password)
126 if ((this->GetOurChallenge() != "") && (this->GetTheirChallenge() != ""))
128 return password + ":" + this->GetTheirChallenge();
133 /** When an outbound connection finishes connecting, we receive
134 * this event, and must send our SERVER string to the other
135 * side. If the other side is happy, as outlined in the server
136 * to server docs on the inspircd.org site, the other side
137 * will then send back its own server string.
139 bool TreeSocket::OnConnected()
141 if (this->LinkState == CONNECTING)
143 /* we do not need to change state here. */
144 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
146 if (x->Name == this->myhost)
148 this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] started.");
151 InspSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
152 this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] using transport \2"+x->Hook+"\2");
155 this->SendCapabilities();
156 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
157 Instance->Timers->AddTimer(new HandshakeTimer(Instance, this, &(*x), this->Utils));
162 /* There is a (remote) chance that between the /CONNECT and the connection
163 * being accepted, some muppet has removed the <link> block and rehashed.
164 * If that happens the connection hangs here until it's closed. Unlikely
165 * and rather harmless.
167 this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2 lost link tag(!)");
171 void TreeSocket::OnError(InspSocketError e)
173 /* We don't handle this method, because all our
174 * dirty work is done in OnClose() (see below)
175 * which is still called on error conditions too.
177 if (e == I_ERR_CONNECT)
179 this->Instance->SNO->WriteToSnoMask('l',"Connection failed: Connection to \002"+myhost+"\002 refused");
180 Link* MyLink = Utils->FindLink(myhost);
182 Utils->DoFailOver(MyLink);
186 int TreeSocket::OnDisconnect()
188 /* For the same reason as above, we don't
189 * handle OnDisconnect()
194 /** Recursively send the server tree with distances as hops.
195 * This is used during network burst to inform the other server
196 * (and any of ITS servers too) of what servers we know about.
197 * If at any point any of these servers already exist on the other
198 * end, our connection may be terminated. The hopcounts given
199 * by this function are relative, this doesn't matter so long as
200 * they are all >1, as all the remote servers re-calculate them
201 * to be relative too, with themselves as hop 0.
203 void TreeSocket::SendServers(TreeServer* Current, TreeServer* s, int hops)
206 for (unsigned int q = 0; q < Current->ChildCount(); q++)
208 TreeServer* recursive_server = Current->GetChild(q);
209 if (recursive_server != s)
211 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
212 this->WriteLine(command);
213 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
214 /* down to next level */
215 this->SendServers(recursive_server, s, hops+1);
220 std::string TreeSocket::MyCapabilities()
222 std::vector<std::string> modlist;
223 std::string capabilities = "";
224 for (int i = 0; i <= this->Instance->GetModuleCount(); i++)
226 if (this->Instance->modules[i]->GetVersion().Flags & VF_COMMON)
227 modlist.push_back(this->Instance->Config->module_names[i]);
229 sort(modlist.begin(),modlist.end());
230 for (unsigned int i = 0; i < modlist.size(); i++)
233 capabilities = capabilities + ",";
234 capabilities = capabilities + modlist[i];
239 std::string TreeSocket::RandString(unsigned int length)
242 for (unsigned int i = 0; i < length; i++)
243 out += static_cast<char>((rand() % 26) + 65);
247 void TreeSocket::SendCapabilities()
249 irc::commasepstream modulelist(MyCapabilities());
250 this->WriteLine("CAPAB START");
252 /* Send module names, split at 509 length */
253 std::string item = "*";
254 std::string line = "CAPAB MODULES ";
255 while ((item = modulelist.GetToken()) != "")
257 if (line.length() + item.length() + 1 > 509)
259 this->WriteLine(line);
260 line = "CAPAB MODULES ";
263 if (line != "CAPAB MODULES ")
268 if (line != "CAPAB MODULES ")
269 this->WriteLine(line);
276 #ifdef SUPPORT_IP6LINKS
279 this->SetOurChallenge(RandString(20));
280 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());
282 this->WriteLine("CAPAB END");
285 /* Check a comma seperated list for an item */
286 bool TreeSocket::HasItem(const std::string &list, const std::string &item)
288 irc::commasepstream seplist(list);
289 std::string item2 = "*";
290 while ((item2 = seplist.GetToken()) != "")
298 /* Isolate and return the elements that are different between two comma seperated lists */
299 std::string TreeSocket::ListDifference(const std::string &one, const std::string &two)
301 irc::commasepstream list_one(one);
302 std::string item = "*";
303 std::string result = "";
304 while ((item = list_one.GetToken()) != "")
306 if (!HasItem(two, item))
315 bool TreeSocket::Capab(const std::deque<std::string> ¶ms)
317 if (params.size() < 1)
319 this->WriteLine("ERROR :Invalid number of parameters for CAPAB - Mismatched version");
322 if (params[0] == "START")
324 this->ModuleList = "";
325 this->CapKeys.clear();
327 else if (params[0] == "END")
329 std::string reason = "";
331 #ifdef SUPPORT_IP6LINKS
334 /* Compare ModuleList and check CapKeys...
335 * Maybe this could be tidier? -- Brain
337 if ((this->ModuleList != this->MyCapabilities()) && (this->ModuleList.length()))
339 std::string diff = ListDifference(this->ModuleList, this->MyCapabilities());
342 diff = "your server:" + ListDifference(this->MyCapabilities(), this->ModuleList);
346 diff = "this server:" + diff;
348 if (diff.length() == 12)
349 reason = "Module list in CAPAB is not alphabetically ordered, cannot compare lists.";
351 reason = "Modules loaded on these servers are not correctly matched, these modules are not loaded on " + diff;
353 if (((this->CapKeys.find("IP6SUPPORT") == this->CapKeys.end()) && (ip6support)) || ((this->CapKeys.find("IP6SUPPORT") != this->CapKeys.end()) && (this->CapKeys.find("IP6SUPPORT")->second != ConvToStr(ip6support))))
354 reason = "We don't both support linking to IPV6 servers";
355 if (((this->CapKeys.find("IP6NATIVE") != this->CapKeys.end()) && (this->CapKeys.find("IP6NATIVE")->second == "1")) && (!ip6support))
356 reason = "The remote server is IPV6 native, and we don't support linking to IPV6 servers";
357 if (((this->CapKeys.find("NICKMAX") == this->CapKeys.end()) || ((this->CapKeys.find("NICKMAX") != this->CapKeys.end()) && (this->CapKeys.find("NICKMAX")->second != ConvToStr(NICKMAX)))))
358 reason = "Maximum nickname lengths differ or remote nickname length not specified";
359 if (((this->CapKeys.find("PROTOCOL") == this->CapKeys.end()) || ((this->CapKeys.find("PROTOCOL") != this->CapKeys.end()) && (this->CapKeys.find("PROTOCOL")->second != ConvToStr(ProtocolVersion)))))
361 if (this->CapKeys.find("PROTOCOL") != this->CapKeys.end())
363 reason = "Mismatched protocol versions "+this->CapKeys.find("PROTOCOL")->second+" and "+ConvToStr(ProtocolVersion);
367 reason = "Protocol version not specified";
370 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))))
371 reason = "We don't both have halfop support enabled/disabled identically";
372 if (((this->CapKeys.find("IDENTMAX") == this->CapKeys.end()) || ((this->CapKeys.find("IDENTMAX") != this->CapKeys.end()) && (this->CapKeys.find("IDENTMAX")->second != ConvToStr(IDENTMAX)))))
373 reason = "Maximum ident lengths differ or remote ident length not specified";
374 if (((this->CapKeys.find("CHANMAX") == this->CapKeys.end()) || ((this->CapKeys.find("CHANMAX") != this->CapKeys.end()) && (this->CapKeys.find("CHANMAX")->second != ConvToStr(CHANMAX)))))
375 reason = "Maximum channel lengths differ or remote channel length not specified";
376 if (((this->CapKeys.find("MAXMODES") == this->CapKeys.end()) || ((this->CapKeys.find("MAXMODES") != this->CapKeys.end()) && (this->CapKeys.find("MAXMODES")->second != ConvToStr(MAXMODES)))))
377 reason = "Maximum modes per line differ or remote modes per line not specified";
378 if (((this->CapKeys.find("MAXQUIT") == this->CapKeys.end()) || ((this->CapKeys.find("MAXQUIT") != this->CapKeys.end()) && (this->CapKeys.find("MAXQUIT")->second != ConvToStr(MAXQUIT)))))
379 reason = "Maximum quit lengths differ or remote quit length not specified";
380 if (((this->CapKeys.find("MAXTOPIC") == this->CapKeys.end()) || ((this->CapKeys.find("MAXTOPIC") != this->CapKeys.end()) && (this->CapKeys.find("MAXTOPIC")->second != ConvToStr(MAXTOPIC)))))
381 reason = "Maximum topic lengths differ or remote topic length not specified";
382 if (((this->CapKeys.find("MAXKICK") == this->CapKeys.end()) || ((this->CapKeys.find("MAXKICK") != this->CapKeys.end()) && (this->CapKeys.find("MAXKICK")->second != ConvToStr(MAXKICK)))))
383 reason = "Maximum kick lengths differ or remote kick length not specified";
384 if (((this->CapKeys.find("MAXGECOS") == this->CapKeys.end()) || ((this->CapKeys.find("MAXGECOS") != this->CapKeys.end()) && (this->CapKeys.find("MAXGECOS")->second != ConvToStr(MAXGECOS)))))
385 reason = "Maximum GECOS (fullname) lengths differ or remote GECOS length not specified";
386 if (((this->CapKeys.find("MAXAWAY") == this->CapKeys.end()) || ((this->CapKeys.find("MAXAWAY") != this->CapKeys.end()) && (this->CapKeys.find("MAXAWAY")->second != ConvToStr(MAXAWAY)))))
387 reason = "Maximum awaymessage lengths differ or remote awaymessage length not specified";
389 /* Challenge response, store their challenge for our password */
390 std::map<std::string,std::string>::iterator n = this->CapKeys.find("CHALLENGE");
391 if (n != this->CapKeys.end())
393 /* Challenge-response is on now */
394 this->SetTheirChallenge(n->second);
399 this->WriteLine("ERROR :CAPAB negotiation failed: "+reason);
403 else if ((params[0] == "MODULES") && (params.size() == 2))
405 if (!this->ModuleList.length())
407 this->ModuleList.append(params[1]);
411 this->ModuleList.append(",");
412 this->ModuleList.append(params[1]);
416 else if ((params[0] == "CAPABILITIES") && (params.size() == 2))
418 irc::tokenstream capabs(params[1]);
421 while ((more = capabs.GetToken(item)))
423 /* Process each key/value pair */
424 std::string::size_type equals = item.rfind('=');
425 if (equals != std::string::npos)
427 std::string var = item.substr(0, equals);
428 std::string value = item.substr(equals+1, item.length());
429 CapKeys[var] = value;
436 /** This function forces this server to quit, removing this server
437 * and any users on it (and servers and users below that, etc etc).
438 * It's very slow and pretty clunky, but luckily unless your network
439 * is having a REAL bad hair day, this function shouldnt be called
440 * too many times a month ;-)
442 void TreeSocket::SquitServer(std::string &from, TreeServer* Current)
444 /* recursively squit the servers attached to 'Current'.
445 * We're going backwards so we don't remove users
446 * while we still need them ;)
448 for (unsigned int q = 0; q < Current->ChildCount(); q++)
450 TreeServer* recursive_server = Current->GetChild(q);
451 this->SquitServer(from,recursive_server);
453 /* Now we've whacked the kids, whack self */
455 num_lost_users += Current->QuitUsers(from);
458 /** This is a wrapper function for SquitServer above, which
459 * does some validation first and passes on the SQUIT to all
460 * other remaining servers.
462 void TreeSocket::Squit(TreeServer* Current, const std::string &reason)
464 if ((Current) && (Current != Utils->TreeRoot))
466 Event rmode((char*)Current->GetName().c_str(), (Module*)Utils->Creator, "lost_server");
467 rmode.Send(Instance);
469 std::deque<std::string> params;
470 params.push_back(Current->GetName());
471 params.push_back(":"+reason);
472 Utils->DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
473 if (Current->GetParent() == Utils->TreeRoot)
475 this->Instance->WriteOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
479 this->Instance->WriteOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
481 num_lost_servers = 0;
483 std::string from = Current->GetParent()->GetName()+" "+Current->GetName();
484 SquitServer(from, Current);
486 Current->GetParent()->DelChild(Current);
488 this->Instance->WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
492 Instance->Log(DEFAULT,"Squit from unknown server");
496 /** FMODE command - server mode with timestamp checks */
497 bool TreeSocket::ForceMode(const std::string &source, std::deque<std::string> ¶ms)
499 /* Chances are this is a 1.0 FMODE without TS */
500 if (params.size() < 3)
502 /* No modes were in the command, probably a channel with no modes set on it */
507 std::string sourceserv;
508 /* Are we dealing with an FMODE from a user, or from a server? */
509 userrec* who = this->Instance->FindNick(source);
512 /* FMODE from a user, set sourceserv to the users server name */
513 sourceserv = who->server;
517 /* FMODE from a server, create a fake user to receive mode feedback */
518 who = new userrec(this->Instance);
519 who->SetFd(FD_MAGIC_NUMBER);
520 smode = true; /* Setting this flag tells us we should free the userrec later */
521 sourceserv = source; /* Set sourceserv to the actual source string */
523 const char* modelist[64];
526 memset(&modelist,0,sizeof(modelist));
527 for (unsigned int q = 0; (q < params.size()) && (q < 64); q++)
531 /* The timestamp is in this position.
532 * We don't want to pass that up to the
533 * server->client protocol!
535 TS = atoi(params[q].c_str());
539 /* Everything else is fine to append to the modelist */
540 modelist[n++] = params[q].c_str();
544 /* Extract the TS value of the object, either userrec or chanrec */
545 userrec* dst = this->Instance->FindNick(params[0]);
546 chanrec* chan = NULL;
554 chan = this->Instance->FindChan(params[0]);
560 /* Oops, channel doesnt exist! */
564 /* TS is equal or less: Merge the mode changes into ours and pass on.
570 this->Instance->SendMode(modelist, n, who);
574 this->Instance->CallCommandHandler("MODE", modelist, n, who);
576 /* HOT POTATO! PASS IT ON! */
577 Utils->DoOneToAllButSender(source,"FMODE",params,sourceserv);
579 /* If the TS is greater than ours, we drop the mode and dont pass it anywhere.
588 /** FTOPIC command */
589 bool TreeSocket::ForceTopic(const std::string &source, std::deque<std::string> ¶ms)
591 if (params.size() != 4)
593 time_t ts = atoi(params[1].c_str());
594 std::string nsource = source;
595 chanrec* c = this->Instance->FindChan(params[0]);
598 if ((ts >= c->topicset) || (!*c->topic))
600 std::string oldtopic = c->topic;
601 strlcpy(c->topic,params[3].c_str(),MAXTOPIC);
602 strlcpy(c->setby,params[2].c_str(),127);
604 /* if the topic text is the same as the current topic,
605 * dont bother to send the TOPIC command out, just silently
606 * update the set time and set nick.
608 if (oldtopic != params[3])
610 userrec* user = this->Instance->FindNick(source);
613 c->WriteChannelWithServ(source.c_str(), "TOPIC %s :%s", c->name, c->topic);
617 c->WriteChannel(user, "TOPIC %s :%s", c->name, c->topic);
618 nsource = user->server;
620 /* all done, send it on its way */
621 params[3] = ":" + params[3];
622 Utils->DoOneToAllButSender(source,"FTOPIC",params,nsource);
630 /** FJOIN, similar to TS6 SJOIN, but not quite. */
631 bool TreeSocket::ForceJoin(const std::string &source, std::deque<std::string> ¶ms)
633 /* 1.1 FJOIN works as follows:
635 * Each FJOIN is sent along with a timestamp, and the side with the lowest
636 * timestamp 'wins'. From this point on we will refer to this side as the
637 * winner. The side with the higher timestamp loses, from this point on we
638 * will call this side the loser or losing side. This should be familiar to
639 * anyone who's dealt with dreamforge or TS6 before.
641 * When two sides of a split heal and this occurs, the following things
644 * If the timestamps are exactly equal, both sides merge their privilages
645 * and users, as in InspIRCd 1.0 and ircd2.8. The channels have not been
646 * re-created during a split, this is safe to do.
649 * If the timestamps are NOT equal, the losing side removes all privilage
650 * modes from all of its users that currently exist in the channel, before
651 * introducing new users into the channel which are listed in the FJOIN
652 * command's parameters. This means, all modes +ohv, and privilages added
653 * by modules, such as +qa. The losing side then LOWERS its timestamp value
654 * of the channel to match that of the winning side, and the modes of the
655 * users of the winning side are merged in with the losing side. The loser
656 * then sends out a set of FMODE commands which 'confirm' that it just
657 * removed all privilage modes from its existing users, which allows for
658 * services packages to still work correctly without needing to know the
659 * timestamping rules which InspIRCd follows. In TS6 servers this is always
660 * a problem, and services packages must contain code which explicitly
661 * behaves as TS6 does, removing ops from the losing side of a split where
662 * neccessary within its internal records, as this state information is
663 * not explicitly echoed out in that protocol.
665 * The winning side on the other hand will ignore all user modes from the
666 * losing side, so only its own modes get applied. Life is simple for those
667 * who succeed at internets. :-)
669 * NOTE: Unlike TS6 and dreamforge and other protocols which have SJOIN,
670 * FJOIN does not contain the simple-modes such as +iklmnsp. Why not,
671 * you ask? Well, quite simply because we don't need to. They'll be sent
672 * after the FJOIN by FMODE, and FMODE is timestamped, so in the event
673 * the losing side sends any modes for the channel which shouldnt win,
674 * they wont as their timestamp will be too high :-)
677 if (params.size() < 3)
680 char first[MAXBUF]; /* The first parameter of the mode command */
681 char modestring[MAXBUF]; /* The mode sequence (2nd parameter) of the mode command */
682 char* mode_users[127]; /* The values used by the mode command */
683 memset(&mode_users,0,sizeof(mode_users)); /* Initialize mode parameters */
684 mode_users[0] = first; /* Set this up to be our on-stack value */
685 mode_users[1] = modestring; /* Same here as above */
686 strcpy(modestring,"+"); /* Initialize the mode sequence to just '+' */
687 unsigned int modectr = 2; /* Pointer to the third mode parameter (e.g. the one after the +-sequence) */
689 userrec* who = NULL; /* User we are currently checking */
690 std::string channel = params[0]; /* Channel name, as a string */
691 time_t TS = atoi(params[1].c_str()); /* Timestamp given to us for remote side */
692 std::string nicklist = params[2];
693 bool created = false;
695 /* Try and find the channel */
696 chanrec* chan = this->Instance->FindChan(channel);
698 /* Initialize channel name in the mode parameters */
699 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
701 /* default TS is a high value, which if we dont have this
702 * channel will let the other side apply their modes.
704 time_t ourTS = Instance->Time(true)+600;
705 /* Does this channel exist? if it does, get its REAL timestamp */
709 created = true; /* don't perform deops, and set TS to correct time after processing. */
711 /* do this first, so our mode reversals are correctly received by other servers
712 * if there is a TS collision.
714 params[2] = ":" + params[2];
715 Utils->DoOneToAllButSender(source,"FJOIN",params,source);
717 /* In 1.1, if they have the newer channel, we immediately clear
718 * all status modes from our users. We then accept their modes.
719 * If WE have the newer channel its the other side's job to do this.
720 * Note that this causes the losing server to send out confirming
725 std::deque<std::string> param_list;
726 /* Lower the TS here */
727 if (Utils->AnnounceTSChange && chan)
728 chan->WriteChannelWithServ(Instance->Config->ServerName,
729 "NOTICE %s :TS for %s changed from %lu to %lu", chan->name, chan->name, ourTS, TS);
731 /* Zap all the privilage modes on our side, if the channel exists here */
734 param_list.push_back(channel);
737 this->RemoveStatus(Instance->Config->ServerName, param_list);
740 /* Put the final parameter of the FJOIN into a tokenstream ready to split it */
741 irc::tokenstream users(nicklist);
744 /* Now, process every 'prefixes,nick' pair */
745 while (users.GetToken(item))
748 const char* usr = item.c_str();
749 /* Safety check just to make sure someones not sent us an FJOIN full of spaces
750 * (is this even possible?) */
753 const char* permissions = usr;
755 char* nm = new char[MAXBUF];
757 /* Iterate through all the prefix values, convert them from prefixes
758 * to mode letters, and append them to the mode sequence
760 while ((*permissions) && (*permissions != ',') && (ntimes < MAXBUF))
762 ModeHandler* mh = Instance->Modes->FindPrefix(*permissions);
765 /* This is a valid prefix */
767 *tnm++ = mh->GetModeChar();
771 /* Not a valid prefix...
772 * danger bill bobbertson! (that's will robinsons older brother ;-) ...)
774 this->Instance->WriteOpers("ERROR: We received a user with an unknown prefix '%c'. Closed connection to avoid a desync.",*permissions);
775 this->WriteLine(std::string("ERROR :Invalid prefix '")+(*permissions)+"' in FJOIN");
781 /* Null terminate modes */
783 /* Advance past the comma, to the nick */
785 /* Check the user actually exists */
786 who = this->Instance->FindNick(usr);
789 /* Check that the user's 'direction' is correct
790 * based on the server sending the FJOIN. We must
791 * check each nickname in turn, because the origin of
792 * the FJOIN may be different to the origin of the nicks
793 * in the command itself.
795 TreeServer* route_back_again = Utils->BestRouteTo(who->server);
796 if ((!route_back_again) || (route_back_again->GetSocket() != this))
798 /* Oh dear oh dear. */
803 /* NOTE: Moved this below the fake direction check, so that modes
804 * arent put into the mode list for users that were collided, and
805 * may reconnect from the other side or our side before the split
809 /* Did they get any modes? How many times? */
810 strlcat(modestring, nm, MAXBUF);
811 for (int k = 0; k < ntimes; k++)
812 mode_users[modectr++] = strdup(usr);
813 /* Free temporary buffer used for mode sequence */
816 /* Finally, we can actually place the user into the channel.
817 * We're sure its right. Final answer, phone a friend.
820 chanrec::JoinUser(this->Instance, who, channel.c_str(), true, "", TS);
822 chanrec::JoinUser(this->Instance, who, channel.c_str(), true, "");
823 /* Have we already queued up MAXMODES modes with parameters
824 * (+qaohv) ready to be sent to the server?
826 if (modectr >= (MAXMODES-1))
828 /* Only actually give the users any status if we lost
829 * the FJOIN or drew (equal timestamps).
830 * It isn't actually possible for ourTS to be > TS here,
831 * only possible to actually have ourTS == TS, or
832 * ourTS < TS, because if we lost, we already lowered
833 * our TS above before we entered this loop. We only
834 * check >= as a safety measure, in case someone stuffed
835 * up. If someone DID stuff up, it was most likely me.
836 * Note: I do not like baseball bats in the face...
840 this->Instance->SendMode((const char**)mode_users,modectr,who);
842 /* Something stuffed up, and for some reason, the timestamp is
843 * NOT lowered right now and should be. Lower it. Usually this
844 * code won't be executed, doubtless someone will remove it some
849 Instance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",chan->name,ourTS,TS);
855 /* Reset all this back to defaults, and
856 * free any ram we have left allocated.
858 strcpy(mode_users[1],"+");
859 for (unsigned int f = 2; f < modectr; f++)
866 /* Remember to free this */
868 /* If we got here, there's a nick in FJOIN which doesnt exist on this server.
869 * We don't try to process the nickname here (that WOULD cause a segfault because
870 * we'd be playing with null pointers) however, we DO pass the nickname on, just
871 * in case somehow we're desynched, so that other users which might be able to see
872 * the nickname get their fair chance to process it.
874 Instance->Log(SPARSE,"Warning! Invalid user %s in FJOIN to channel %s IGNORED", usr, channel.c_str());
880 /* there werent enough modes built up to flush it during FJOIN,
881 * or, there are a number left over. flush them out.
883 if ((modectr > 2) && (who) && (chan))
887 /* Our channel is newer than theirs. Evil deeds must be afoot. */
888 this->Instance->SendMode((const char**)mode_users,modectr,who);
889 /* Yet again, we can't actually get a true value here, if everything else
890 * is working as it should.
894 Instance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",chan->name,ourTS,TS);
900 /* Free anything we have left to free */
901 for (unsigned int f = 2; f < modectr; f++)
904 /* All done. That wasnt so bad was it, you can wipe
905 * the sweat from your forehead now. :-)
911 bool TreeSocket::IntroduceClient(const std::string &source, std::deque<std::string> ¶ms)
913 /** Do we have enough parameters:
914 * NICK age nick host dhost ident +modes ip :gecos
916 if (params.size() != 8)
918 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[1]+"?)");
922 time_t age = atoi(params[0].c_str());
923 const char* tempnick = params[1].c_str();
925 /** Check parameters for validity before introducing the client, discovered by dmb.
926 * XXX: Can we make this neater?
930 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction (Invalid TS?)");
933 else if (params[1].length() > NICKMAX)
935 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[1]+" > NICKMAX?)");
938 else if (params[2].length() > 64)
940 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[2]+" > 64?)");
943 else if (params[3].length() > 64)
945 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[3]+" > 64?)");
948 else if (params[4].length() > IDENTMAX)
950 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[4]+" > IDENTMAX?)");
953 else if (params[7].length() > MAXGECOS)
955 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[7]+" > MAXGECOS?)");
959 /** Our client looks ok, lets introduce it now
961 Instance->Log(DEBUG,"New remote client %s",tempnick);
962 user_hash::iterator iter = this->Instance->clientlist->find(tempnick);
964 if (iter != this->Instance->clientlist->end())
967 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+tempnick+" :Nickname collision");
968 userrec::QuitUser(this->Instance, iter->second, "Nickname collision");
972 userrec* _new = new userrec(this->Instance);
973 (*(this->Instance->clientlist))[tempnick] = _new;
974 _new->SetFd(FD_MAGIC_NUMBER);
975 strlcpy(_new->nick, tempnick,NICKMAX-1);
976 strlcpy(_new->host, params[2].c_str(),63);
977 strlcpy(_new->dhost, params[3].c_str(),63);
978 _new->server = this->Instance->FindServerNamePtr(source.c_str());
979 strlcpy(_new->ident, params[4].c_str(),IDENTMAX);
980 strlcpy(_new->fullname, params[7].c_str(),MAXGECOS);
981 _new->registered = REG_ALL;
984 /* we need to remove the + from the modestring, so we can do our stuff */
985 std::string::size_type pos_after_plus = params[5].find_first_not_of('+');
986 if (pos_after_plus != std::string::npos)
987 params[5] = params[5].substr(pos_after_plus);
989 for (std::string::iterator v = params[5].begin(); v != params[5].end(); v++)
991 _new->modes[(*v)-65] = 1;
992 /* For each mode thats set, increase counter */
993 ModeHandler* mh = Instance->Modes->FindMode(*v, MODETYPE_USER);
998 /* now we've done with modes processing, put the + back for remote servers */
999 params[5] = "+" + params[5];
1001 #ifdef SUPPORT_IP6LINKS
1002 if (params[6].find_first_of(":") != std::string::npos)
1003 _new->SetSockAddr(AF_INET6, params[6].c_str(), 0);
1006 _new->SetSockAddr(AF_INET, params[6].c_str(), 0);
1008 Instance->AddGlobalClone(_new);
1010 if (!this->Instance->SilentULine(_new->server))
1011 this->Instance->SNO->WriteToSnoMask('C',"Client connecting at %s: %s!%s@%s [%s]",_new->server,_new->nick,_new->ident,_new->host, _new->GetIPString());
1013 params[7] = ":" + params[7];
1014 Utils->DoOneToAllButSender(source,"NICK", params, source);
1016 // Increment the Source Servers User Count..
1017 TreeServer* SourceServer = Utils->FindServer(source);
1020 SourceServer->AddUserCount();
1023 FOREACH_MOD_I(Instance,I_OnPostConnect,OnPostConnect(_new));
1028 /** Send one or more FJOINs for a channel of users.
1029 * If the length of a single line is more than 480-NICKMAX
1030 * in length, it is split over multiple lines.
1032 void TreeSocket::SendFJoins(TreeServer* Current, chanrec* c)
1036 std::string individual_halfops = std::string(":")+this->Instance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age);
1038 size_t dlen, curlen;
1039 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1041 char* ptr = list + dlen;
1043 CUList *ulist = c->GetUsers();
1044 std::string modes = "";
1045 std::string params = "";
1047 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1049 // The first parameter gets a : before it
1050 size_t ptrlen = snprintf(ptr, MAXBUF, " %s%s,%s", !numusers ? ":" : "", c->GetAllPrefixChars(i->second), i->second->nick);
1057 if (curlen > (480-NICKMAX))
1059 buffer.append(list).append("\r\n");
1060 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1068 buffer.append(list).append("\r\n");
1070 /* Sorry for the hax. Because newly created channels assume +nt,
1071 * if this channel doesnt have +nt, explicitly send -n and -t for the missing modes.
1073 bool inverted = false;
1074 if (!c->IsModeSet('n'))
1079 if (!c->IsModeSet('t'))
1089 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");
1092 for (BanList::iterator b = c->bans.begin(); b != c->bans.end(); b++)
1094 int size = strlen(b->data) + 2;
1095 int currsize = linesize + size;
1096 if (currsize <= 350)
1099 params.append(" ").append(b->data);
1102 if ((params.length() >= MAXMODES) || (currsize > 350))
1104 /* Wrap at MAXMODES */
1105 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");
1112 /* Only send these if there are any */
1114 buffer.append(":").append(this->Instance->Config->ServerName).append(" FMODE ").append(c->name).append(" ").append(ConvToStr(c->age)).append(" +").append(modes).append(params);
1116 this->WriteLine(buffer);
1119 /** Send G, Q, Z and E lines */
1120 void TreeSocket::SendXLines(TreeServer* Current)
1124 std::string n = this->Instance->Config->ServerName;
1125 const char* sn = n.c_str();
1126 /* Yes, these arent too nice looking, but they get the job done */
1127 for (std::vector<ZLine*>::iterator i = Instance->XLines->zlines.begin(); i != Instance->XLines->zlines.end(); i++)
1129 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);
1130 buffer.append(data);
1132 for (std::vector<QLine*>::iterator i = Instance->XLines->qlines.begin(); i != Instance->XLines->qlines.end(); i++)
1134 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);
1135 buffer.append(data);
1137 for (std::vector<GLine*>::iterator i = Instance->XLines->glines.begin(); i != Instance->XLines->glines.end(); i++)
1139 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);
1140 buffer.append(data);
1142 for (std::vector<ELine*>::iterator i = Instance->XLines->elines.begin(); i != Instance->XLines->elines.end(); i++)
1144 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);
1145 buffer.append(data);
1147 for (std::vector<ZLine*>::iterator i = Instance->XLines->pzlines.begin(); i != Instance->XLines->pzlines.end(); i++)
1149 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);
1150 buffer.append(data);
1152 for (std::vector<QLine*>::iterator i = Instance->XLines->pqlines.begin(); i != Instance->XLines->pqlines.end(); i++)
1154 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);
1155 buffer.append(data);
1157 for (std::vector<GLine*>::iterator i = Instance->XLines->pglines.begin(); i != Instance->XLines->pglines.end(); i++)
1159 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);
1160 buffer.append(data);
1162 for (std::vector<ELine*>::iterator i = Instance->XLines->pelines.begin(); i != Instance->XLines->pelines.end(); i++)
1164 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);
1165 buffer.append(data);
1168 if (!buffer.empty())
1169 this->WriteLine(buffer);
1172 /** Send channel modes and topics */
1173 void TreeSocket::SendChannelModes(TreeServer* Current)
1176 std::deque<std::string> list;
1177 std::string n = this->Instance->Config->ServerName;
1178 const char* sn = n.c_str();
1179 for (chan_hash::iterator c = this->Instance->chanlist->begin(); c != this->Instance->chanlist->end(); c++)
1181 SendFJoins(Current, c->second);
1182 if (*c->second->topic)
1184 snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",sn,c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
1185 this->WriteLine(data);
1187 FOREACH_MOD_I(this->Instance,I_OnSyncChannel,OnSyncChannel(c->second,(Module*)Utils->Creator,(void*)this));
1189 c->second->GetExtList(list);
1190 for (unsigned int j = 0; j < list.size(); j++)
1192 FOREACH_MOD_I(this->Instance,I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)Utils->Creator,(void*)this,list[j]));
1197 /** send all users and their oper state/modes */
1198 void TreeSocket::SendUsers(TreeServer* Current)
1201 std::deque<std::string> list;
1202 std::string dataline;
1203 for (user_hash::iterator u = this->Instance->clientlist->begin(); u != this->Instance->clientlist->end(); u++)
1205 if (u->second->registered == REG_ALL)
1207 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);
1208 this->WriteLine(data);
1209 if (*u->second->oper)
1211 snprintf(data,MAXBUF,":%s OPERTYPE %s", u->second->nick, u->second->oper);
1212 this->WriteLine(data);
1214 if (*u->second->awaymsg)
1216 snprintf(data,MAXBUF,":%s AWAY :%s", u->second->nick, u->second->awaymsg);
1217 this->WriteLine(data);
1219 FOREACH_MOD_I(this->Instance,I_OnSyncUser,OnSyncUser(u->second,(Module*)Utils->Creator,(void*)this));
1221 u->second->GetExtList(list);
1223 for (unsigned int j = 0; j < list.size(); j++)
1225 FOREACH_MOD_I(this->Instance,I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)Utils->Creator,(void*)this,list[j]));
1231 /** This function is called when we want to send a netburst to a local
1232 * server. There is a set order we must do this, because for example
1233 * users require their servers to exist, and channels require their
1234 * users to exist. You get the idea.
1236 void TreeSocket::DoBurst(TreeServer* s)
1238 std::string burst = "BURST "+ConvToStr(Instance->Time(true));
1239 std::string endburst = "ENDBURST";
1240 // Because by the end of the netburst, it could be gone!
1241 std::string name = s->GetName();
1242 this->Instance->SNO->WriteToSnoMask('l',"Bursting to \2"+name+"\2.");
1243 this->WriteLine(burst);
1244 /* send our version string */
1245 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" VERSION :"+this->Instance->GetVersionString());
1246 /* Send server tree */
1247 this->SendServers(Utils->TreeRoot,s,1);
1248 /* Send users and their oper status */
1250 /* Send everything else (channel modes, xlines etc) */
1251 this->SendChannelModes(s);
1252 this->SendXLines(s);
1253 FOREACH_MOD_I(this->Instance,I_OnSyncOtherMetaData,OnSyncOtherMetaData((Module*)Utils->Creator,(void*)this));
1254 this->WriteLine(endburst);
1255 this->Instance->SNO->WriteToSnoMask('l',"Finished bursting to \2"+name+"\2.");
1258 /** This function is called when we receive data from a remote
1259 * server. We buffer the data in a std::string (it doesnt stay
1260 * there for long), reading using InspSocket::Read() which can
1261 * read up to 16 kilobytes in one operation.
1263 * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
1264 * THE SOCKET OBJECT FOR US.
1266 bool TreeSocket::OnDataReady()
1268 char* data = this->Read();
1269 /* Check that the data read is a valid pointer and it has some content */
1272 this->in_buffer.append(data);
1273 /* While there is at least one new line in the buffer,
1274 * do something useful (we hope!) with it.
1276 while (in_buffer.find("\n") != std::string::npos)
1278 std::string ret = in_buffer.substr(0,in_buffer.find("\n")-1);
1279 in_buffer = in_buffer.substr(in_buffer.find("\n")+1,in_buffer.length()-in_buffer.find("\n"));
1280 /* Use rfind here not find, as theres more
1281 * chance of the \r being near the end of the
1282 * string, not the start.
1284 if (ret.find("\r") != std::string::npos)
1285 ret = in_buffer.substr(0,in_buffer.find("\r")-1);
1286 /* Process this one, abort if it
1287 * didnt return true.
1289 if (!this->ProcessLine(ret))
1296 /* EAGAIN returns an empty but non-NULL string, so this
1297 * evaluates to TRUE for EAGAIN but to FALSE for EOF.
1299 return (data && !*data);