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