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