1 #include "configreader.h"
5 #include "commands/cmd_whois.h"
6 #include "commands/cmd_stats.h"
11 #include "transport.h"
12 #include "socketengine.h"
14 #include "m_spanningtree/main.h"
15 #include "m_spanningtree/utils.h"
16 #include "m_spanningtree/treeserver.h"
17 #include "m_spanningtree/link.h"
18 #include "m_spanningtree/treesocket.h"
19 #include "m_spanningtree/resolvers.h"
20 #include "m_spanningtree/handshaketimer.h"
22 /* $ModDep: m_spanningtree/timesynctimer.h m_spanningtree/resolvers.h m_spanningtree/main.h m_spanningtree/utils.h m_spanningtree/treeserver.h m_spanningtree/link.h m_spanningtree/treesocket.h */
24 /** Because most of the I/O gubbins are encapsulated within
25 * InspSocket, we just call the superclass constructor for
26 * most of the action, and append a few of our own values
29 TreeSocket::TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime, Module* HookMod)
30 : InspSocket(SI, host, port, listening, maxtime), Utils(Util), Hook(HookMod)
33 this->LinkState = LISTENER;
34 if (listening && Hook)
35 InspSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
38 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)
39 : InspSocket(SI, host, port, listening, maxtime, bindto), Utils(Util), Hook(HookMod)
42 this->LinkState = CONNECTING;
44 InspSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
47 /** When a listening socket gives us a new file descriptor,
48 * we must associate it with a socket without creating a new
49 * connection. This constructor is used for this purpose.
51 TreeSocket::TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, int newfd, char* ip, Module* HookMod)
52 : InspSocket(SI, newfd, ip), Utils(Util), Hook(HookMod)
54 this->LinkState = WAIT_AUTH_1;
55 /* If we have a transport module hooked to the parent, hook the same module to this
56 * socket, and set a timer waiting for handshake before we send CAPAB etc.
60 InspSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
61 Instance->Timers->AddTimer(new HandshakeTimer(Instance, this, &(Utils->LinkBlocks[0]), this->Utils));
65 /* Otherwise, theres no lower layer transport in plain TCP/IP,
66 * so just send the capabilities right now.
68 this->SendCapabilities();
72 ServerState TreeSocket::GetLinkState()
74 return this->LinkState;
77 Module* TreeSocket::GetHook()
82 TreeSocket::~TreeSocket()
85 InspSocketUnhookRequest(this, (Module*)Utils->Creator, Hook).Send();
88 /** When an outbound connection finishes connecting, we receive
89 * this event, and must send our SERVER string to the other
90 * side. If the other side is happy, as outlined in the server
91 * to server docs on the inspircd.org site, the other side
92 * will then send back its own server string.
94 bool TreeSocket::OnConnected()
96 if (this->LinkState == CONNECTING)
98 /* we do not need to change state here. */
99 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
101 if (x->Name == this->myhost)
103 this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] started.");
106 InspSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
107 this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] using transport \2"+x->Hook+"\2");
110 this->SendCapabilities();
111 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
113 Instance->Timers->AddTimer(new HandshakeTimer(Instance, this, &(*x), this->Utils));
115 this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+x->SendPass+" 0 :"+this->Instance->Config->ServerDesc);
120 /* There is a (remote) chance that between the /CONNECT and the connection
121 * being accepted, some muppet has removed the <link> block and rehashed.
122 * If that happens the connection hangs here until it's closed. Unlikely
123 * and rather harmless.
125 this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2 lost link tag(!)");
129 void TreeSocket::OnError(InspSocketError e)
131 /* We don't handle this method, because all our
132 * dirty work is done in OnClose() (see below)
133 * which is still called on error conditions too.
135 if (e == I_ERR_CONNECT)
137 this->Instance->SNO->WriteToSnoMask('l',"Connection failed: Connection to \002"+myhost+"\002 refused");
138 Link* MyLink = Utils->FindLink(myhost);
140 Utils->DoFailOver(MyLink);
144 int TreeSocket::OnDisconnect()
146 /* For the same reason as above, we don't
147 * handle OnDisconnect()
152 /** Recursively send the server tree with distances as hops.
153 * This is used during network burst to inform the other server
154 * (and any of ITS servers too) of what servers we know about.
155 * If at any point any of these servers already exist on the other
156 * end, our connection may be terminated. The hopcounts given
157 * by this function are relative, this doesn't matter so long as
158 * they are all >1, as all the remote servers re-calculate them
159 * to be relative too, with themselves as hop 0.
161 void TreeSocket::SendServers(TreeServer* Current, TreeServer* s, int hops)
164 for (unsigned int q = 0; q < Current->ChildCount(); q++)
166 TreeServer* recursive_server = Current->GetChild(q);
167 if (recursive_server != s)
169 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
170 this->WriteLine(command);
171 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
172 /* down to next level */
173 this->SendServers(recursive_server, s, hops+1);
178 std::string TreeSocket::MyCapabilities()
180 std::vector<std::string> modlist;
181 std::string capabilities = "";
182 for (int i = 0; i <= this->Instance->GetModuleCount(); i++)
184 if (this->Instance->modules[i]->GetVersion().Flags & VF_COMMON)
185 modlist.push_back(this->Instance->Config->module_names[i]);
187 sort(modlist.begin(),modlist.end());
188 for (unsigned int i = 0; i < modlist.size(); i++)
191 capabilities = capabilities + ",";
192 capabilities = capabilities + modlist[i];
197 void TreeSocket::SendCapabilities()
199 irc::commasepstream modulelist(MyCapabilities());
200 this->WriteLine("CAPAB START");
202 /* Send module names, split at 509 length */
203 std::string item = "*";
204 std::string line = "CAPAB MODULES ";
205 while ((item = modulelist.GetToken()) != "")
207 if (line.length() + item.length() + 1 > 509)
209 this->WriteLine(line);
210 line = "CAPAB MODULES ";
213 if (line != "CAPAB MODULES ")
218 if (line != "CAPAB MODULES ")
219 this->WriteLine(line);
226 #ifdef SUPPORT_IP6LINKS
229 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));
231 this->WriteLine("CAPAB END");
234 /* Check a comma seperated list for an item */
235 bool TreeSocket::HasItem(const std::string &list, const std::string &item)
237 irc::commasepstream seplist(list);
238 std::string item2 = "*";
239 while ((item2 = seplist.GetToken()) != "")
247 /* Isolate and return the elements that are different between two comma seperated lists */
248 std::string TreeSocket::ListDifference(const std::string &one, const std::string &two)
250 irc::commasepstream list_one(one);
251 std::string item = "*";
252 std::string result = "";
253 while ((item = list_one.GetToken()) != "")
255 if (!HasItem(two, item))
264 bool TreeSocket::Capab(const std::deque<std::string> ¶ms)
266 if (params.size() < 1)
268 this->WriteLine("ERROR :Invalid number of parameters for CAPAB - Mismatched version");
271 if (params[0] == "START")
273 this->ModuleList = "";
274 this->CapKeys.clear();
276 else if (params[0] == "END")
278 std::string reason = "";
280 #ifdef SUPPORT_IP6LINKS
283 /* Compare ModuleList and check CapKeys...
284 * Maybe this could be tidier? -- Brain
286 if ((this->ModuleList != this->MyCapabilities()) && (this->ModuleList.length()))
288 std::string diff = ListDifference(this->ModuleList, this->MyCapabilities());
291 diff = "your server:" + ListDifference(this->MyCapabilities(), this->ModuleList);
295 diff = "this server:" + diff;
297 if (diff.length() == 12)
298 reason = "Module list in CAPAB is not alphabetically ordered, cannot compare lists.";
300 reason = "Modules loaded on these servers are not correctly matched, these modules are not loaded on " + diff;
302 if (((this->CapKeys.find("IP6SUPPORT") == this->CapKeys.end()) && (ip6support)) || ((this->CapKeys.find("IP6SUPPORT") != this->CapKeys.end()) && (this->CapKeys.find("IP6SUPPORT")->second != ConvToStr(ip6support))))
303 reason = "We don't both support linking to IPV6 servers";
304 if (((this->CapKeys.find("IP6NATIVE") != this->CapKeys.end()) && (this->CapKeys.find("IP6NATIVE")->second == "1")) && (!ip6support))
305 reason = "The remote server is IPV6 native, and we don't support linking to IPV6 servers";
306 if (((this->CapKeys.find("NICKMAX") == this->CapKeys.end()) || ((this->CapKeys.find("NICKMAX") != this->CapKeys.end()) && (this->CapKeys.find("NICKMAX")->second != ConvToStr(NICKMAX)))))
307 reason = "Maximum nickname lengths differ or remote nickname length not specified";
308 if (((this->CapKeys.find("PROTOCOL") == this->CapKeys.end()) || ((this->CapKeys.find("PROTOCOL") != this->CapKeys.end()) && (this->CapKeys.find("PROTOCOL")->second != ConvToStr(ProtocolVersion)))))
310 if (this->CapKeys.find("PROTOCOL") != this->CapKeys.end())
312 reason = "Mismatched protocol versions "+this->CapKeys.find("PROTOCOL")->second+" and "+ConvToStr(ProtocolVersion);
316 reason = "Protocol version not specified";
319 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))))
320 reason = "We don't both have halfop support enabled/disabled identically";
321 if (((this->CapKeys.find("IDENTMAX") == this->CapKeys.end()) || ((this->CapKeys.find("IDENTMAX") != this->CapKeys.end()) && (this->CapKeys.find("IDENTMAX")->second != ConvToStr(IDENTMAX)))))
322 reason = "Maximum ident lengths differ or remote ident length not specified";
323 if (((this->CapKeys.find("CHANMAX") == this->CapKeys.end()) || ((this->CapKeys.find("CHANMAX") != this->CapKeys.end()) && (this->CapKeys.find("CHANMAX")->second != ConvToStr(CHANMAX)))))
324 reason = "Maximum channel lengths differ or remote channel length not specified";
325 if (((this->CapKeys.find("MAXMODES") == this->CapKeys.end()) || ((this->CapKeys.find("MAXMODES") != this->CapKeys.end()) && (this->CapKeys.find("MAXMODES")->second != ConvToStr(MAXMODES)))))
326 reason = "Maximum modes per line differ or remote modes per line not specified";
327 if (((this->CapKeys.find("MAXQUIT") == this->CapKeys.end()) || ((this->CapKeys.find("MAXQUIT") != this->CapKeys.end()) && (this->CapKeys.find("MAXQUIT")->second != ConvToStr(MAXQUIT)))))
328 reason = "Maximum quit lengths differ or remote quit length not specified";
329 if (((this->CapKeys.find("MAXTOPIC") == this->CapKeys.end()) || ((this->CapKeys.find("MAXTOPIC") != this->CapKeys.end()) && (this->CapKeys.find("MAXTOPIC")->second != ConvToStr(MAXTOPIC)))))
330 reason = "Maximum topic lengths differ or remote topic length not specified";
331 if (((this->CapKeys.find("MAXKICK") == this->CapKeys.end()) || ((this->CapKeys.find("MAXKICK") != this->CapKeys.end()) && (this->CapKeys.find("MAXKICK")->second != ConvToStr(MAXKICK)))))
332 reason = "Maximum kick lengths differ or remote kick length not specified";
333 if (((this->CapKeys.find("MAXGECOS") == this->CapKeys.end()) || ((this->CapKeys.find("MAXGECOS") != this->CapKeys.end()) && (this->CapKeys.find("MAXGECOS")->second != ConvToStr(MAXGECOS)))))
334 reason = "Maximum GECOS (fullname) lengths differ or remote GECOS length not specified";
335 if (((this->CapKeys.find("MAXAWAY") == this->CapKeys.end()) || ((this->CapKeys.find("MAXAWAY") != this->CapKeys.end()) && (this->CapKeys.find("MAXAWAY")->second != ConvToStr(MAXAWAY)))))
336 reason = "Maximum awaymessage lengths differ or remote awaymessage length not specified";
339 this->WriteLine("ERROR :CAPAB negotiation failed: "+reason);
343 else if ((params[0] == "MODULES") && (params.size() == 2))
345 if (!this->ModuleList.length())
347 this->ModuleList.append(params[1]);
351 this->ModuleList.append(",");
352 this->ModuleList.append(params[1]);
356 else if ((params[0] == "CAPABILITIES") && (params.size() == 2))
358 irc::tokenstream capabs(params[1]);
359 std::string item = "*";
360 while ((item = capabs.GetToken()) != "")
362 /* Process each key/value pair */
363 std::string::size_type equals = item.rfind('=');
364 if (equals != std::string::npos)
366 std::string var = item.substr(0, equals);
367 std::string value = item.substr(equals+1, item.length());
368 CapKeys[var] = value;
375 /** This function forces this server to quit, removing this server
376 * and any users on it (and servers and users below that, etc etc).
377 * It's very slow and pretty clunky, but luckily unless your network
378 * is having a REAL bad hair day, this function shouldnt be called
379 * too many times a month ;-)
381 void TreeSocket::SquitServer(std::string &from, TreeServer* Current)
383 /* recursively squit the servers attached to 'Current'.
384 * We're going backwards so we don't remove users
385 * while we still need them ;)
387 for (unsigned int q = 0; q < Current->ChildCount(); q++)
389 TreeServer* recursive_server = Current->GetChild(q);
390 this->SquitServer(from,recursive_server);
392 /* Now we've whacked the kids, whack self */
394 num_lost_users += Current->QuitUsers(from);
397 /** This is a wrapper function for SquitServer above, which
398 * does some validation first and passes on the SQUIT to all
399 * other remaining servers.
401 void TreeSocket::Squit(TreeServer* Current, const std::string &reason)
403 if ((Current) && (Current != Utils->TreeRoot))
405 Event rmode((char*)Current->GetName().c_str(), (Module*)Utils->Creator, "lost_server");
406 rmode.Send(Instance);
408 std::deque<std::string> params;
409 params.push_back(Current->GetName());
410 params.push_back(":"+reason);
411 Utils->DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
412 if (Current->GetParent() == Utils->TreeRoot)
414 this->Instance->WriteOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
418 this->Instance->WriteOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
420 num_lost_servers = 0;
422 std::string from = Current->GetParent()->GetName()+" "+Current->GetName();
423 SquitServer(from, Current);
425 Current->GetParent()->DelChild(Current);
427 this->Instance->WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
431 Instance->Log(DEFAULT,"Squit from unknown server");
435 /** FMODE command - server mode with timestamp checks */
436 bool TreeSocket::ForceMode(const std::string &source, std::deque<std::string> ¶ms)
438 /* Chances are this is a 1.0 FMODE without TS */
439 if (params.size() < 3)
441 /* No modes were in the command, probably a channel with no modes set on it */
446 std::string sourceserv;
447 /* Are we dealing with an FMODE from a user, or from a server? */
448 userrec* who = this->Instance->FindNick(source);
451 /* FMODE from a user, set sourceserv to the users server name */
452 sourceserv = who->server;
456 /* FMODE from a server, create a fake user to receive mode feedback */
457 who = new userrec(this->Instance);
458 who->SetFd(FD_MAGIC_NUMBER);
459 smode = true; /* Setting this flag tells us we should free the userrec later */
460 sourceserv = source; /* Set sourceserv to the actual source string */
462 const char* modelist[64];
465 memset(&modelist,0,sizeof(modelist));
466 for (unsigned int q = 0; (q < params.size()) && (q < 64); q++)
470 /* The timestamp is in this position.
471 * We don't want to pass that up to the
472 * server->client protocol!
474 TS = atoi(params[q].c_str());
478 /* Everything else is fine to append to the modelist */
479 modelist[n++] = params[q].c_str();
483 /* Extract the TS value of the object, either userrec or chanrec */
484 userrec* dst = this->Instance->FindNick(params[0]);
485 chanrec* chan = NULL;
493 chan = this->Instance->FindChan(params[0]);
499 /* Oops, channel doesnt exist! */
503 /* TS is equal: Merge the mode changes, use voooodoooooo on modes
508 ModeHandler* mh = NULL;
509 unsigned long paramptr = 3;
510 std::string to_bounce = "";
511 std::string to_keep = "";
512 std::vector<std::string> params_to_keep;
513 std::string params_to_bounce = "";
517 char old_bounce_change = 0;
518 /* Merge modes, basically do special stuff to mode with params */
519 for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
532 /* We only care about whats being set,
533 * not whats being unset
535 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
536 if ((mh) && (mh->GetNumParams(adding) > 0) && (!mh->IsListMode()))
538 /* We only want to do special things to
539 * modes with parameters, we are going to rewrite
543 adding ? cur_change = '+' : cur_change = '-';
544 ret = mh->ModeSet(smode ? NULL : who, dst, chan, params[paramptr]);
545 /* The mode is set here, check which we should keep */
548 bool which_to_keep = mh->CheckTimeStamp(TS, ourTS, params[paramptr], ret.second, chan);
549 if (which_to_keep == true)
551 /* Keep ours, bounce theirs:
552 * Send back ours to them and
553 * drop their mode changs
555 adding ? cur_change = '+' : cur_change = '-';
556 if (cur_change != old_bounce_change)
557 to_bounce += cur_change;
559 old_bounce_change = cur_change;
560 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
561 params_to_bounce.append(" ").append(ret.second);
565 /* Keep theirs: Accept their mode change,
568 adding ? cur_change = '+' : cur_change = '-';
569 if (cur_change != old_change)
570 to_keep += cur_change;
572 old_change = cur_change;
573 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
574 params_to_keep.push_back(params[paramptr]);
579 /* Mode isnt set here, we want it */
580 adding ? cur_change = '+' : cur_change = '-';
581 if (cur_change != old_change)
582 to_keep += cur_change;
584 old_change = cur_change;
585 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
586 params_to_keep.push_back(params[paramptr]);
592 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
595 adding ? cur_change = '+' : cur_change = '-';
597 /* Just keep this, safe to merge with no checks
598 * it has no parameters
601 if (cur_change != old_change)
602 to_keep += cur_change;
604 old_change = cur_change;
606 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
608 params_to_keep.push_back(params[paramptr++]);
615 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
618 /* Taking a mode away */
619 adding ? cur_change = '+' : cur_change = '-';
620 if (cur_change != old_change)
621 to_keep += cur_change;
623 old_change = cur_change;
624 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
625 params_to_keep.push_back(params[paramptr++]);
631 if (to_bounce.length())
633 std::deque<std::string> newparams;
634 newparams.push_back(params[0]);
635 newparams.push_back(ConvToStr(ourTS));
636 newparams.push_back(to_bounce+params_to_bounce);
637 Utils->DoOneToOne(this->Instance->Config->ServerName,"FMODE",newparams,sourceserv);
639 if (to_keep.length())
643 modelist[0] = params[0].c_str();
644 modelist[1] = to_keep.c_str();
645 if (params_to_keep.size() > 0)
647 for (q = 0; (q < params_to_keep.size()) && (q < 64); q++)
649 modelist[n++] = params_to_keep[q].c_str();
654 this->Instance->SendMode(modelist, n, who);
658 this->Instance->CallCommandHandler("MODE", modelist, n, who);
660 /* HOT POTATO! PASS IT ON! */
661 Utils->DoOneToAllButSender(source,"FMODE",params,sourceserv);
665 /* U-lined servers always win regardless of their TS */
668 /* Bounce the mode back to its sender.* We use our lower TS, so the other end
669 * SHOULD accept it, if its clock is right.
671 * NOTE: We should check that we arent bouncing anything thats already set at this end.
672 * If we are, bounce +ourmode to 'reinforce' it. This prevents desyncs.
673 * e.g. They send +l 50, we have +l 10 set. rather than bounce -l 50, we bounce +l 10.
675 * Thanks to jilles for pointing out this one-hell-of-an-issue before i even finished
676 * writing the code. It took me a while to come up with this solution.
678 * XXX: BE SURE YOU UNDERSTAND THIS CODE FULLY BEFORE YOU MESS WITH IT.
680 std::deque<std::string> newparams; /* New parameter list we send back */
681 newparams.push_back(params[0]); /* Target, user or channel */
682 newparams.push_back(ConvToStr(ourTS)); /* Timestamp value of the target */
683 newparams.push_back(""); /* This contains the mode string. For now
684 * it's empty, we fill it below.
686 /* Intelligent mode bouncing. Don't just invert, reinforce any modes which are already
687 * set to avoid a desync here.
689 std::string modebounce = "";
692 ModeHandler* mh = NULL;
695 for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
697 /* Iterate over all mode chars in the sent set */
700 /* Adding or subtracting modes? */
708 /* Find the mode handler for this mode */
709 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
710 /* Got a mode handler?
711 * This also prevents us bouncing modes we have no handler for.
717 /* Does the mode require a parameter right now?
718 * If it does, fetch it if we can
720 if ((mh->GetNumParams(adding) > 0) && (t < params.size()))
722 /* Call the ModeSet method to determine if its set with the
723 * given parameter here or not.
725 ret = mh->ModeSet(smode ? NULL : who, dst, chan, p);
726 /* XXX: Really. Dont ask.
727 * Determine from if its set combined with what the current
728 * 'state' is (adding or not) as to wether we should 'invert'
729 * or 'reinforce' the mode change
731 (!ret.first ? (adding ? cur_change = '-' : cur_change = '+') : (!adding ? cur_change = '-' : cur_change = '+'));
732 /* Quickly determine if we have 'flipped' from + to -,
733 * or - to +, to prevent unneccessary +/- chars in the
734 * output string that waste bandwidth
736 if (cur_change != old_change)
737 modebounce += cur_change;
738 old_change = cur_change;
739 /* Add the mode character to the output string */
740 modebounce += mh->GetModeChar();
741 /* We got a parameter back from ModeHandler::ModeSet,
742 * are we supposed to be sending one out right now?
744 if (ret.second.length())
746 if (mh->GetNumParams(cur_change == '+') > 0)
747 /* Yes we're supposed to be sending out
748 * the parameter. Make sure it goes
750 newparams.push_back(ret.second);
757 /* Update the parameters for FMODE with the new 'bounced' string */
758 newparams[2] = modebounce;
759 /* Only send it back the way it came, no need to send it anywhere else */
760 Utils->DoOneToOne(this->Instance->Config->ServerName,"FMODE",newparams,sourceserv);
764 /* Allow the mode, route it to either server or user command handling */
766 this->Instance->SendMode(modelist,n,who);
768 this->Instance->CallCommandHandler("MODE", modelist, n, who);
769 /* HOT POTATO! PASS IT ON! */
770 Utils->DoOneToAllButSender(source,"FMODE",params,sourceserv);
772 /* Are we supposed to free the userrec? */
779 /** FTOPIC command */
780 bool TreeSocket::ForceTopic(const std::string &source, std::deque<std::string> ¶ms)
782 if (params.size() != 4)
784 time_t ts = atoi(params[1].c_str());
785 std::string nsource = source;
786 chanrec* c = this->Instance->FindChan(params[0]);
789 if ((ts >= c->topicset) || (!*c->topic))
791 std::string oldtopic = c->topic;
792 strlcpy(c->topic,params[3].c_str(),MAXTOPIC);
793 strlcpy(c->setby,params[2].c_str(),127);
795 /* if the topic text is the same as the current topic,
796 * dont bother to send the TOPIC command out, just silently
797 * update the set time and set nick.
799 if (oldtopic != params[3])
801 userrec* user = this->Instance->FindNick(source);
804 c->WriteChannelWithServ(source.c_str(), "TOPIC %s :%s", c->name, c->topic);
808 c->WriteChannel(user, "TOPIC %s :%s", c->name, c->topic);
809 nsource = user->server;
811 /* all done, send it on its way */
812 params[3] = ":" + params[3];
813 Utils->DoOneToAllButSender(source,"FTOPIC",params,nsource);
821 /** FJOIN, similar to TS6 SJOIN, but not quite. */
822 bool TreeSocket::ForceJoin(const std::string &source, std::deque<std::string> ¶ms)
824 /* 1.1 FJOIN works as follows:
826 * Each FJOIN is sent along with a timestamp, and the side with the lowest
827 * timestamp 'wins'. From this point on we will refer to this side as the
828 * winner. The side with the higher timestamp loses, from this point on we
829 * will call this side the loser or losing side. This should be familiar to
830 * anyone who's dealt with dreamforge or TS6 before.
832 * When two sides of a split heal and this occurs, the following things
835 * If the timestamps are exactly equal, both sides merge their privilages
836 * and users, as in InspIRCd 1.0 and ircd2.8. The channels have not been
837 * re-created during a split, this is safe to do.
840 * If the timestamps are NOT equal, the losing side removes all privilage
841 * modes from all of its users that currently exist in the channel, before
842 * introducing new users into the channel which are listed in the FJOIN
843 * command's parameters. This means, all modes +ohv, and privilages added
844 * by modules, such as +qa. The losing side then LOWERS its timestamp value
845 * of the channel to match that of the winning side, and the modes of the
846 * users of the winning side are merged in with the losing side. The loser
847 * then sends out a set of FMODE commands which 'confirm' that it just
848 * removed all privilage modes from its existing users, which allows for
849 * services packages to still work correctly without needing to know the
850 * timestamping rules which InspIRCd follows. In TS6 servers this is always
851 * a problem, and services packages must contain code which explicitly
852 * behaves as TS6 does, removing ops from the losing side of a split where
853 * neccessary within its internal records, as this state information is
854 * not explicitly echoed out in that protocol.
856 * The winning side on the other hand will ignore all user modes from the
857 * losing side, so only its own modes get applied. Life is simple for those
858 * who succeed at internets. :-)
860 * NOTE: Unlike TS6 and dreamforge and other protocols which have SJOIN,
861 * FJOIN does not contain the simple-modes such as +iklmnsp. Why not,
862 * you ask? Well, quite simply because we don't need to. They'll be sent
863 * after the FJOIN by FMODE, and FMODE is timestamped, so in the event
864 * the losing side sends any modes for the channel which shouldnt win,
865 * they wont as their timestamp will be too high :-)
868 if (params.size() < 3)
871 char first[MAXBUF]; /* The first parameter of the mode command */
872 char modestring[MAXBUF]; /* The mode sequence (2nd parameter) of the mode command */
873 char* mode_users[127]; /* The values used by the mode command */
874 memset(&mode_users,0,sizeof(mode_users)); /* Initialize mode parameters */
875 mode_users[0] = first; /* Set this up to be our on-stack value */
876 mode_users[1] = modestring; /* Same here as above */
877 strcpy(modestring,"+"); /* Initialize the mode sequence to just '+' */
878 unsigned int modectr = 2; /* Pointer to the third mode parameter (e.g. the one after the +-sequence) */
880 userrec* who = NULL; /* User we are currently checking */
881 std::string channel = params[0]; /* Channel name, as a string */
882 time_t TS = atoi(params[1].c_str()); /* Timestamp given to us for remote side */
883 bool created = false;
885 /* Try and find the channel */
886 chanrec* chan = this->Instance->FindChan(channel);
888 /* Initialize channel name in the mode parameters */
889 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
891 /* default TS is a high value, which if we dont have this
892 * channel will let the other side apply their modes.
894 time_t ourTS = Instance->Time(true)+600;
895 /* Does this channel exist? if it does, get its REAL timestamp */
899 created = true; /* don't perform deops, and set TS to correct time after processing. */
900 /* In 1.1, if they have the newer channel, we immediately clear
901 * all status modes from our users. We then accept their modes.
902 * If WE have the newer channel its the other side's job to do this.
903 * Note that this causes the losing server to send out confirming
908 std::deque<std::string> param_list;
909 /* Lower the TS here */
910 if (Utils->AnnounceTSChange && chan)
911 chan->WriteChannelWithServ(Instance->Config->ServerName,
912 "NOTICE %s :TS for %s changed from %lu to %lu", chan->name, chan->name, ourTS, TS);
914 /* Zap all the privilage modes on our side, if the channel exists here */
917 param_list.push_back(channel);
920 this->RemoveStatus(Instance->Config->ServerName, param_list);
923 /* Put the final parameter of the FJOIN into a tokenstream ready to split it */
924 irc::tokenstream users(params[2]);
925 std::string item = "*";
926 /* do this first, so our mode reversals are correctly received by other servers
927 * if there is a TS collision.
929 params[2] = ":" + params[2];
930 Utils->DoOneToAllButSender(source,"FJOIN",params,source);
931 /* Now, process every 'prefixes,nick' pair */
935 item = users.GetToken();
936 const char* usr = item.c_str();
937 /* Safety check just to make sure someones not sent us an FJOIN full of spaces
938 * (is this even possible?) */
941 const char* permissions = usr;
943 char* nm = new char[MAXBUF];
945 /* Iterate through all the prefix values, convert them from prefixes
946 * to mode letters, and append them to the mode sequence
948 while ((*permissions) && (*permissions != ',') && (ntimes < MAXBUF))
950 ModeHandler* mh = Instance->Modes->FindPrefix(*permissions);
953 /* This is a valid prefix */
955 *tnm++ = mh->GetModeChar();
959 /* Not a valid prefix...
960 * danger bill bobbertson! (that's will robinsons older brother ;-) ...)
962 this->Instance->WriteOpers("ERROR: We received a user with an unknown prefix '%c'. Closed connection to avoid a desync.",*permissions);
963 this->WriteLine(std::string("ERROR :Invalid prefix '")+(*permissions)+"' in FJOIN");
969 /* Null terminate modes */
971 /* Advance past the comma, to the nick */
973 /* Check the user actually exists */
974 who = this->Instance->FindNick(usr);
977 /* Check that the user's 'direction' is correct
978 * based on the server sending the FJOIN. We must
979 * check each nickname in turn, because the origin of
980 * the FJOIN may be different to the origin of the nicks
981 * in the command itself.
983 TreeServer* route_back_again = Utils->BestRouteTo(who->server);
984 if ((!route_back_again) || (route_back_again->GetSocket() != this))
986 /* Oh dear oh dear. */
991 /* NOTE: Moved this below the fake direction check, so that modes
992 * arent put into the mode list for users that were collided, and
993 * may reconnect from the other side or our side before the split
997 /* Did they get any modes? How many times? */
998 strlcat(modestring, nm, MAXBUF);
999 for (int k = 0; k < ntimes; k++)
1000 mode_users[modectr++] = strdup(usr);
1001 /* Free temporary buffer used for mode sequence */
1004 /* Finally, we can actually place the user into the channel.
1005 * We're sure its right. Final answer, phone a friend.
1007 chanrec::JoinUser(this->Instance, who, channel.c_str(), true, "");
1008 /* Have we already queued up MAXMODES modes with parameters
1009 * (+qaohv) ready to be sent to the server?
1011 if (modectr >= (MAXMODES-1))
1013 /* Only actually give the users any status if we lost
1014 * the FJOIN or drew (equal timestamps).
1015 * It isn't actually possible for ourTS to be > TS here,
1016 * only possible to actually have ourTS == TS, or
1017 * ourTS < TS, because if we lost, we already lowered
1018 * our TS above before we entered this loop. We only
1019 * check >= as a safety measure, in case someone stuffed
1020 * up. If someone DID stuff up, it was most likely me.
1021 * Note: I do not like baseball bats in the face...
1025 this->Instance->SendMode((const char**)mode_users,modectr,who);
1027 /* Something stuffed up, and for some reason, the timestamp is
1028 * NOT lowered right now and should be. Lower it. Usually this
1029 * code won't be executed, doubtless someone will remove it some
1034 Instance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",chan->name,ourTS,TS);
1040 /* Reset all this back to defaults, and
1041 * free any ram we have left allocated.
1043 strcpy(mode_users[1],"+");
1044 for (unsigned int f = 2; f < modectr; f++)
1045 free(mode_users[f]);
1051 /* Remember to free this */
1053 /* If we got here, there's a nick in FJOIN which doesnt exist on this server.
1054 * We don't try to process the nickname here (that WOULD cause a segfault because
1055 * we'd be playing with null pointers) however, we DO pass the nickname on, just
1056 * in case somehow we're desynched, so that other users which might be able to see
1057 * the nickname get their fair chance to process it.
1059 Instance->Log(SPARSE,"Warning! Invalid user %s in FJOIN to channel %s IGNORED", usr, channel.c_str());
1065 /* there werent enough modes built up to flush it during FJOIN,
1066 * or, there are a number left over. flush them out.
1068 if ((modectr > 2) && (who) && (chan))
1072 /* Our channel is newer than theirs. Evil deeds must be afoot. */
1073 this->Instance->SendMode((const char**)mode_users,modectr,who);
1074 /* Yet again, we can't actually get a true value here, if everything else
1075 * is working as it should.
1079 Instance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",chan->name,ourTS,TS);
1085 /* Free anything we have left to free */
1086 for (unsigned int f = 2; f < modectr; f++)
1087 free(mode_users[f]);
1089 /* if we newly created the channel, set it's TS properly. */
1092 /* find created channel .. */
1093 chan = this->Instance->FindChan(channel);
1095 /* w00t said this shouldnt be needed but it is.
1096 * This isnt strictly true, as chan can be NULL
1097 * if a nick collision has occured and therefore
1098 * the channel was never created.
1102 /* All done. That wasnt so bad was it, you can wipe
1103 * the sweat from your forehead now. :-)
1109 bool TreeSocket::IntroduceClient(const std::string &source, std::deque<std::string> ¶ms)
1111 if (params.size() < 8)
1113 if (params.size() > 8)
1115 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[1]+"?)");
1118 // NICK age nick host dhost ident +modes ip :gecos
1120 time_t age = atoi(params[0].c_str());
1122 const char* tempnick = params[1].c_str();
1123 Instance->Log(DEBUG,"New remote client %s",tempnick);
1125 user_hash::iterator iter = this->Instance->clientlist->find(tempnick);
1127 if (iter != this->Instance->clientlist->end())
1130 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+tempnick+" :Nickname collision");
1131 userrec::QuitUser(this->Instance, iter->second, "Nickname collision");
1135 userrec* _new = new userrec(this->Instance);
1136 (*(this->Instance->clientlist))[tempnick] = _new;
1137 _new->SetFd(FD_MAGIC_NUMBER);
1138 strlcpy(_new->nick, tempnick,NICKMAX-1);
1139 strlcpy(_new->host, params[2].c_str(),63);
1140 strlcpy(_new->dhost, params[3].c_str(),63);
1141 _new->server = this->Instance->FindServerNamePtr(source.c_str());
1142 strlcpy(_new->ident, params[4].c_str(),IDENTMAX);
1143 strlcpy(_new->fullname, params[7].c_str(),MAXGECOS);
1144 _new->registered = REG_ALL;
1148 * we need to remove the + from the modestring, so we can do our stuff
1150 std::string::size_type pos_after_plus = params[5].find_first_not_of('+');
1151 if (pos_after_plus != std::string::npos)
1152 params[5] = params[5].substr(pos_after_plus);
1154 for (std::string::iterator v = params[5].begin(); v != params[5].end(); v++)
1156 _new->modes[(*v)-65] = 1;
1157 /* For each mode thats set, increase counter */
1158 ModeHandler* mh = Instance->Modes->FindMode(*v, MODETYPE_USER);
1163 /* now we've done with modes processing, put the + back for remote servers */
1164 params[5] = "+" + params[5];
1166 #ifdef SUPPORT_IP6LINKS
1167 if (params[6].find_first_of(":") != std::string::npos)
1168 _new->SetSockAddr(AF_INET6, params[6].c_str(), 0);
1171 _new->SetSockAddr(AF_INET, params[6].c_str(), 0);
1173 Instance->AddGlobalClone(_new);
1174 this->Instance->SNO->WriteToSnoMask('C',"Client connecting at %s: %s!%s@%s [%s]",_new->server,_new->nick,_new->ident,_new->host, _new->GetIPString());
1176 params[7] = ":" + params[7];
1177 Utils->DoOneToAllButSender(source,"NICK", params, source);
1179 // Increment the Source Servers User Count..
1180 TreeServer* SourceServer = Utils->FindServer(source);
1183 SourceServer->AddUserCount();
1186 FOREACH_MOD_I(Instance,I_OnPostConnect,OnPostConnect(_new));
1191 /** Send one or more FJOINs for a channel of users.
1192 * If the length of a single line is more than 480-NICKMAX
1193 * in length, it is split over multiple lines.
1195 void TreeSocket::SendFJoins(TreeServer* Current, chanrec* c)
1199 std::string individual_halfops = std::string(":")+this->Instance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age);
1201 size_t dlen, curlen;
1202 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1204 char* ptr = list + dlen;
1206 CUList *ulist = c->GetUsers();
1207 std::string modes = "";
1208 std::string params = "";
1210 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1212 // The first parameter gets a : before it
1213 size_t ptrlen = snprintf(ptr, MAXBUF, " %s%s,%s", !numusers ? ":" : "", c->GetAllPrefixChars(i->second), i->second->nick);
1220 if (curlen > (480-NICKMAX))
1222 buffer.append(list).append("\r\n");
1223 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1231 buffer.append(list).append("\r\n");
1233 /* Sorry for the hax. Because newly created channels assume +nt,
1234 * if this channel doesnt have +nt, explicitly send -n and -t for the missing modes.
1236 bool inverted = false;
1237 if (!c->IsModeSet('n'))
1242 if (!c->IsModeSet('t'))
1252 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");
1255 for (BanList::iterator b = c->bans.begin(); b != c->bans.end(); b++)
1257 int size = strlen(b->data) + 2;
1258 int currsize = linesize + size;
1259 if (currsize <= 350)
1262 params.append(" ").append(b->data);
1265 if ((params.length() >= MAXMODES) || (currsize > 350))
1267 /* Wrap at MAXMODES */
1268 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");
1275 /* Only send these if there are any */
1277 buffer.append(":").append(this->Instance->Config->ServerName).append(" FMODE ").append(c->name).append(" ").append(ConvToStr(c->age)).append(" +").append(modes).append(params);
1279 this->WriteLine(buffer);
1282 /** Send G, Q, Z and E lines */
1283 void TreeSocket::SendXLines(TreeServer* Current)
1287 std::string n = this->Instance->Config->ServerName;
1288 const char* sn = n.c_str();
1289 /* Yes, these arent too nice looking, but they get the job done */
1290 for (std::vector<ZLine*>::iterator i = Instance->XLines->zlines.begin(); i != Instance->XLines->zlines.end(); i++)
1292 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);
1293 buffer.append(data);
1295 for (std::vector<QLine*>::iterator i = Instance->XLines->qlines.begin(); i != Instance->XLines->qlines.end(); i++)
1297 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);
1298 buffer.append(data);
1300 for (std::vector<GLine*>::iterator i = Instance->XLines->glines.begin(); i != Instance->XLines->glines.end(); i++)
1302 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);
1303 buffer.append(data);
1305 for (std::vector<ELine*>::iterator i = Instance->XLines->elines.begin(); i != Instance->XLines->elines.end(); i++)
1307 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);
1308 buffer.append(data);
1310 for (std::vector<ZLine*>::iterator i = Instance->XLines->pzlines.begin(); i != Instance->XLines->pzlines.end(); i++)
1312 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);
1313 buffer.append(data);
1315 for (std::vector<QLine*>::iterator i = Instance->XLines->pqlines.begin(); i != Instance->XLines->pqlines.end(); i++)
1317 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);
1318 buffer.append(data);
1320 for (std::vector<GLine*>::iterator i = Instance->XLines->pglines.begin(); i != Instance->XLines->pglines.end(); i++)
1322 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);
1323 buffer.append(data);
1325 for (std::vector<ELine*>::iterator i = Instance->XLines->pelines.begin(); i != Instance->XLines->pelines.end(); i++)
1327 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);
1328 buffer.append(data);
1331 if (!buffer.empty())
1332 this->WriteLine(buffer);
1335 /** Send channel modes and topics */
1336 void TreeSocket::SendChannelModes(TreeServer* Current)
1339 std::deque<std::string> list;
1340 std::string n = this->Instance->Config->ServerName;
1341 const char* sn = n.c_str();
1342 for (chan_hash::iterator c = this->Instance->chanlist->begin(); c != this->Instance->chanlist->end(); c++)
1344 SendFJoins(Current, c->second);
1345 if (*c->second->topic)
1347 snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",sn,c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
1348 this->WriteLine(data);
1350 FOREACH_MOD_I(this->Instance,I_OnSyncChannel,OnSyncChannel(c->second,(Module*)Utils->Creator,(void*)this));
1352 c->second->GetExtList(list);
1353 for (unsigned int j = 0; j < list.size(); j++)
1355 FOREACH_MOD_I(this->Instance,I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)Utils->Creator,(void*)this,list[j]));
1360 /** send all users and their oper state/modes */
1361 void TreeSocket::SendUsers(TreeServer* Current)
1364 std::deque<std::string> list;
1365 std::string dataline;
1366 for (user_hash::iterator u = this->Instance->clientlist->begin(); u != this->Instance->clientlist->end(); u++)
1368 if (u->second->registered == REG_ALL)
1370 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);
1371 this->WriteLine(data);
1372 if (*u->second->oper)
1374 snprintf(data,MAXBUF,":%s OPERTYPE %s", u->second->nick, u->second->oper);
1375 this->WriteLine(data);
1377 if (*u->second->awaymsg)
1379 snprintf(data,MAXBUF,":%s AWAY :%s", u->second->nick, u->second->awaymsg);
1380 this->WriteLine(data);
1382 FOREACH_MOD_I(this->Instance,I_OnSyncUser,OnSyncUser(u->second,(Module*)Utils->Creator,(void*)this));
1384 u->second->GetExtList(list);
1386 for (unsigned int j = 0; j < list.size(); j++)
1388 FOREACH_MOD_I(this->Instance,I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)Utils->Creator,(void*)this,list[j]));
1394 /** This function is called when we want to send a netburst to a local
1395 * server. There is a set order we must do this, because for example
1396 * users require their servers to exist, and channels require their
1397 * users to exist. You get the idea.
1399 void TreeSocket::DoBurst(TreeServer* s)
1401 std::string burst = "BURST "+ConvToStr(Instance->Time(true));
1402 std::string endburst = "ENDBURST";
1403 // Because by the end of the netburst, it could be gone!
1404 std::string name = s->GetName();
1405 this->Instance->SNO->WriteToSnoMask('l',"Bursting to \2"+name+"\2.");
1406 this->WriteLine(burst);
1407 /* send our version string */
1408 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" VERSION :"+this->Instance->GetVersionString());
1409 /* Send server tree */
1410 this->SendServers(Utils->TreeRoot,s,1);
1411 /* Send users and their oper status */
1413 /* Send everything else (channel modes, xlines etc) */
1414 this->SendChannelModes(s);
1415 this->SendXLines(s);
1416 FOREACH_MOD_I(this->Instance,I_OnSyncOtherMetaData,OnSyncOtherMetaData((Module*)Utils->Creator,(void*)this));
1417 this->WriteLine(endburst);
1418 this->Instance->SNO->WriteToSnoMask('l',"Finished bursting to \2"+name+"\2.");
1421 /** This function is called when we receive data from a remote
1422 * server. We buffer the data in a std::string (it doesnt stay
1423 * there for long), reading using InspSocket::Read() which can
1424 * read up to 16 kilobytes in one operation.
1426 * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
1427 * THE SOCKET OBJECT FOR US.
1429 bool TreeSocket::OnDataReady()
1431 char* data = this->Read();
1432 /* Check that the data read is a valid pointer and it has some content */
1435 this->in_buffer.append(data);
1436 /* While there is at least one new line in the buffer,
1437 * do something useful (we hope!) with it.
1439 while (in_buffer.find("\n") != std::string::npos)
1441 std::string ret = in_buffer.substr(0,in_buffer.find("\n")-1);
1442 in_buffer = in_buffer.substr(in_buffer.find("\n")+1,in_buffer.length()-in_buffer.find("\n"));
1443 /* Use rfind here not find, as theres more
1444 * chance of the \r being near the end of the
1445 * string, not the start.
1447 if (ret.find("\r") != std::string::npos)
1448 ret = in_buffer.substr(0,in_buffer.find("\r")-1);
1449 /* Process this one, abort if it
1450 * didnt return true.
1452 if (!this->ProcessLine(ret))
1459 /* EAGAIN returns an empty but non-NULL string, so this
1460 * evaluates to TRUE for EAGAIN but to FALSE for EOF.
1462 return (data && !*data);