]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/treesocket1.cpp
Add methods needed for storing challenge string
[user/henk/code/inspircd.git] / src / modules / m_spanningtree / treesocket1.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2007 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include "configreader.h"
15 #include "users.h"
16 #include "channels.h"
17 #include "modules.h"
18 #include "commands/cmd_whois.h"
19 #include "commands/cmd_stats.h"
20 #include "socket.h"
21 #include "inspircd.h"
22 #include "wildcard.h"
23 #include "xline.h"
24 #include "transport.h"
25 #include "socketengine.h"
26
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"
34
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 */
36
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
40  * to it.
41  */
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)
44 {
45         myhost = host;
46         this->LinkState = LISTENER;
47         theirchallenge = ourchallenge = "";
48         if (listening && Hook)
49                 InspSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
50 }
51
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)
54 {
55         myhost = ServerName;
56         theirchallenge = ourchallenge = "";
57         this->LinkState = CONNECTING;
58         if (Hook)
59                 InspSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
60 }
61
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.
65  */
66 TreeSocket::TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, int newfd, char* ip, Module* HookMod)
67         : InspSocket(SI, newfd, ip), Utils(Util), Hook(HookMod)
68 {
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.
73          */
74         if (Hook)
75         {
76                 InspSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
77                 Instance->Timers->AddTimer(new HandshakeTimer(Instance, this, &(Utils->LinkBlocks[0]), this->Utils));
78         }
79         else
80         {
81                 /* Otherwise, theres no lower layer transport in plain TCP/IP,
82                  * so just send the capabilities right now.
83                  */
84                 this->SendCapabilities();
85         }
86 }
87
88 ServerState TreeSocket::GetLinkState()
89 {
90         return this->LinkState;
91 }
92
93 Module* TreeSocket::GetHook()
94 {
95         return this->Hook;
96 }
97
98 TreeSocket::~TreeSocket()
99 {
100         if (Hook)
101                 InspSocketUnhookRequest(this, (Module*)Utils->Creator, Hook).Send();
102 }
103
104 const std::string& TreeSocket::GetOurChallenge()
105 {
106         return this->ourchallenge;
107 }
108
109 void TreeSocket::SetOurChallenge(const std::string &c)
110 {
111         this->ourchallenge = c;
112 }
113
114 const std::string& TreeSocket::GetTheirChallenge()
115 {
116         return this->theirchallenge;
117 }
118
119 void TreeSocket::SetTheirChallenge(const std::string &c)
120 {
121         this->theirchallenge = c;
122 }
123
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.
129  */
130 bool TreeSocket::OnConnected()
131 {
132         if (this->LinkState == CONNECTING)
133         {
134                 /* we do not need to change state here. */
135                 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
136                 {
137                         if (x->Name == this->myhost)
138                         {
139                                 this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] started.");
140                                 if (Hook)
141                                 {
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");
144                                 }
145                                 else
146                                         this->SendCapabilities();
147                                 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
148                                 if (Hook)
149                                         Instance->Timers->AddTimer(new HandshakeTimer(Instance, this, &(*x), this->Utils));
150                                 else
151                                         this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+x->SendPass+" 0 :"+this->Instance->Config->ServerDesc);
152                                 return true;
153                         }
154                 }
155         }
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.
160          */
161         this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2 lost link tag(!)");
162         return true;
163 }
164
165 void TreeSocket::OnError(InspSocketError e)
166 {
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.
170          */
171         if (e == I_ERR_CONNECT)
172         {
173                 this->Instance->SNO->WriteToSnoMask('l',"Connection failed: Connection to \002"+myhost+"\002 refused");
174                 Link* MyLink = Utils->FindLink(myhost);
175                 if (MyLink)
176                         Utils->DoFailOver(MyLink);
177         }
178 }
179
180 int TreeSocket::OnDisconnect()
181 {
182         /* For the same reason as above, we don't
183          * handle OnDisconnect()
184          */
185         return true;
186 }
187
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.
196  */
197 void TreeSocket::SendServers(TreeServer* Current, TreeServer* s, int hops)
198 {
199         char command[1024];
200         for (unsigned int q = 0; q < Current->ChildCount(); q++)
201         {
202                 TreeServer* recursive_server = Current->GetChild(q);
203                 if (recursive_server != s)
204                 {
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);
210                 }
211         }
212 }
213
214 std::string TreeSocket::MyCapabilities()
215 {
216         std::vector<std::string> modlist;
217         std::string capabilities = "";
218         for (int i = 0; i <= this->Instance->GetModuleCount(); i++)
219         {
220                 if (this->Instance->modules[i]->GetVersion().Flags & VF_COMMON)
221                         modlist.push_back(this->Instance->Config->module_names[i]);
222         }
223         sort(modlist.begin(),modlist.end());
224         for (unsigned int i = 0; i < modlist.size(); i++)
225         {
226                 if (i)
227                         capabilities = capabilities + ",";
228                 capabilities = capabilities + modlist[i];
229         }
230         return capabilities;
231 }
232
233 void TreeSocket::SendCapabilities()
234 {
235         irc::commasepstream modulelist(MyCapabilities());
236         this->WriteLine("CAPAB START");
237
238         /* Send module names, split at 509 length */
239         std::string item = "*";
240         std::string line = "CAPAB MODULES ";
241         while ((item = modulelist.GetToken()) != "")
242         {
243                 if (line.length() + item.length() + 1 > 509)
244                 {
245                         this->WriteLine(line);
246                         line = "CAPAB MODULES ";
247                 }
248
249                 if (line != "CAPAB MODULES ")
250                         line.append(",");
251
252                 line.append(item);
253         }
254         if (line != "CAPAB MODULES ")
255                 this->WriteLine(line);
256
257         int ip6 = 0;
258         int ip6support = 0;
259 #ifdef IPV6
260         ip6 = 1;
261 #endif
262 #ifdef SUPPORT_IP6LINKS
263         ip6support = 1;
264 #endif
265         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));
266
267         this->WriteLine("CAPAB END");
268 }
269
270 /* Check a comma seperated list for an item */
271 bool TreeSocket::HasItem(const std::string &list, const std::string &item)
272 {
273         irc::commasepstream seplist(list);
274         std::string item2 = "*";
275         while ((item2 = seplist.GetToken()) != "")
276         {
277                 if (item2 == item)
278                         return true;
279         }
280         return false;
281 }
282
283 /* Isolate and return the elements that are different between two comma seperated lists */
284 std::string TreeSocket::ListDifference(const std::string &one, const std::string &two)
285 {
286         irc::commasepstream list_one(one);
287         std::string item = "*";
288         std::string result = "";
289         while ((item = list_one.GetToken()) != "")
290         {
291                 if (!HasItem(two, item))
292                 {
293                         result.append(" ");
294                         result.append(item);
295                 }
296         }
297         return result;
298 }
299
300 bool TreeSocket::Capab(const std::deque<std::string> &params)
301 {
302         if (params.size() < 1)
303         {
304                 this->WriteLine("ERROR :Invalid number of parameters for CAPAB - Mismatched version");
305                 return false;
306         }
307         if (params[0] == "START")
308         {
309                 this->ModuleList = "";
310                 this->CapKeys.clear();
311         }
312         else if (params[0] == "END")
313         {
314                 std::string reason = "";
315                 int ip6support = 0;
316 #ifdef SUPPORT_IP6LINKS
317                 ip6support = 1;
318 #endif
319                 /* Compare ModuleList and check CapKeys...
320                  * Maybe this could be tidier? -- Brain
321                  */
322                 if ((this->ModuleList != this->MyCapabilities()) && (this->ModuleList.length()))
323                 {
324                         std::string diff = ListDifference(this->ModuleList, this->MyCapabilities());
325                         if (!diff.length())
326                         {
327                                 diff = "your server:" + ListDifference(this->MyCapabilities(), this->ModuleList);
328                         }
329                         else
330                         {
331                                 diff = "this server:" + diff;
332                         }
333                         if (diff.length() == 12)
334                                 reason = "Module list in CAPAB is not alphabetically ordered, cannot compare lists.";
335                         else
336                                 reason = "Modules loaded on these servers are not correctly matched, these modules are not loaded on " + diff;
337                 }
338                 if (((this->CapKeys.find("IP6SUPPORT") == this->CapKeys.end()) && (ip6support)) || ((this->CapKeys.find("IP6SUPPORT") != this->CapKeys.end()) && (this->CapKeys.find("IP6SUPPORT")->second != ConvToStr(ip6support))))
339                         reason = "We don't both support linking to IPV6 servers";
340                 if (((this->CapKeys.find("IP6NATIVE") != this->CapKeys.end()) && (this->CapKeys.find("IP6NATIVE")->second == "1")) && (!ip6support))
341                         reason = "The remote server is IPV6 native, and we don't support linking to IPV6 servers";
342                 if (((this->CapKeys.find("NICKMAX") == this->CapKeys.end()) || ((this->CapKeys.find("NICKMAX") != this->CapKeys.end()) && (this->CapKeys.find("NICKMAX")->second != ConvToStr(NICKMAX)))))
343                         reason = "Maximum nickname lengths differ or remote nickname length not specified";
344                 if (((this->CapKeys.find("PROTOCOL") == this->CapKeys.end()) || ((this->CapKeys.find("PROTOCOL") != this->CapKeys.end()) && (this->CapKeys.find("PROTOCOL")->second != ConvToStr(ProtocolVersion)))))
345                 {
346                         if (this->CapKeys.find("PROTOCOL") != this->CapKeys.end())
347                         {
348                                 reason = "Mismatched protocol versions "+this->CapKeys.find("PROTOCOL")->second+" and "+ConvToStr(ProtocolVersion);
349                         }
350                         else
351                         {
352                                 reason = "Protocol version not specified";
353                         }
354                 }
355                 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))))
356                         reason = "We don't both have halfop support enabled/disabled identically";
357                 if (((this->CapKeys.find("IDENTMAX") == this->CapKeys.end()) || ((this->CapKeys.find("IDENTMAX") != this->CapKeys.end()) && (this->CapKeys.find("IDENTMAX")->second != ConvToStr(IDENTMAX)))))
358                         reason = "Maximum ident lengths differ or remote ident length not specified";
359                 if (((this->CapKeys.find("CHANMAX") == this->CapKeys.end()) || ((this->CapKeys.find("CHANMAX") != this->CapKeys.end()) && (this->CapKeys.find("CHANMAX")->second != ConvToStr(CHANMAX)))))
360                         reason = "Maximum channel lengths differ or remote channel length not specified";
361                 if (((this->CapKeys.find("MAXMODES") == this->CapKeys.end()) || ((this->CapKeys.find("MAXMODES") != this->CapKeys.end()) && (this->CapKeys.find("MAXMODES")->second != ConvToStr(MAXMODES)))))
362                         reason = "Maximum modes per line differ or remote modes per line not specified";
363                 if (((this->CapKeys.find("MAXQUIT") == this->CapKeys.end()) || ((this->CapKeys.find("MAXQUIT") != this->CapKeys.end()) && (this->CapKeys.find("MAXQUIT")->second != ConvToStr(MAXQUIT)))))
364                         reason = "Maximum quit lengths differ or remote quit length not specified";
365                 if (((this->CapKeys.find("MAXTOPIC") == this->CapKeys.end()) || ((this->CapKeys.find("MAXTOPIC") != this->CapKeys.end()) && (this->CapKeys.find("MAXTOPIC")->second != ConvToStr(MAXTOPIC)))))
366                         reason = "Maximum topic lengths differ or remote topic length not specified";
367                 if (((this->CapKeys.find("MAXKICK") == this->CapKeys.end()) || ((this->CapKeys.find("MAXKICK") != this->CapKeys.end()) && (this->CapKeys.find("MAXKICK")->second != ConvToStr(MAXKICK)))))
368                         reason = "Maximum kick lengths differ or remote kick length not specified";
369                 if (((this->CapKeys.find("MAXGECOS") == this->CapKeys.end()) || ((this->CapKeys.find("MAXGECOS") != this->CapKeys.end()) && (this->CapKeys.find("MAXGECOS")->second != ConvToStr(MAXGECOS)))))
370                         reason = "Maximum GECOS (fullname) lengths differ or remote GECOS length not specified";
371                 if (((this->CapKeys.find("MAXAWAY") == this->CapKeys.end()) || ((this->CapKeys.find("MAXAWAY") != this->CapKeys.end()) && (this->CapKeys.find("MAXAWAY")->second != ConvToStr(MAXAWAY)))))
372                         reason = "Maximum awaymessage lengths differ or remote awaymessage length not specified";
373                 if (reason.length())
374                 {
375                         this->WriteLine("ERROR :CAPAB negotiation failed: "+reason);
376                         return false;
377                 }
378         }
379         else if ((params[0] == "MODULES") && (params.size() == 2))
380         {
381                 if (!this->ModuleList.length())
382                 {
383                         this->ModuleList.append(params[1]);
384                 }
385                 else
386                 {
387                         this->ModuleList.append(",");
388                         this->ModuleList.append(params[1]);
389                 }
390         }
391
392         else if ((params[0] == "CAPABILITIES") && (params.size() == 2))
393         {
394                 irc::tokenstream capabs(params[1]);
395                 std::string item;
396                 bool more = true;
397                 while ((more = capabs.GetToken(item)))
398                 {
399                         /* Process each key/value pair */
400                         std::string::size_type equals = item.rfind('=');
401                         if (equals != std::string::npos)
402                         {
403                                 std::string var = item.substr(0, equals);
404                                 std::string value = item.substr(equals+1, item.length());
405                                 CapKeys[var] = value;
406                         }
407                 }
408         }
409         return true;
410 }
411
412 /** This function forces this server to quit, removing this server
413  * and any users on it (and servers and users below that, etc etc).
414  * It's very slow and pretty clunky, but luckily unless your network
415  * is having a REAL bad hair day, this function shouldnt be called
416  * too many times a month ;-)
417  */
418 void TreeSocket::SquitServer(std::string &from, TreeServer* Current)
419 {
420         /* recursively squit the servers attached to 'Current'.
421          * We're going backwards so we don't remove users
422          * while we still need them ;)
423          */
424         for (unsigned int q = 0; q < Current->ChildCount(); q++)
425         {
426                 TreeServer* recursive_server = Current->GetChild(q);
427                 this->SquitServer(from,recursive_server);
428         }
429         /* Now we've whacked the kids, whack self */
430         num_lost_servers++;
431         num_lost_users += Current->QuitUsers(from);
432 }
433
434 /** This is a wrapper function for SquitServer above, which
435  * does some validation first and passes on the SQUIT to all
436  * other remaining servers.
437  */
438 void TreeSocket::Squit(TreeServer* Current, const std::string &reason)
439 {
440         if ((Current) && (Current != Utils->TreeRoot))
441         {
442                 Event rmode((char*)Current->GetName().c_str(), (Module*)Utils->Creator, "lost_server");
443                 rmode.Send(Instance);
444
445                 std::deque<std::string> params;
446                 params.push_back(Current->GetName());
447                 params.push_back(":"+reason);
448                 Utils->DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
449                 if (Current->GetParent() == Utils->TreeRoot)
450                 {
451                         this->Instance->WriteOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
452                 }
453                 else
454                 {
455                         this->Instance->WriteOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
456                 }
457                 num_lost_servers = 0;
458                 num_lost_users = 0;
459                 std::string from = Current->GetParent()->GetName()+" "+Current->GetName();
460                 SquitServer(from, Current);
461                 Current->Tidy();
462                 Current->GetParent()->DelChild(Current);
463                 DELETE(Current);
464                 this->Instance->WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
465         }
466         else
467         {
468                 Instance->Log(DEFAULT,"Squit from unknown server");
469         }
470 }
471
472 /** FMODE command - server mode with timestamp checks */
473 bool TreeSocket::ForceMode(const std::string &source, std::deque<std::string> &params)
474 {
475         /* Chances are this is a 1.0 FMODE without TS */
476         if (params.size() < 3)
477         {
478                 /* No modes were in the command, probably a channel with no modes set on it */
479                 return true;
480         }
481
482         bool smode = false;
483         std::string sourceserv;
484         /* Are we dealing with an FMODE from a user, or from a server? */
485         userrec* who = this->Instance->FindNick(source);
486         if (who)
487         {
488                 /* FMODE from a user, set sourceserv to the users server name */
489                 sourceserv = who->server;
490         }
491         else
492         {
493                 /* FMODE from a server, create a fake user to receive mode feedback */
494                 who = new userrec(this->Instance);
495                 who->SetFd(FD_MAGIC_NUMBER);
496                 smode = true;      /* Setting this flag tells us we should free the userrec later */
497                 sourceserv = source;    /* Set sourceserv to the actual source string */
498         }
499         const char* modelist[64];
500         time_t TS = 0;
501         int n = 0;
502         memset(&modelist,0,sizeof(modelist));
503         for (unsigned int q = 0; (q < params.size()) && (q < 64); q++)
504         {
505                 if (q == 1)
506                 {
507                         /* The timestamp is in this position.
508                          * We don't want to pass that up to the
509                          * server->client protocol!
510                          */
511                         TS = atoi(params[q].c_str());
512                 }
513                 else
514                 {
515                         /* Everything else is fine to append to the modelist */
516                         modelist[n++] = params[q].c_str();
517                 }
518
519         }
520         /* Extract the TS value of the object, either userrec or chanrec */
521         userrec* dst = this->Instance->FindNick(params[0]);
522         chanrec* chan = NULL;
523         time_t ourTS = 0;
524         if (dst)
525         {
526                 ourTS = dst->age;
527         }
528         else
529         {
530                 chan = this->Instance->FindChan(params[0]);
531                 if (chan)
532                 {
533                         ourTS = chan->age;
534                 }
535                 else
536                         /* Oops, channel doesnt exist! */
537                         return true;
538         }
539
540         /* TS is equal or less: Merge the mode changes into ours and pass on.
541          */
542         if (TS <= ourTS)
543         {
544                 if (smode)
545                 {
546                         this->Instance->SendMode(modelist, n, who);
547                 }
548                 else
549                 {
550                         this->Instance->CallCommandHandler("MODE", modelist, n, who);
551                 }
552                 /* HOT POTATO! PASS IT ON! */
553                 Utils->DoOneToAllButSender(source,"FMODE",params,sourceserv);
554         }
555         /* If the TS is greater than ours, we drop the mode and dont pass it anywhere.
556          */
557
558         if (smode)
559                 DELETE(who);
560
561         return true;
562 }
563
564 /** FTOPIC command */
565 bool TreeSocket::ForceTopic(const std::string &source, std::deque<std::string> &params)
566 {
567         if (params.size() != 4)
568                 return true;
569         time_t ts = atoi(params[1].c_str());
570         std::string nsource = source;
571         chanrec* c = this->Instance->FindChan(params[0]);
572         if (c)
573         {
574                 if ((ts >= c->topicset) || (!*c->topic))
575                 {
576                         std::string oldtopic = c->topic;
577                         strlcpy(c->topic,params[3].c_str(),MAXTOPIC);
578                         strlcpy(c->setby,params[2].c_str(),127);
579                         c->topicset = ts;
580                         /* if the topic text is the same as the current topic,
581                          * dont bother to send the TOPIC command out, just silently
582                          * update the set time and set nick.
583                          */
584                         if (oldtopic != params[3])
585                         {
586                                 userrec* user = this->Instance->FindNick(source);
587                                 if (!user)
588                                 {
589                                         c->WriteChannelWithServ(source.c_str(), "TOPIC %s :%s", c->name, c->topic);
590                                 }
591                                 else
592                                 {
593                                         c->WriteChannel(user, "TOPIC %s :%s", c->name, c->topic);
594                                         nsource = user->server;
595                                 }
596                                 /* all done, send it on its way */
597                                 params[3] = ":" + params[3];
598                                 Utils->DoOneToAllButSender(source,"FTOPIC",params,nsource);
599                         }
600                 }
601
602         }
603         return true;
604 }
605
606 /** FJOIN, similar to TS6 SJOIN, but not quite. */
607 bool TreeSocket::ForceJoin(const std::string &source, std::deque<std::string> &params)
608 {
609         /* 1.1 FJOIN works as follows:
610          *
611          * Each FJOIN is sent along with a timestamp, and the side with the lowest
612          * timestamp 'wins'. From this point on we will refer to this side as the
613          * winner. The side with the higher timestamp loses, from this point on we
614          * will call this side the loser or losing side. This should be familiar to
615          * anyone who's dealt with dreamforge or TS6 before.
616          *
617          * When two sides of a split heal and this occurs, the following things
618          * will happen:
619          *
620          * If the timestamps are exactly equal, both sides merge their privilages
621          * and users, as in InspIRCd 1.0 and ircd2.8. The channels have not been
622          * re-created during a split, this is safe to do.
623          *
624          *
625          * If the timestamps are NOT equal, the losing side removes all privilage
626          * modes from all of its users that currently exist in the channel, before
627          * introducing new users into the channel which are listed in the FJOIN
628          * command's parameters. This means, all modes +ohv, and privilages added
629          * by modules, such as +qa. The losing side then LOWERS its timestamp value
630          * of the channel to match that of the winning side, and the modes of the
631          * users of the winning side are merged in with the losing side. The loser
632          * then sends out a set of FMODE commands which 'confirm' that it just
633          * removed all privilage modes from its existing users, which allows for
634          * services packages to still work correctly without needing to know the
635          * timestamping rules which InspIRCd follows. In TS6 servers this is always
636          * a problem, and services packages must contain code which explicitly
637          * behaves as TS6 does, removing ops from the losing side of a split where
638          * neccessary within its internal records, as this state information is
639          * not explicitly echoed out in that protocol.
640          *
641          * The winning side on the other hand will ignore all user modes from the
642          * losing side, so only its own modes get applied. Life is simple for those
643          * who succeed at internets. :-)
644          *
645          * NOTE: Unlike TS6 and dreamforge and other protocols which have SJOIN,
646          * FJOIN does not contain the simple-modes such as +iklmnsp. Why not,
647          * you ask? Well, quite simply because we don't need to. They'll be sent
648          * after the FJOIN by FMODE, and FMODE is timestamped, so in the event
649          * the losing side sends any modes for the channel which shouldnt win,
650          * they wont as their timestamp will be too high :-)
651          */
652
653         if (params.size() < 3)
654                 return true;
655
656         char first[MAXBUF];          /* The first parameter of the mode command */
657         char modestring[MAXBUF];        /* The mode sequence (2nd parameter) of the mode command */
658         char* mode_users[127];    /* The values used by the mode command */
659         memset(&mode_users,0,sizeof(mode_users));       /* Initialize mode parameters */
660         mode_users[0] = first;    /* Set this up to be our on-stack value */
661         mode_users[1] = modestring;     /* Same here as above */
662         strcpy(modestring,"+");  /* Initialize the mode sequence to just '+' */
663         unsigned int modectr = 2;       /* Pointer to the third mode parameter (e.g. the one after the +-sequence) */
664
665         userrec* who = NULL;                /* User we are currently checking */
666         std::string channel = params[0];        /* Channel name, as a string */
667         time_t TS = atoi(params[1].c_str());    /* Timestamp given to us for remote side */
668         std::string nicklist = params[2];
669         bool created = false;
670
671         /* Try and find the channel */
672         chanrec* chan = this->Instance->FindChan(channel);
673
674         /* Initialize channel name in the mode parameters */
675         strlcpy(mode_users[0],channel.c_str(),MAXBUF);
676
677         /* default TS is a high value, which if we dont have this
678          * channel will let the other side apply their modes.
679          */
680         time_t ourTS = Instance->Time(true)+600;
681         /* Does this channel exist? if it does, get its REAL timestamp */
682         if (chan)
683                 ourTS = chan->age;
684         else
685                 created = true; /* don't perform deops, and set TS to correct time after processing. */
686
687         /* do this first, so our mode reversals are correctly received by other servers
688          * if there is a TS collision.
689          */
690         params[2] = ":" + params[2];
691         Utils->DoOneToAllButSender(source,"FJOIN",params,source);
692
693         /* In 1.1, if they have the newer channel, we immediately clear
694          * all status modes from our users. We then accept their modes.
695          * If WE have the newer channel its the other side's job to do this.
696          * Note that this causes the losing server to send out confirming
697          * FMODE lines.
698          */
699         if (ourTS > TS)
700         {
701                 std::deque<std::string> param_list;
702                 /* Lower the TS here */
703                 if (Utils->AnnounceTSChange && chan)
704                         chan->WriteChannelWithServ(Instance->Config->ServerName,
705                         "NOTICE %s :TS for %s changed from %lu to %lu", chan->name, chan->name, ourTS, TS);
706                 ourTS = TS;
707                 /* Zap all the privilage modes on our side, if the channel exists here */
708                 if (!created)
709                 {
710                         param_list.push_back(channel);
711                         /* Do this first! */
712                         chan->age = TS;
713                         this->RemoveStatus(Instance->Config->ServerName, param_list);
714                 }
715         }
716         /* Put the final parameter of the FJOIN into a tokenstream ready to split it */
717         irc::tokenstream users(nicklist);
718         std::string item;
719
720         /* Now, process every 'prefixes,nick' pair */
721         while (users.GetToken(item))
722         {
723                 /* Find next user */
724                 const char* usr = item.c_str();
725                 /* Safety check just to make sure someones not sent us an FJOIN full of spaces
726                  * (is this even possible?) */
727                 if (usr && *usr)
728                 {
729                         const char* permissions = usr;
730                         int ntimes = 0;
731                         char* nm = new char[MAXBUF];
732                         char* tnm = nm;
733                         /* Iterate through all the prefix values, convert them from prefixes
734                          * to mode letters, and append them to the mode sequence
735                          */
736                         while ((*permissions) && (*permissions != ',') && (ntimes < MAXBUF))
737                         {
738                                 ModeHandler* mh = Instance->Modes->FindPrefix(*permissions);
739                                 if (mh)
740                                 {
741                                         /* This is a valid prefix */
742                                         ntimes++;
743                                         *tnm++ = mh->GetModeChar();
744                                 }
745                                 else
746                                 {
747                                         /* Not a valid prefix...
748                                          * danger bill bobbertson! (that's will robinsons older brother ;-) ...)
749                                          */
750                                         this->Instance->WriteOpers("ERROR: We received a user with an unknown prefix '%c'. Closed connection to avoid a desync.",*permissions);
751                                         this->WriteLine(std::string("ERROR :Invalid prefix '")+(*permissions)+"' in FJOIN");
752                                         return false;
753                                 }
754                                 usr++;
755                                 permissions++;
756                         }
757                         /* Null terminate modes */
758                         *tnm = 0;
759                         /* Advance past the comma, to the nick */
760                         usr++;
761                         /* Check the user actually exists */
762                         who = this->Instance->FindNick(usr);
763                         if (who)
764                         {
765                                 /* Check that the user's 'direction' is correct
766                                  * based on the server sending the FJOIN. We must
767                                  * check each nickname in turn, because the origin of
768                                  * the FJOIN may be different to the origin of the nicks
769                                  * in the command itself.
770                                  */
771                                 TreeServer* route_back_again = Utils->BestRouteTo(who->server);
772                                 if ((!route_back_again) || (route_back_again->GetSocket() != this))
773                                 {
774                                         /* Oh dear oh dear. */
775                                         delete[] nm;
776                                         continue;
777                                 }
778
779                                 /* NOTE: Moved this below the fake direction check, so that modes
780                                  * arent put into the mode list for users that were collided, and
781                                  * may reconnect from the other side or our side before the split
782                                  * is completed!
783                                  */
784
785                                 /* Did they get any modes? How many times? */
786                                 strlcat(modestring, nm, MAXBUF);
787                                 for (int k = 0; k < ntimes; k++)
788                                         mode_users[modectr++] = strdup(usr);
789                                 /* Free temporary buffer used for mode sequence */
790                                 delete[] nm;
791
792                                 /* Finally, we can actually place the user into the channel.
793                                  * We're sure its right. Final answer, phone a friend.
794                                  */
795                                 if (created)
796                                         chanrec::JoinUser(this->Instance, who, channel.c_str(), true, "", TS);
797                                 else
798                                         chanrec::JoinUser(this->Instance, who, channel.c_str(), true, "");
799                                 /* Have we already queued up MAXMODES modes with parameters
800                                  * (+qaohv) ready to be sent to the server?
801                                  */
802                                 if (modectr >= (MAXMODES-1))
803                                 {
804                                         /* Only actually give the users any status if we lost
805                                          * the FJOIN or drew (equal timestamps).
806                                          * It isn't actually possible for ourTS to be > TS here,
807                                          * only possible to actually have ourTS == TS, or
808                                          * ourTS < TS, because if we lost, we already lowered
809                                          * our TS above before we entered this loop. We only
810                                          * check >= as a safety measure, in case someone stuffed
811                                          * up. If someone DID stuff up, it was most likely me.
812                                          * Note: I do not like baseball bats in the face...
813                                          */
814                                         if (ourTS >= TS)
815                                         {
816                                                 this->Instance->SendMode((const char**)mode_users,modectr,who);
817
818                                                 /* Something stuffed up, and for some reason, the timestamp is
819                                                  * NOT lowered right now and should be. Lower it. Usually this
820                                                  * code won't be executed, doubtless someone will remove it some
821                                                  * day soon.
822                                                  */
823                                                 if (ourTS > TS)
824                                                 {
825                                                         Instance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",chan->name,ourTS,TS);
826                                                         chan->age = TS;
827                                                         ourTS = TS;
828                                                 }
829                                         }
830
831                                         /* Reset all this back to defaults, and
832                                          * free any ram we have left allocated.
833                                          */
834                                         strcpy(mode_users[1],"+");
835                                         for (unsigned int f = 2; f < modectr; f++)
836                                                 free(mode_users[f]);
837                                         modectr = 2;
838                                 }
839                         }
840                         else
841                         {
842                                 /* Remember to free this */
843                                 delete[] nm;
844                                 /* If we got here, there's a nick in FJOIN which doesnt exist on this server.
845                                  * We don't try to process the nickname here (that WOULD cause a segfault because
846                                  * we'd be playing with null pointers) however, we DO pass the nickname on, just
847                                  * in case somehow we're desynched, so that other users which might be able to see
848                                  * the nickname get their fair chance to process it.
849                                  */
850                                 Instance->Log(SPARSE,"Warning! Invalid user %s in FJOIN to channel %s IGNORED", usr, channel.c_str());
851                                 continue;
852                         }
853                 }
854         }
855
856         /* there werent enough modes built up to flush it during FJOIN,
857          * or, there are a number left over. flush them out.
858          */
859         if ((modectr > 2) && (who) && (chan))
860         {
861                 if (ourTS >= TS)
862                 {
863                         /* Our channel is newer than theirs. Evil deeds must be afoot. */
864                         this->Instance->SendMode((const char**)mode_users,modectr,who);
865                         /* Yet again, we can't actually get a true value here, if everything else
866                          * is working as it should.
867                          */
868                         if (ourTS > TS)
869                         {
870                                 Instance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",chan->name,ourTS,TS);
871                                 chan->age = TS;
872                                 ourTS = TS;
873                         }
874                 }
875
876                 /* Free anything we have left to free */
877                 for (unsigned int f = 2; f < modectr; f++)
878                         free(mode_users[f]);
879         }
880         /* All done. That wasnt so bad was it, you can wipe
881          * the sweat from your forehead now. :-)
882          */
883         return true;
884 }
885
886 /** NICK command */
887 bool TreeSocket::IntroduceClient(const std::string &source, std::deque<std::string> &params)
888 {
889         /** Do we have enough parameters:
890          * NICK age nick host dhost ident +modes ip :gecos
891          */
892         if (params.size() != 8)
893         {
894                 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[1]+"?)");
895                 return true;
896         }
897
898         time_t age = atoi(params[0].c_str());
899         const char* tempnick = params[1].c_str();
900
901         /** Check parameters for validity before introducing the client, discovered by dmb.
902          * XXX: Can we make this neater?
903          */
904         if (!age)
905         {
906                 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction (Invalid TS?)");
907                 return true;
908         }
909         else if (params[1].length() > NICKMAX)
910         {
911                 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[1]+" > NICKMAX?)");
912                 return true;
913         }
914         else if (params[2].length() > 64)
915         {
916                 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[2]+" > 64?)");
917                 return true;
918         }
919         else if (params[3].length() > 64)
920         {
921                 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[3]+" > 64?)");
922                 return true;
923         }
924         else if (params[4].length() > IDENTMAX)
925         {
926                 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[4]+" > IDENTMAX?)");
927                 return true;
928         }
929         else if (params[7].length() > MAXGECOS)
930         {
931                 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[7]+" > MAXGECOS?)");
932                 return true;
933         }
934
935         /** Our client looks ok, lets introduce it now
936          */
937         Instance->Log(DEBUG,"New remote client %s",tempnick);
938         user_hash::iterator iter = this->Instance->clientlist->find(tempnick);
939
940         if (iter != this->Instance->clientlist->end())
941         {
942                 /* nick collision */
943                 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+tempnick+" :Nickname collision");
944                 userrec::QuitUser(this->Instance, iter->second, "Nickname collision");
945                 return true;
946         }
947
948         userrec* _new = new userrec(this->Instance);
949         (*(this->Instance->clientlist))[tempnick] = _new;
950         _new->SetFd(FD_MAGIC_NUMBER);
951         strlcpy(_new->nick, tempnick,NICKMAX-1);
952         strlcpy(_new->host, params[2].c_str(),63);
953         strlcpy(_new->dhost, params[3].c_str(),63);
954         _new->server = this->Instance->FindServerNamePtr(source.c_str());
955         strlcpy(_new->ident, params[4].c_str(),IDENTMAX);
956         strlcpy(_new->fullname, params[7].c_str(),MAXGECOS);
957         _new->registered = REG_ALL;
958         _new->signon = age;
959
960         /* we need to remove the + from the modestring, so we can do our stuff */
961         std::string::size_type pos_after_plus = params[5].find_first_not_of('+');
962         if (pos_after_plus != std::string::npos)
963         params[5] = params[5].substr(pos_after_plus);
964
965         for (std::string::iterator v = params[5].begin(); v != params[5].end(); v++)
966         {
967                 _new->modes[(*v)-65] = 1;
968                 /* For each mode thats set, increase counter */
969                 ModeHandler* mh = Instance->Modes->FindMode(*v, MODETYPE_USER);
970                 if (mh)
971                         mh->ChangeCount(1);
972         }
973
974         /* now we've done with modes processing, put the + back for remote servers */
975         params[5] = "+" + params[5];
976
977 #ifdef SUPPORT_IP6LINKS
978         if (params[6].find_first_of(":") != std::string::npos)
979                 _new->SetSockAddr(AF_INET6, params[6].c_str(), 0);
980         else
981 #endif
982                 _new->SetSockAddr(AF_INET, params[6].c_str(), 0);
983
984         Instance->AddGlobalClone(_new);
985
986         if (!this->Instance->SilentULine(_new->server))
987                 this->Instance->SNO->WriteToSnoMask('C',"Client connecting at %s: %s!%s@%s [%s]",_new->server,_new->nick,_new->ident,_new->host, _new->GetIPString());
988
989         params[7] = ":" + params[7];
990         Utils->DoOneToAllButSender(source,"NICK", params, source);
991
992         // Increment the Source Servers User Count..
993         TreeServer* SourceServer = Utils->FindServer(source);
994         if (SourceServer)
995         {
996                 SourceServer->AddUserCount();
997         }
998
999         FOREACH_MOD_I(Instance,I_OnPostConnect,OnPostConnect(_new));
1000
1001         return true;
1002 }
1003
1004 /** Send one or more FJOINs for a channel of users.
1005  * If the length of a single line is more than 480-NICKMAX
1006  * in length, it is split over multiple lines.
1007  */
1008 void TreeSocket::SendFJoins(TreeServer* Current, chanrec* c)
1009 {
1010         std::string buffer;
1011         char list[MAXBUF];
1012         std::string individual_halfops = std::string(":")+this->Instance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age);
1013
1014         size_t dlen, curlen;
1015         dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1016         int numusers = 0;
1017         char* ptr = list + dlen;
1018
1019         CUList *ulist = c->GetUsers();
1020         std::string modes = "";
1021         std::string params = "";
1022
1023         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1024         {
1025                 // The first parameter gets a : before it
1026                 size_t ptrlen = snprintf(ptr, MAXBUF, " %s%s,%s", !numusers ? ":" : "", c->GetAllPrefixChars(i->second), i->second->nick);
1027
1028                 curlen += ptrlen;
1029                 ptr += ptrlen;
1030
1031                 numusers++;
1032
1033                 if (curlen > (480-NICKMAX))
1034                 {
1035                         buffer.append(list).append("\r\n");
1036                         dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1037                         ptr = list + dlen;
1038                         ptrlen = 0;
1039                         numusers = 0;
1040                 }
1041         }
1042
1043         if (numusers)
1044                 buffer.append(list).append("\r\n");
1045
1046         /* Sorry for the hax. Because newly created channels assume +nt,
1047          * if this channel doesnt have +nt, explicitly send -n and -t for the missing modes.
1048          */
1049         bool inverted = false;
1050         if (!c->IsModeSet('n'))
1051         {
1052                 modes.append("-n");
1053                 inverted = true;
1054         }
1055         if (!c->IsModeSet('t'))
1056         {
1057                 modes.append("-t");
1058                 inverted = true;
1059         }
1060         if (inverted)
1061         {
1062                 modes.append("+");
1063         }
1064
1065         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");
1066
1067         int linesize = 1;
1068         for (BanList::iterator b = c->bans.begin(); b != c->bans.end(); b++)
1069         {
1070                 int size = strlen(b->data) + 2;
1071                 int currsize = linesize + size;
1072                 if (currsize <= 350)
1073                 {
1074                         modes.append("b");
1075                         params.append(" ").append(b->data);
1076                         linesize += size; 
1077                 }
1078                 if ((params.length() >= MAXMODES) || (currsize > 350))
1079                 {
1080                         /* Wrap at MAXMODES */
1081                         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");
1082                         modes = "";
1083                         params = "";
1084                         linesize = 1;
1085                 }
1086         }
1087
1088         /* Only send these if there are any */
1089         if (!modes.empty())
1090                 buffer.append(":").append(this->Instance->Config->ServerName).append(" FMODE ").append(c->name).append(" ").append(ConvToStr(c->age)).append(" +").append(modes).append(params);
1091
1092         this->WriteLine(buffer);
1093 }
1094
1095 /** Send G, Q, Z and E lines */
1096 void TreeSocket::SendXLines(TreeServer* Current)
1097 {
1098         char data[MAXBUF];
1099         std::string buffer;
1100         std::string n = this->Instance->Config->ServerName;
1101         const char* sn = n.c_str();
1102         /* Yes, these arent too nice looking, but they get the job done */
1103         for (std::vector<ZLine*>::iterator i = Instance->XLines->zlines.begin(); i != Instance->XLines->zlines.end(); i++)
1104         {
1105                 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);
1106                 buffer.append(data);
1107         }
1108         for (std::vector<QLine*>::iterator i = Instance->XLines->qlines.begin(); i != Instance->XLines->qlines.end(); i++)
1109         {
1110                 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);
1111                 buffer.append(data);
1112         }
1113         for (std::vector<GLine*>::iterator i = Instance->XLines->glines.begin(); i != Instance->XLines->glines.end(); i++)
1114         {
1115                 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);
1116                 buffer.append(data);
1117         }
1118         for (std::vector<ELine*>::iterator i = Instance->XLines->elines.begin(); i != Instance->XLines->elines.end(); i++)
1119         {
1120                 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);
1121                 buffer.append(data);
1122         }
1123         for (std::vector<ZLine*>::iterator i = Instance->XLines->pzlines.begin(); i != Instance->XLines->pzlines.end(); i++)
1124         {
1125                 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);
1126                 buffer.append(data);
1127         }
1128         for (std::vector<QLine*>::iterator i = Instance->XLines->pqlines.begin(); i != Instance->XLines->pqlines.end(); i++)
1129         {
1130                 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);
1131                 buffer.append(data);
1132         }
1133         for (std::vector<GLine*>::iterator i = Instance->XLines->pglines.begin(); i != Instance->XLines->pglines.end(); i++)
1134         {
1135                 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);
1136                 buffer.append(data);
1137         }
1138         for (std::vector<ELine*>::iterator i = Instance->XLines->pelines.begin(); i != Instance->XLines->pelines.end(); i++)
1139         {
1140                 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);
1141                 buffer.append(data);
1142         }
1143
1144         if (!buffer.empty())
1145                 this->WriteLine(buffer);
1146 }
1147
1148 /** Send channel modes and topics */
1149 void TreeSocket::SendChannelModes(TreeServer* Current)
1150 {
1151         char data[MAXBUF];
1152         std::deque<std::string> list;
1153         std::string n = this->Instance->Config->ServerName;
1154         const char* sn = n.c_str();
1155         for (chan_hash::iterator c = this->Instance->chanlist->begin(); c != this->Instance->chanlist->end(); c++)
1156         {
1157                 SendFJoins(Current, c->second);
1158                 if (*c->second->topic)
1159                 {
1160                         snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",sn,c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
1161                         this->WriteLine(data);
1162                 }
1163                 FOREACH_MOD_I(this->Instance,I_OnSyncChannel,OnSyncChannel(c->second,(Module*)Utils->Creator,(void*)this));
1164                 list.clear();
1165                 c->second->GetExtList(list);
1166                 for (unsigned int j = 0; j < list.size(); j++)
1167                 {
1168                         FOREACH_MOD_I(this->Instance,I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)Utils->Creator,(void*)this,list[j]));
1169                 }
1170         }
1171 }
1172
1173 /** send all users and their oper state/modes */
1174 void TreeSocket::SendUsers(TreeServer* Current)
1175 {
1176         char data[MAXBUF];
1177         std::deque<std::string> list;
1178         std::string dataline;
1179         for (user_hash::iterator u = this->Instance->clientlist->begin(); u != this->Instance->clientlist->end(); u++)
1180         {
1181                 if (u->second->registered == REG_ALL)
1182                 {
1183                         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);
1184                         this->WriteLine(data);
1185                         if (*u->second->oper)
1186                         {
1187                                 snprintf(data,MAXBUF,":%s OPERTYPE %s", u->second->nick, u->second->oper);
1188                                 this->WriteLine(data);
1189                         }
1190                         if (*u->second->awaymsg)
1191                         {
1192                                 snprintf(data,MAXBUF,":%s AWAY :%s", u->second->nick, u->second->awaymsg);
1193                                 this->WriteLine(data);
1194                         }
1195                         FOREACH_MOD_I(this->Instance,I_OnSyncUser,OnSyncUser(u->second,(Module*)Utils->Creator,(void*)this));
1196                         list.clear();
1197                         u->second->GetExtList(list);
1198
1199                         for (unsigned int j = 0; j < list.size(); j++)
1200                         {
1201                                 FOREACH_MOD_I(this->Instance,I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)Utils->Creator,(void*)this,list[j]));
1202                         }
1203                 }
1204         }
1205 }
1206
1207 /** This function is called when we want to send a netburst to a local
1208  * server. There is a set order we must do this, because for example
1209  * users require their servers to exist, and channels require their
1210  * users to exist. You get the idea.
1211  */
1212 void TreeSocket::DoBurst(TreeServer* s)
1213 {
1214         std::string burst = "BURST "+ConvToStr(Instance->Time(true));
1215         std::string endburst = "ENDBURST";
1216         // Because by the end of the netburst, it  could be gone!
1217         std::string name = s->GetName();
1218         this->Instance->SNO->WriteToSnoMask('l',"Bursting to \2"+name+"\2.");
1219         this->WriteLine(burst);
1220         /* send our version string */
1221         this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" VERSION :"+this->Instance->GetVersionString());
1222         /* Send server tree */
1223         this->SendServers(Utils->TreeRoot,s,1);
1224         /* Send users and their oper status */
1225         this->SendUsers(s);
1226         /* Send everything else (channel modes, xlines etc) */
1227         this->SendChannelModes(s);
1228         this->SendXLines(s);
1229         FOREACH_MOD_I(this->Instance,I_OnSyncOtherMetaData,OnSyncOtherMetaData((Module*)Utils->Creator,(void*)this));
1230         this->WriteLine(endburst);
1231         this->Instance->SNO->WriteToSnoMask('l',"Finished bursting to \2"+name+"\2.");
1232 }
1233
1234 /** This function is called when we receive data from a remote
1235  * server. We buffer the data in a std::string (it doesnt stay
1236  * there for long), reading using InspSocket::Read() which can
1237  * read up to 16 kilobytes in one operation.
1238  *
1239  * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
1240  * THE SOCKET OBJECT FOR US.
1241  */
1242 bool TreeSocket::OnDataReady()
1243 {
1244         char* data = this->Read();
1245         /* Check that the data read is a valid pointer and it has some content */
1246         if (data && *data)
1247         {
1248                 this->in_buffer.append(data);
1249                 /* While there is at least one new line in the buffer,
1250                  * do something useful (we hope!) with it.
1251                  */
1252                 while (in_buffer.find("\n") != std::string::npos)
1253                 {
1254                         std::string ret = in_buffer.substr(0,in_buffer.find("\n")-1);
1255                         in_buffer = in_buffer.substr(in_buffer.find("\n")+1,in_buffer.length()-in_buffer.find("\n"));
1256                         /* Use rfind here not find, as theres more
1257                          * chance of the \r being near the end of the
1258                          * string, not the start.
1259                          */
1260                         if (ret.find("\r") != std::string::npos)
1261                                 ret = in_buffer.substr(0,in_buffer.find("\r")-1);
1262                         /* Process this one, abort if it
1263                          * didnt return true.
1264                          */
1265                         if (!this->ProcessLine(ret))
1266                         {
1267                                 return false;
1268                         }
1269                 }
1270                 return true;
1271         }
1272         /* EAGAIN returns an empty but non-NULL string, so this
1273          * evaluates to TRUE for EAGAIN but to FALSE for EOF.
1274          */
1275         return (data && !*data);
1276 }
1277