]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/treesocket1.cpp
Support port binding here
[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                 while ((item = capabs.GetToken()) != "")
361                 {
362                         /* Process each key/value pair */
363                         std::string::size_type equals = item.rfind('=');
364                         if (equals != std::string::npos)
365                         {
366                                 std::string var = item.substr(0, equals);
367                                 std::string value = item.substr(equals+1, item.length());
368                                 CapKeys[var] = value;
369                         }
370                 }
371         }
372         return true;
373 }
374
375 /** This function forces this server to quit, removing this server
376  * and any users on it (and servers and users below that, etc etc).
377  * It's very slow and pretty clunky, but luckily unless your network
378  * is having a REAL bad hair day, this function shouldnt be called
379  * too many times a month ;-)
380  */
381 void TreeSocket::SquitServer(std::string &from, TreeServer* Current)
382 {
383         /* recursively squit the servers attached to 'Current'.
384          * We're going backwards so we don't remove users
385          * while we still need them ;)
386          */
387         for (unsigned int q = 0; q < Current->ChildCount(); q++)
388         {
389                 TreeServer* recursive_server = Current->GetChild(q);
390                 this->SquitServer(from,recursive_server);
391         }
392         /* Now we've whacked the kids, whack self */
393         num_lost_servers++;
394         num_lost_users += Current->QuitUsers(from);
395 }
396
397 /** This is a wrapper function for SquitServer above, which
398  * does some validation first and passes on the SQUIT to all
399  * other remaining servers.
400  */
401 void TreeSocket::Squit(TreeServer* Current, const std::string &reason)
402 {
403         if ((Current) && (Current != Utils->TreeRoot))
404         {
405                 Event rmode((char*)Current->GetName().c_str(), (Module*)Utils->Creator, "lost_server");
406                 rmode.Send(Instance);
407
408                 std::deque<std::string> params;
409                 params.push_back(Current->GetName());
410                 params.push_back(":"+reason);
411                 Utils->DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
412                 if (Current->GetParent() == Utils->TreeRoot)
413                 {
414                         this->Instance->WriteOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
415                 }
416                 else
417                 {
418                         this->Instance->WriteOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
419                 }
420                 num_lost_servers = 0;
421                 num_lost_users = 0;
422                 std::string from = Current->GetParent()->GetName()+" "+Current->GetName();
423                 SquitServer(from, Current);
424                 Current->Tidy();
425                 Current->GetParent()->DelChild(Current);
426                 DELETE(Current);
427                 this->Instance->WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
428         }
429         else
430         {
431                 Instance->Log(DEFAULT,"Squit from unknown server");
432         }
433 }
434
435 /** FMODE command - server mode with timestamp checks */
436 bool TreeSocket::ForceMode(const std::string &source, std::deque<std::string> &params)
437 {
438         /* Chances are this is a 1.0 FMODE without TS */
439         if (params.size() < 3)
440         {
441                 /* No modes were in the command, probably a channel with no modes set on it */
442                 return true;
443         }
444
445         bool smode = false;
446         std::string sourceserv;
447         /* Are we dealing with an FMODE from a user, or from a server? */
448         userrec* who = this->Instance->FindNick(source);
449         if (who)
450         {
451                 /* FMODE from a user, set sourceserv to the users server name */
452                 sourceserv = who->server;
453         }
454         else
455         {
456                 /* FMODE from a server, create a fake user to receive mode feedback */
457                 who = new userrec(this->Instance);
458                 who->SetFd(FD_MAGIC_NUMBER);
459                 smode = true;      /* Setting this flag tells us we should free the userrec later */
460                 sourceserv = source;    /* Set sourceserv to the actual source string */
461         }
462         const char* modelist[64];
463         time_t TS = 0;
464         int n = 0;
465         memset(&modelist,0,sizeof(modelist));
466         for (unsigned int q = 0; (q < params.size()) && (q < 64); q++)
467         {
468                 if (q == 1)
469                 {
470                         /* The timestamp is in this position.
471                          * We don't want to pass that up to the
472                          * server->client protocol!
473                          */
474                         TS = atoi(params[q].c_str());
475                 }
476                 else
477                 {
478                         /* Everything else is fine to append to the modelist */
479                         modelist[n++] = params[q].c_str();
480                 }
481
482         }
483         /* Extract the TS value of the object, either userrec or chanrec */
484         userrec* dst = this->Instance->FindNick(params[0]);
485         chanrec* chan = NULL;
486         time_t ourTS = 0;
487         if (dst)
488         {
489                 ourTS = dst->age;
490         }
491         else
492         {
493                 chan = this->Instance->FindChan(params[0]);
494                 if (chan)
495                 {
496                         ourTS = chan->age;
497                 }
498                 else
499                         /* Oops, channel doesnt exist! */
500                         return true;
501         }
502
503         /* TS is equal: Merge the mode changes, use voooodoooooo on modes
504          * with parameters.
505          */
506         if (TS == ourTS)
507         {
508                 ModeHandler* mh = NULL;
509                 unsigned long paramptr = 3;
510                 std::string to_bounce = "";
511                 std::string to_keep = "";
512                 std::vector<std::string> params_to_keep;
513                 std::string params_to_bounce = "";
514                 bool adding = true;
515                 char cur_change = 1;
516                 char old_change = 0;
517                 char old_bounce_change = 0;
518                 /* Merge modes, basically do special stuff to mode with params */
519                 for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
520                 {
521                         switch (*x)
522                         {
523                                 case '-':
524                                         adding = false;
525                                 break;
526                                 case '+':
527                                         adding = true;
528                                 break;
529                                 default:
530                                         if (adding)
531                                         {
532                                                 /* We only care about whats being set,
533                                                  * not whats being unset
534                                                  */
535                                                 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
536                                                 if ((mh) && (mh->GetNumParams(adding) > 0) && (!mh->IsListMode()))
537                                                 {
538                                                         /* We only want to do special things to
539                                                          * modes with parameters, we are going to rewrite
540                                                          * those parameters
541                                                          */
542                                                         ModePair ret;
543                                                         adding ? cur_change = '+' : cur_change = '-';
544                                                         ret = mh->ModeSet(smode ? NULL : who, dst, chan, params[paramptr]);
545                                                         /* The mode is set here, check which we should keep */
546                                                         if (ret.first)
547                                                         {
548                                                                 bool which_to_keep = mh->CheckTimeStamp(TS, ourTS, params[paramptr], ret.second, chan);
549                                                                 if (which_to_keep == true)
550                                                                 {
551                                                                         /* Keep ours, bounce theirs:
552                                                                          * Send back ours to them and
553                                                                          * drop their mode changs
554                                                                          */
555                                                                         adding ? cur_change = '+' : cur_change = '-';
556                                                                         if (cur_change != old_bounce_change)
557                                                                                 to_bounce += cur_change;
558                                                                         to_bounce += *x;
559                                                                         old_bounce_change = cur_change;
560                                                                         if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
561                                                                                 params_to_bounce.append(" ").append(ret.second);
562                                                                 }
563                                                                 else
564                                                                 {
565                                                                         /* Keep theirs: Accept their mode change,
566                                                                          * do nothing else
567                                                                          */
568                                                                         adding ? cur_change = '+' : cur_change = '-';
569                                                                         if (cur_change != old_change)
570                                                                                 to_keep += cur_change;
571                                                                         to_keep += *x;
572                                                                         old_change = cur_change;
573                                                                         if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
574                                                                                 params_to_keep.push_back(params[paramptr]);
575                                                                 }
576                                                         }
577                                                         else
578                                                         {
579                                                                 /* Mode isnt set here, we want it */
580                                                                 adding ? cur_change = '+' : cur_change = '-';
581                                                                 if (cur_change != old_change)
582                                                                         to_keep += cur_change;
583                                                                 to_keep += *x;
584                                                                 old_change = cur_change;
585                                                                 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
586                                                                         params_to_keep.push_back(params[paramptr]);
587                                                         }
588                                                         paramptr++;
589                                                 }
590                                                 else
591                                                 {
592                                                         mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
593                                                         if (mh)
594                                                         {
595                                                                 adding ? cur_change = '+' : cur_change = '-';
596
597                                                                 /* Just keep this, safe to merge with no checks
598                                                                  * it has no parameters
599                                                                  */
600
601                                                                 if (cur_change != old_change)
602                                                                         to_keep += cur_change;
603                                                                 to_keep += *x;
604                                                                 old_change = cur_change;
605
606                                                                 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
607                                                                 {
608                                                                         params_to_keep.push_back(params[paramptr++]);
609                                                                 }
610                                                         }
611                                                 }
612                                         }
613                                         else
614                                         {
615                                                 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
616                                                 if (mh)
617                                                 {
618                                                         /* Taking a mode away */
619                                                         adding ? cur_change = '+' : cur_change = '-';
620                                                         if (cur_change != old_change)
621                                                                 to_keep += cur_change;
622                                                         to_keep += *x;
623                                                         old_change = cur_change;
624                                                         if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
625                                                                 params_to_keep.push_back(params[paramptr++]);
626                                                 }
627                                         }
628                                 break;
629                         }
630                 }
631                 if (to_bounce.length())
632                 {
633                         std::deque<std::string> newparams;
634                         newparams.push_back(params[0]);
635                         newparams.push_back(ConvToStr(ourTS));
636                         newparams.push_back(to_bounce+params_to_bounce);
637                         Utils->DoOneToOne(this->Instance->Config->ServerName,"FMODE",newparams,sourceserv);
638                 }
639                 if (to_keep.length())
640                 {
641                         unsigned int n = 2;
642                         unsigned int q = 0;
643                         modelist[0] = params[0].c_str();
644                         modelist[1] = to_keep.c_str();
645                         if (params_to_keep.size() > 0)
646                         {
647                                 for (q = 0; (q < params_to_keep.size()) && (q < 64); q++)
648                                 {
649                                         modelist[n++] = params_to_keep[q].c_str();
650                                 }
651                         }
652                         if (smode)
653                         {
654                                 this->Instance->SendMode(modelist, n, who);
655                         }
656                         else
657                         {
658                                 this->Instance->CallCommandHandler("MODE", modelist, n, who);
659                         }
660                         /* HOT POTATO! PASS IT ON! */
661                         Utils->DoOneToAllButSender(source,"FMODE",params,sourceserv);
662                 }
663         }
664         else
665         /* U-lined servers always win regardless of their TS */
666         if ((TS > ourTS) && (!this->Instance->ULine(source.c_str())))
667         {
668                 /* Bounce the mode back to its sender.* We use our lower TS, so the other end
669                  * SHOULD accept it, if its clock is right.
670                  *
671                  * NOTE: We should check that we arent bouncing anything thats already set at this end.
672                  * If we are, bounce +ourmode to 'reinforce' it. This prevents desyncs.
673                  * e.g. They send +l 50, we have +l 10 set. rather than bounce -l 50, we bounce +l 10.
674                  *
675                  * Thanks to jilles for pointing out this one-hell-of-an-issue before i even finished
676                  * writing the code. It took me a while to come up with this solution.
677                  *
678                  * XXX: BE SURE YOU UNDERSTAND THIS CODE FULLY BEFORE YOU MESS WITH IT.
679                  */
680                 std::deque<std::string> newparams;      /* New parameter list we send back */
681                 newparams.push_back(params[0]);  /* Target, user or channel */
682                 newparams.push_back(ConvToStr(ourTS));  /* Timestamp value of the target */
683                 newparams.push_back("");                /* This contains the mode string. For now
684                                                          * it's empty, we fill it below.
685                                                          */
686                 /* Intelligent mode bouncing. Don't just invert, reinforce any modes which are already
687                  * set to avoid a desync here.
688                  */
689                 std::string modebounce = "";
690                 bool adding = true;
691                 unsigned int t = 3;
692                 ModeHandler* mh = NULL;
693                 char cur_change = 1;
694                 char old_change = 0;
695                 for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
696                 {
697                         /* Iterate over all mode chars in the sent set */
698                         switch (*x)
699                         {
700                                 /* Adding or subtracting modes? */
701                                 case '-':
702                                         adding = false;
703                                 break;
704                                 case '+':
705                                         adding = true;
706                                 break;
707                                 default:
708                                         /* Find the mode handler for this mode */
709                                         mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
710                                         /* Got a mode handler?
711                                          * This also prevents us bouncing modes we have no handler for.
712                                          */
713                                         if (mh)
714                                         {
715                                                 ModePair ret;
716                                                 std::string p = "";
717                                                 /* Does the mode require a parameter right now?
718                                                  * If it does, fetch it if we can
719                                                  */
720                                                 if ((mh->GetNumParams(adding) > 0) && (t < params.size()))
721                                                         p = params[t++];
722                                                 /* Call the ModeSet method to determine if its set with the
723                                                  * given parameter here or not.
724                                                  */
725                                                 ret = mh->ModeSet(smode ? NULL : who, dst, chan, p);
726                                                 /* XXX: Really. Dont ask.
727                                                  * Determine from if its set combined with what the current
728                                                  * 'state' is (adding or not) as to wether we should 'invert'
729                                                  * or 'reinforce' the mode change
730                                                  */
731                                                 (!ret.first ? (adding ? cur_change = '-' : cur_change = '+') : (!adding ? cur_change = '-' : cur_change = '+'));
732                                                 /* Quickly determine if we have 'flipped' from + to -,
733                                                  * or - to +, to prevent unneccessary +/- chars in the
734                                                  * output string that waste bandwidth
735                                                  */
736                                                 if (cur_change != old_change)
737                                                         modebounce += cur_change;
738                                                 old_change = cur_change;
739                                                 /* Add the mode character to the output string */
740                                                 modebounce += mh->GetModeChar();
741                                                 /* We got a parameter back from ModeHandler::ModeSet,
742                                                  * are we supposed to be sending one out right now?
743                                                  */
744                                                 if (ret.second.length())
745                                                 {
746                                                         if (mh->GetNumParams(cur_change == '+') > 0)
747                                                                 /* Yes we're supposed to be sending out
748                                                                  * the parameter. Make sure it goes
749                                                                  */
750                                                                 newparams.push_back(ret.second);
751                                                 }
752                                         }
753                                 break;
754                         }
755                 }
756
757                 /* Update the parameters for FMODE with the new 'bounced' string */
758                 newparams[2] = modebounce;
759                 /* Only send it back the way it came, no need to send it anywhere else */
760                 Utils->DoOneToOne(this->Instance->Config->ServerName,"FMODE",newparams,sourceserv);
761         }
762         else
763         {
764                 /* The server was ulined, but something iffy is up with the TS.
765                  * Sound the alarm bells!
766                  */
767                 if ((this->Instance->ULine(sourceserv.c_str())) && (TS > ourTS))
768                 {
769                         this->Instance->WriteOpers("\2WARNING!\2 U-Lined server '%s' has bad TS for '%s' (accepted change): \2SYNC YOUR CLOCKS\2 to avoid this notice",sourceserv.c_str(),params[0].c_str());
770                 }
771                 /* Allow the mode, route it to either server or user command handling */
772                 if (smode)
773                         this->Instance->SendMode(modelist,n,who);
774                 else
775                         this->Instance->CallCommandHandler("MODE", modelist, n, who);
776                 /* HOT POTATO! PASS IT ON! */
777                 Utils->DoOneToAllButSender(source,"FMODE",params,sourceserv);
778         }
779         /* Are we supposed to free the userrec? */
780         if (smode)
781                 DELETE(who);
782
783         return true;
784 }
785
786 /** FTOPIC command */
787 bool TreeSocket::ForceTopic(const std::string &source, std::deque<std::string> &params)
788 {
789         if (params.size() != 4)
790                 return true;
791         time_t ts = atoi(params[1].c_str());
792         std::string nsource = source;
793         chanrec* c = this->Instance->FindChan(params[0]);
794         if (c)
795         {
796                 if ((ts >= c->topicset) || (!*c->topic))
797                 {
798                         std::string oldtopic = c->topic;
799                         strlcpy(c->topic,params[3].c_str(),MAXTOPIC);
800                         strlcpy(c->setby,params[2].c_str(),NICKMAX-1);
801                         c->topicset = ts;
802                         /* if the topic text is the same as the current topic,
803                          * dont bother to send the TOPIC command out, just silently
804                          * update the set time and set nick.
805                          */
806                         if (oldtopic != params[3])
807                         {
808                                 userrec* user = this->Instance->FindNick(source);
809                                 if (!user)
810                                 {
811                                         c->WriteChannelWithServ(source.c_str(), "TOPIC %s :%s", c->name, c->topic);
812                                 }
813                                 else
814                                 {
815                                         c->WriteChannel(user, "TOPIC %s :%s", c->name, c->topic);
816                                         nsource = user->server;
817                                 }
818                                 /* all done, send it on its way */
819                                 params[3] = ":" + params[3];
820                                 Utils->DoOneToAllButSender(source,"FTOPIC",params,nsource);
821                         }
822                 }
823
824         }
825         return true;
826 }
827
828 /** FJOIN, similar to TS6 SJOIN, but not quite. */
829 bool TreeSocket::ForceJoin(const std::string &source, std::deque<std::string> &params)
830 {
831         /* 1.1 FJOIN works as follows:
832          *
833          * Each FJOIN is sent along with a timestamp, and the side with the lowest
834          * timestamp 'wins'. From this point on we will refer to this side as the
835          * winner. The side with the higher timestamp loses, from this point on we
836          * will call this side the loser or losing side. This should be familiar to
837          * anyone who's dealt with dreamforge or TS6 before.
838          *
839          * When two sides of a split heal and this occurs, the following things
840          * will happen:
841          *
842          * If the timestamps are exactly equal, both sides merge their privilages
843          * and users, as in InspIRCd 1.0 and ircd2.8. The channels have not been
844          * re-created during a split, this is safe to do.
845          *
846          *
847          * If the timestamps are NOT equal, the losing side removes all privilage
848          * modes from all of its users that currently exist in the channel, before
849          * introducing new users into the channel which are listed in the FJOIN
850          * command's parameters. This means, all modes +ohv, and privilages added
851          * by modules, such as +qa. The losing side then LOWERS its timestamp value
852          * of the channel to match that of the winning side, and the modes of the
853          * users of the winning side are merged in with the losing side. The loser
854          * then sends out a set of FMODE commands which 'confirm' that it just
855          * removed all privilage modes from its existing users, which allows for
856          * services packages to still work correctly without needing to know the
857          * timestamping rules which InspIRCd follows. In TS6 servers this is always
858          * a problem, and services packages must contain code which explicitly
859          * behaves as TS6 does, removing ops from the losing side of a split where
860          * neccessary within its internal records, as this state information is
861          * not explicitly echoed out in that protocol.
862          *
863          * The winning side on the other hand will ignore all user modes from the
864          * losing side, so only its own modes get applied. Life is simple for those
865          * who succeed at internets. :-)
866          *
867          * NOTE: Unlike TS6 and dreamforge and other protocols which have SJOIN,
868          * FJOIN does not contain the simple-modes such as +iklmnsp. Why not,
869          * you ask? Well, quite simply because we don't need to. They'll be sent
870          * after the FJOIN by FMODE, and FMODE is timestamped, so in the event
871          * the losing side sends any modes for the channel which shouldnt win,
872          * they wont as their timestamp will be too high :-)
873          */
874
875         if (params.size() < 3)
876                 return true;
877
878         char first[MAXBUF];          /* The first parameter of the mode command */
879         char modestring[MAXBUF];        /* The mode sequence (2nd parameter) of the mode command */
880         char* mode_users[127];    /* The values used by the mode command */
881         memset(&mode_users,0,sizeof(mode_users));       /* Initialize mode parameters */
882         mode_users[0] = first;    /* Set this up to be our on-stack value */
883         mode_users[1] = modestring;     /* Same here as above */
884         strcpy(modestring,"+");  /* Initialize the mode sequence to just '+' */
885         unsigned int modectr = 2;       /* Pointer to the third mode parameter (e.g. the one after the +-sequence) */
886
887         userrec* who = NULL;                /* User we are currently checking */
888         std::string channel = params[0];        /* Channel name, as a string */
889         time_t TS = atoi(params[1].c_str());    /* Timestamp given to us for remote side */
890         bool created = false;
891
892         /* Try and find the channel */
893         chanrec* chan = this->Instance->FindChan(channel);
894
895         /* Initialize channel name in the mode parameters */
896         strlcpy(mode_users[0],channel.c_str(),MAXBUF);
897
898         /* default TS is a high value, which if we dont have this
899          * channel will let the other side apply their modes.
900          */
901         time_t ourTS = Instance->Time(true)+600;
902         /* Does this channel exist? if it does, get its REAL timestamp */
903         if (chan)
904                 ourTS = chan->age;
905         else
906                 created = true; /* don't perform deops, and set TS to correct time after processing. */
907         /* In 1.1, if they have the newer channel, we immediately clear
908          * all status modes from our users. We then accept their modes.
909          * If WE have the newer channel its the other side's job to do this.
910          * Note that this causes the losing server to send out confirming
911          * FMODE lines.
912          */
913         if (ourTS > TS)
914         {
915                 std::deque<std::string> param_list;
916                 /* Lower the TS here */
917                 if (Utils->AnnounceTSChange && chan)
918                         chan->WriteChannelWithServ(Instance->Config->ServerName,
919                         "NOTICE %s :TS for %s changed from %lu to %lu", chan->name, chan->name, ourTS, TS);
920                 ourTS = TS;
921                 /* Zap all the privilage modes on our side, if the channel exists here */
922                 if (!created)
923                 {
924                         param_list.push_back(channel);
925                         /* Do this first! */
926                         chan->age = TS;
927                         this->RemoveStatus(Instance->Config->ServerName, param_list);
928                 }
929         }
930         /* Put the final parameter of the FJOIN into a tokenstream ready to split it */
931         irc::tokenstream users(params[2]);
932         std::string item = "*";
933         /* do this first, so our mode reversals are correctly received by other servers
934          * if there is a TS collision.
935          */
936         params[2] = ":" + params[2];
937         Utils->DoOneToAllButSender(source,"FJOIN",params,source);
938         /* Now, process every 'prefixes,nick' pair */
939         while (item != "")
940         {
941                 /* Find next user */
942                 item = users.GetToken();
943                 const char* usr = item.c_str();
944                 /* Safety check just to make sure someones not sent us an FJOIN full of spaces
945                  * (is this even possible?) */
946                 if (usr && *usr)
947                 {
948                         const char* permissions = usr;
949                         int ntimes = 0;
950                         char* nm = new char[MAXBUF];
951                         char* tnm = nm;
952                         /* Iterate through all the prefix values, convert them from prefixes
953                          * to mode letters, and append them to the mode sequence
954                          */
955                         while ((*permissions) && (*permissions != ',') && (ntimes < MAXBUF))
956                         {
957                                 ModeHandler* mh = Instance->Modes->FindPrefix(*permissions);
958                                 if (mh)
959                                 {
960                                         /* This is a valid prefix */
961                                         ntimes++;
962                                         *tnm++ = mh->GetModeChar();
963                                 }
964                                 else
965                                 {
966                                         /* Not a valid prefix...
967                                          * danger bill bobbertson! (that's will robinsons older brother ;-) ...)
968                                          */
969                                         this->Instance->WriteOpers("ERROR: We received a user with an unknown prefix '%c'. Closed connection to avoid a desync.",*permissions);
970                                         this->WriteLine(std::string("ERROR :Invalid prefix '")+(*permissions)+"' in FJOIN");
971                                         return false;
972                                 }
973                                 usr++;
974                                 permissions++;
975                         }
976                         /* Null terminate modes */
977                         *tnm = 0;
978                         /* Advance past the comma, to the nick */
979                         usr++;
980                         /* Check the user actually exists */
981                         who = this->Instance->FindNick(usr);
982                         if (who)
983                         {
984                                 /* Check that the user's 'direction' is correct
985                                  * based on the server sending the FJOIN. We must
986                                  * check each nickname in turn, because the origin of
987                                  * the FJOIN may be different to the origin of the nicks
988                                  * in the command itself.
989                                  */
990                                 TreeServer* route_back_again = Utils->BestRouteTo(who->server);
991                                 if ((!route_back_again) || (route_back_again->GetSocket() != this))
992                                 {
993                                         /* Oh dear oh dear. */
994                                         delete[] nm;
995                                         continue;
996                                 }
997
998                                 /* NOTE: Moved this below the fake direction check, so that modes
999                                  * arent put into the mode list for users that were collided, and
1000                                  * may reconnect from the other side or our side before the split
1001                                  * is completed!
1002                                  */
1003
1004                                 /* Did they get any modes? How many times? */
1005                                 strlcat(modestring, nm, MAXBUF);
1006                                 for (int k = 0; k < ntimes; k++)
1007                                         mode_users[modectr++] = strdup(usr);
1008                                 /* Free temporary buffer used for mode sequence */
1009                                 delete[] nm;
1010
1011                                 /* Finally, we can actually place the user into the channel.
1012                                  * We're sure its right. Final answer, phone a friend.
1013                                  */
1014                                 chanrec::JoinUser(this->Instance, who, channel.c_str(), true, "");
1015                                 /* Have we already queued up MAXMODES modes with parameters
1016                                  * (+qaohv) ready to be sent to the server?
1017                                  */
1018                                 if (modectr >= (MAXMODES-1))
1019                                 {
1020                                         /* Only actually give the users any status if we lost
1021                                          * the FJOIN or drew (equal timestamps).
1022                                          * It isn't actually possible for ourTS to be > TS here,
1023                                          * only possible to actually have ourTS == TS, or
1024                                          * ourTS < TS, because if we lost, we already lowered
1025                                          * our TS above before we entered this loop. We only
1026                                          * check >= as a safety measure, in case someone stuffed
1027                                          * up. If someone DID stuff up, it was most likely me.
1028                                          * Note: I do not like baseball bats in the face...
1029                                          */
1030                                         if (ourTS >= TS)
1031                                         {
1032                                                 this->Instance->SendMode((const char**)mode_users,modectr,who);
1033
1034                                                 /* Something stuffed up, and for some reason, the timestamp is
1035                                                  * NOT lowered right now and should be. Lower it. Usually this
1036                                                  * code won't be executed, doubtless someone will remove it some
1037                                                  * day soon.
1038                                                  */
1039                                                 if (ourTS > TS)
1040                                                 {
1041                                                         Instance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",chan->name,ourTS,TS);
1042                                                         chan->age = TS;
1043                                                         ourTS = TS;
1044                                                 }
1045                                         }
1046
1047                                         /* Reset all this back to defaults, and
1048                                          * free any ram we have left allocated.
1049                                          */
1050                                         strcpy(mode_users[1],"+");
1051                                         for (unsigned int f = 2; f < modectr; f++)
1052                                                 free(mode_users[f]);
1053                                         modectr = 2;
1054                                 }
1055                         }
1056                         else
1057                         {
1058                                 /* Remember to free this */
1059                                 delete[] nm;
1060                                 /* If we got here, there's a nick in FJOIN which doesnt exist on this server.
1061                                  * We don't try to process the nickname here (that WOULD cause a segfault because
1062                                  * we'd be playing with null pointers) however, we DO pass the nickname on, just
1063                                  * in case somehow we're desynched, so that other users which might be able to see
1064                                  * the nickname get their fair chance to process it.
1065                                  */
1066                                 Instance->Log(SPARSE,"Warning! Invalid user %s in FJOIN to channel %s IGNORED", usr, channel.c_str());
1067                                 continue;
1068                         }
1069                 }
1070         }
1071
1072         /* there werent enough modes built up to flush it during FJOIN,
1073          * or, there are a number left over. flush them out.
1074          */
1075         if ((modectr > 2) && (who) && (chan))
1076         {
1077                 if (ourTS >= TS)
1078                 {
1079                         /* Our channel is newer than theirs. Evil deeds must be afoot. */
1080                         this->Instance->SendMode((const char**)mode_users,modectr,who);
1081                         /* Yet again, we can't actually get a true value here, if everything else
1082                          * is working as it should.
1083                          */
1084                         if (ourTS > TS)
1085                         {
1086                                 Instance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",chan->name,ourTS,TS);
1087                                 chan->age = TS;
1088                                 ourTS = TS;
1089                         }
1090                 }
1091
1092                 /* Free anything we have left to free */
1093                 for (unsigned int f = 2; f < modectr; f++)
1094                         free(mode_users[f]);
1095         }
1096         /* if we newly created the channel, set it's TS properly. */
1097         if (created)
1098         {
1099                 /* find created channel .. */
1100                 chan = this->Instance->FindChan(channel);
1101                 if (chan)
1102                         /* w00t said this shouldnt be needed but it is.
1103                          * This isnt strictly true, as chan can be NULL
1104                          * if a nick collision has occured and therefore
1105                          * the channel was never created.
1106                          */
1107                         chan->age = TS;
1108         }
1109         /* All done. That wasnt so bad was it, you can wipe
1110          * the sweat from your forehead now. :-)
1111          */
1112         return true;
1113 }
1114
1115 /** NICK command */
1116 bool TreeSocket::IntroduceClient(const std::string &source, std::deque<std::string> &params)
1117 {
1118         if (params.size() < 8)
1119                 return true;
1120         if (params.size() > 8)
1121         {
1122                 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[1]+"?)");
1123                 return true;
1124         }
1125         // NICK age nick host dhost ident +modes ip :gecos
1126         //       0    1   2     3     4      5   6     7
1127         time_t age = atoi(params[0].c_str());
1128
1129         const char* tempnick = params[1].c_str();
1130         Instance->Log(DEBUG,"New remote client %s",tempnick);
1131
1132         user_hash::iterator iter = this->Instance->clientlist->find(tempnick);
1133
1134         if (iter != this->Instance->clientlist->end())
1135         {
1136                 // nick collision
1137                 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+tempnick+" :Nickname collision");
1138                 userrec::QuitUser(this->Instance, iter->second, "Nickname collision");
1139                 return true;
1140         }
1141
1142         userrec* _new = new userrec(this->Instance);
1143         (*(this->Instance->clientlist))[tempnick] = _new;
1144         _new->SetFd(FD_MAGIC_NUMBER);
1145         strlcpy(_new->nick, tempnick,NICKMAX-1);
1146         strlcpy(_new->host, params[2].c_str(),63);
1147         strlcpy(_new->dhost, params[3].c_str(),63);
1148         _new->server = this->Instance->FindServerNamePtr(source.c_str());
1149         strlcpy(_new->ident, params[4].c_str(),IDENTMAX);
1150         strlcpy(_new->fullname, params[7].c_str(),MAXGECOS);
1151         _new->registered = REG_ALL;
1152         _new->signon = age;
1153
1154         /*
1155          * we need to remove the + from the modestring, so we can do our stuff
1156          */
1157         std::string::size_type pos_after_plus = params[5].find_first_not_of('+');
1158         if (pos_after_plus != std::string::npos)
1159         params[5] = params[5].substr(pos_after_plus);
1160
1161         for (std::string::iterator v = params[5].begin(); v != params[5].end(); v++)
1162         {
1163                 _new->modes[(*v)-65] = 1;
1164                 /* For each mode thats set, increase counter */
1165                 ModeHandler* mh = Instance->Modes->FindMode(*v, MODETYPE_USER);
1166                 if (mh)
1167                         mh->ChangeCount(1);
1168         }
1169
1170         /* now we've done with modes processing, put the + back for remote servers */
1171         params[5] = "+" + params[5];
1172
1173 #ifdef SUPPORT_IP6LINKS
1174         if (params[6].find_first_of(":") != std::string::npos)
1175                 _new->SetSockAddr(AF_INET6, params[6].c_str(), 0);
1176         else
1177 #endif
1178                 _new->SetSockAddr(AF_INET, params[6].c_str(), 0);
1179
1180         Instance->AddGlobalClone(_new);
1181         this->Instance->SNO->WriteToSnoMask('C',"Client connecting at %s: %s!%s@%s [%s]",_new->server,_new->nick,_new->ident,_new->host, _new->GetIPString());
1182
1183         params[7] = ":" + params[7];
1184         Utils->DoOneToAllButSender(source,"NICK", params, source);
1185
1186         // Increment the Source Servers User Count..
1187         TreeServer* SourceServer = Utils->FindServer(source);
1188         if (SourceServer)
1189         {
1190                 SourceServer->AddUserCount();
1191         }
1192
1193         FOREACH_MOD_I(Instance,I_OnPostConnect,OnPostConnect(_new));
1194
1195         return true;
1196 }
1197
1198 /** Send one or more FJOINs for a channel of users.
1199  * If the length of a single line is more than 480-NICKMAX
1200  * in length, it is split over multiple lines.
1201  */
1202 void TreeSocket::SendFJoins(TreeServer* Current, chanrec* c)
1203 {
1204         std::string buffer;
1205         char list[MAXBUF];
1206         std::string individual_halfops = std::string(":")+this->Instance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age);
1207
1208         size_t dlen, curlen;
1209         dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1210         int numusers = 0;
1211         char* ptr = list + dlen;
1212
1213         CUList *ulist = c->GetUsers();
1214         std::string modes = "";
1215         std::string params = "";
1216
1217         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1218         {
1219                 // The first parameter gets a : before it
1220                 size_t ptrlen = snprintf(ptr, MAXBUF, " %s%s,%s", !numusers ? ":" : "", c->GetAllPrefixChars(i->second), i->second->nick);
1221
1222                 curlen += ptrlen;
1223                 ptr += ptrlen;
1224
1225                 numusers++;
1226
1227                 if (curlen > (480-NICKMAX))
1228                 {
1229                         buffer.append(list).append("\r\n");
1230                         dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1231                         ptr = list + dlen;
1232                         ptrlen = 0;
1233                         numusers = 0;
1234                 }
1235         }
1236
1237         if (numusers)
1238                 buffer.append(list).append("\r\n");
1239
1240         /* Sorry for the hax. Because newly created channels assume +nt,
1241          * if this channel doesnt have +nt, explicitly send -n and -t for the missing modes.
1242          */
1243         bool inverted = false;
1244         if (!c->IsModeSet('n'))
1245         {
1246                 modes.append("-n");
1247                 inverted = true;
1248         }
1249         if (!c->IsModeSet('t'))
1250         {
1251                 modes.append("-t");
1252                 inverted = true;
1253         }
1254         if (inverted)
1255         {
1256                 modes.append("+");
1257         }
1258
1259         for (BanList::iterator b = c->bans.begin(); b != c->bans.end(); b++)
1260         {
1261                 modes.append("b");
1262                 params.append(" ").append(b->data);
1263                 if (params.length() >= MAXMODES)
1264                 {
1265                         /* Wrap at MAXMODES */
1266                         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");
1267                         modes = "";
1268                         params = "";
1269                 }
1270         }
1271         buffer.append(":").append(this->Instance->Config->ServerName).append(" FMODE ").append(c->name).append(" ").append(ConvToStr(c->age)).append(" +").append(c->ChanModes(true));
1272
1273         /* Only send these if there are any */
1274         if (!modes.empty())
1275                 buffer.append("\r\n").append(":").append(this->Instance->Config->ServerName).append(" FMODE ").append(c->name).append(" ").append(ConvToStr(c->age)).append(" +").append(modes).append(params);
1276
1277         this->WriteLine(buffer);
1278 }
1279
1280 /** Send G, Q, Z and E lines */
1281 void TreeSocket::SendXLines(TreeServer* Current)
1282 {
1283         char data[MAXBUF];
1284         std::string buffer;
1285         std::string n = this->Instance->Config->ServerName;
1286         const char* sn = n.c_str();
1287         /* Yes, these arent too nice looking, but they get the job done */
1288         for (std::vector<ZLine*>::iterator i = Instance->XLines->zlines.begin(); i != Instance->XLines->zlines.end(); i++)
1289         {
1290                 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);
1291                 buffer.append(data);
1292         }
1293         for (std::vector<QLine*>::iterator i = Instance->XLines->qlines.begin(); i != Instance->XLines->qlines.end(); i++)
1294         {
1295                 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);
1296                 buffer.append(data);
1297         }
1298         for (std::vector<GLine*>::iterator i = Instance->XLines->glines.begin(); i != Instance->XLines->glines.end(); i++)
1299         {
1300                 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);
1301                 buffer.append(data);
1302         }
1303         for (std::vector<ELine*>::iterator i = Instance->XLines->elines.begin(); i != Instance->XLines->elines.end(); i++)
1304         {
1305                 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);
1306                 buffer.append(data);
1307         }
1308         for (std::vector<ZLine*>::iterator i = Instance->XLines->pzlines.begin(); i != Instance->XLines->pzlines.end(); i++)
1309         {
1310                 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);
1311                 buffer.append(data);
1312         }
1313         for (std::vector<QLine*>::iterator i = Instance->XLines->pqlines.begin(); i != Instance->XLines->pqlines.end(); i++)
1314         {
1315                 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);
1316                 buffer.append(data);
1317         }
1318         for (std::vector<GLine*>::iterator i = Instance->XLines->pglines.begin(); i != Instance->XLines->pglines.end(); i++)
1319         {
1320                 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);
1321                 buffer.append(data);
1322         }
1323         for (std::vector<ELine*>::iterator i = Instance->XLines->pelines.begin(); i != Instance->XLines->pelines.end(); i++)
1324         {
1325                 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);
1326                 buffer.append(data);
1327         }
1328
1329         if (!buffer.empty())
1330                 this->WriteLine(buffer);
1331 }
1332
1333 /** Send channel modes and topics */
1334 void TreeSocket::SendChannelModes(TreeServer* Current)
1335 {
1336         char data[MAXBUF];
1337         std::deque<std::string> list;
1338         std::string n = this->Instance->Config->ServerName;
1339         const char* sn = n.c_str();
1340         for (chan_hash::iterator c = this->Instance->chanlist->begin(); c != this->Instance->chanlist->end(); c++)
1341         {
1342                 SendFJoins(Current, c->second);
1343                 if (*c->second->topic)
1344                 {
1345                         snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",sn,c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
1346                         this->WriteLine(data);
1347                 }
1348                 FOREACH_MOD_I(this->Instance,I_OnSyncChannel,OnSyncChannel(c->second,(Module*)Utils->Creator,(void*)this));
1349                 list.clear();
1350                 c->second->GetExtList(list);
1351                 for (unsigned int j = 0; j < list.size(); j++)
1352                 {
1353                         FOREACH_MOD_I(this->Instance,I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)Utils->Creator,(void*)this,list[j]));
1354                 }
1355         }
1356 }
1357
1358 /** send all users and their oper state/modes */
1359 void TreeSocket::SendUsers(TreeServer* Current)
1360 {
1361         char data[MAXBUF];
1362         std::deque<std::string> list;
1363         std::string dataline;
1364         for (user_hash::iterator u = this->Instance->clientlist->begin(); u != this->Instance->clientlist->end(); u++)
1365         {
1366                 if (u->second->registered == REG_ALL)
1367                 {
1368                         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);
1369                         this->WriteLine(data);
1370                         if (*u->second->oper)
1371                         {
1372                                 snprintf(data,MAXBUF,":%s OPERTYPE %s", u->second->nick, u->second->oper);
1373                                 this->WriteLine(data);
1374                         }
1375                         if (*u->second->awaymsg)
1376                         {
1377                                 snprintf(data,MAXBUF,":%s AWAY :%s", u->second->nick, u->second->awaymsg);
1378                                 this->WriteLine(data);
1379                         }
1380                         FOREACH_MOD_I(this->Instance,I_OnSyncUser,OnSyncUser(u->second,(Module*)Utils->Creator,(void*)this));
1381                         list.clear();
1382                         u->second->GetExtList(list);
1383
1384                         for (unsigned int j = 0; j < list.size(); j++)
1385                         {
1386                                 FOREACH_MOD_I(this->Instance,I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)Utils->Creator,(void*)this,list[j]));
1387                         }
1388                 }
1389         }
1390 }
1391
1392 /** This function is called when we want to send a netburst to a local
1393  * server. There is a set order we must do this, because for example
1394  * users require their servers to exist, and channels require their
1395  * users to exist. You get the idea.
1396  */
1397 void TreeSocket::DoBurst(TreeServer* s)
1398 {
1399         std::string burst = "BURST "+ConvToStr(Instance->Time(true));
1400         std::string endburst = "ENDBURST";
1401         // Because by the end of the netburst, it  could be gone!
1402         std::string name = s->GetName();
1403         this->Instance->SNO->WriteToSnoMask('l',"Bursting to \2"+name+"\2.");
1404         this->WriteLine(burst);
1405         /* send our version string */
1406         this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" VERSION :"+this->Instance->GetVersionString());
1407         /* Send server tree */
1408         this->SendServers(Utils->TreeRoot,s,1);
1409         /* Send users and their oper status */
1410         this->SendUsers(s);
1411         /* Send everything else (channel modes, xlines etc) */
1412         this->SendChannelModes(s);
1413         this->SendXLines(s);
1414         FOREACH_MOD_I(this->Instance,I_OnSyncOtherMetaData,OnSyncOtherMetaData((Module*)Utils->Creator,(void*)this));
1415         this->WriteLine(endburst);
1416         this->Instance->SNO->WriteToSnoMask('l',"Finished bursting to \2"+name+"\2.");
1417 }
1418
1419 /** This function is called when we receive data from a remote
1420  * server. We buffer the data in a std::string (it doesnt stay
1421  * there for long), reading using InspSocket::Read() which can
1422  * read up to 16 kilobytes in one operation.
1423  *
1424  * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
1425  * THE SOCKET OBJECT FOR US.
1426  */
1427 bool TreeSocket::OnDataReady()
1428 {
1429         char* data = this->Read();
1430         /* Check that the data read is a valid pointer and it has some content */
1431         if (data && *data)
1432         {
1433                 this->in_buffer.append(data);
1434                 /* While there is at least one new line in the buffer,
1435                  * do something useful (we hope!) with it.
1436                  */
1437                 while (in_buffer.find("\n") != std::string::npos)
1438                 {
1439                         std::string ret = in_buffer.substr(0,in_buffer.find("\n")-1);
1440                         in_buffer = in_buffer.substr(in_buffer.find("\n")+1,in_buffer.length()-in_buffer.find("\n"));
1441                         /* Use rfind here not find, as theres more
1442                          * chance of the \r being near the end of the
1443                          * string, not the start.
1444                          */
1445                         if (ret.find("\r") != std::string::npos)
1446                                 ret = in_buffer.substr(0,in_buffer.find("\r")-1);
1447                         /* Process this one, abort if it
1448                          * didnt return true.
1449                          */
1450                         if (!this->ProcessLine(ret))
1451                         {
1452                                 return false;
1453                         }
1454                 }
1455                 return true;
1456         }
1457         /* EAGAIN returns an empty but non-NULL string, so this
1458          * evaluates to TRUE for EAGAIN but to FALSE for EOF.
1459          */
1460         return (data && !*data);
1461 }
1462