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