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