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