]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree.cpp
The IPV6 stuff compiles now, with compile-correct ipv6 code. I dont know if this...
[user/henk/code/inspircd.git] / src / modules / m_spanningtree.cpp
1 /*   +------------------------------------+
2  *   | Inspire Internet Relay Chat Daemon |
3  *   +------------------------------------+
4  *
5  *  InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
6  *                     E-mail:
7  *                <brain@chatspike.net>
8  *                <Craig@chatspike.net>
9  *     
10  * Written by Craig Edwards, Craig McLure, and others.
11  * This program is free but copyrighted software; see
12  *            the file COPYING for details.
13  *
14  * ---------------------------------------------------
15  */
16
17 /* $ModDesc: Povides a spanning tree server link protocol */
18
19 using namespace std;
20
21 #include <stdio.h>
22 #include <vector>
23 #include <deque>
24 #include "globals.h"
25 #include "inspircd_config.h"
26 #include "hash_map.h"
27 #include "configreader.h"
28 #include "users.h"
29 #include "channels.h"
30 #include "modules.h"
31 #include "commands.h"
32 #include "commands/cmd_whois.h"
33 #include "commands/cmd_stats.h"
34 #include "socket.h"
35 #include "helperfuncs.h"
36 #include "inspircd.h"
37 #include "inspstring.h"
38 #include "hashcomp.h"
39 #include "message.h"
40 #include "xline.h"
41 #include "typedefs.h"
42 #include "cull_list.h"
43 #include "aes.h"
44
45 #define nspace __gnu_cxx
46
47 /*
48  * The server list in InspIRCd is maintained as two structures
49  * which hold the data in different ways. Most of the time, we
50  * want to very quicky obtain three pieces of information:
51  *
52  * (1) The information on a server
53  * (2) The information on the server we must send data through
54  *     to actually REACH the server we're after
55  * (3) Potentially, the child/parent objects of this server
56  *
57  * The InspIRCd spanning protocol provides easy access to these
58  * by storing the data firstly in a recursive structure, where
59  * each item references its parent item, and a dynamic list
60  * of child items, and another structure which stores the items
61  * hashed, linearly. This means that if we want to find a server
62  * by name quickly, we can look it up in the hash, avoiding
63  * any O(n) lookups. If however, during a split or sync, we want
64  * to apply an operation to a server, and any of its child objects
65  * we can resort to recursion to walk the tree structure.
66  */
67
68 class ModuleSpanningTree;
69 static ModuleSpanningTree* TreeProtocolModule;
70
71 extern ServerConfig* Config;
72 extern InspIRCd* ServerInstance;
73 extern std::vector<Module*> modules;
74 extern std::vector<ircd_module*> factory;
75 extern int MODCOUNT;
76
77 /* Any socket can have one of five states at any one time.
78  * The LISTENER state indicates a socket which is listening
79  * for connections. It cannot receive data itself, only incoming
80  * sockets.
81  * The CONNECTING state indicates an outbound socket which is
82  * waiting to be writeable.
83  * The WAIT_AUTH_1 state indicates the socket is outbound and
84  * has successfully connected, but has not yet sent and received
85  * SERVER strings.
86  * The WAIT_AUTH_2 state indicates that the socket is inbound
87  * (allocated by a LISTENER) but has not yet sent and received
88  * SERVER strings.
89  * The CONNECTED state represents a fully authorized, fully
90  * connected server.
91  */
92 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
93
94 /* We need to import these from the core for use in netbursts */
95 extern user_hash clientlist;
96 extern chan_hash chanlist;
97
98 /* Foward declarations */
99 class TreeServer;
100 class TreeSocket;
101
102 /* This variable represents the root of the server tree
103  * (for all intents and purposes, it's us)
104  */
105 TreeServer *TreeRoot;
106
107 static Server* Srv;
108
109 /* This hash_map holds the hash equivalent of the server
110  * tree, used for rapid linear lookups.
111  */
112 typedef nspace::hash_map<std::string, TreeServer*, nspace::hash<string>, irc::StrHashComp> server_hash;
113 server_hash serverlist;
114
115 typedef nspace::hash_map<std::string, userrec*> uid_hash;
116 typedef nspace::hash_map<std::string, char*> sid_hash;
117
118 /* More forward declarations */
119 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> &params, std::string target);
120 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> &params, std::string omit);
121 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> &params);
122 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, irc::string command, std::deque<std::string> &params);
123 void ReadConfiguration(bool rebind);
124
125 /* Flatten links and /MAP for non-opers */
126 bool FlatLinks;
127 /* Hide U-Lined servers in /MAP and /LINKS */
128 bool HideULines;
129
130 /* Imported from xline.cpp for use during netburst */
131 extern std::vector<KLine> klines;
132 extern std::vector<GLine> glines;
133 extern std::vector<ZLine> zlines;
134 extern std::vector<QLine> qlines;
135 extern std::vector<ELine> elines;
136 extern std::vector<KLine> pklines;
137 extern std::vector<GLine> pglines;
138 extern std::vector<ZLine> pzlines;
139 extern std::vector<QLine> pqlines;
140 extern std::vector<ELine> pelines;
141
142 class UserManager : public classbase
143 {
144         uid_hash uids;
145         sid_hash sids;
146  public:
147         UserManager()
148         {
149                 uids.clear();
150                 sids.clear();
151         }
152
153         std::string UserToUID(userrec* user)
154         {
155                 return "";
156         }
157
158         std::string UIDToUser(const std::string &UID)
159         {
160                 return "";
161         }
162
163         std::string CreateAndAdd(userrec* user)
164         {
165                 return "";
166         }
167
168         std::string CreateAndAdd(const std::string &servername)
169         {
170                 return "";
171         }
172
173         std::string ServerToSID(const std::string &servername)
174         {
175                 return "";
176         }
177
178         std::string SIDToServer(const std::string &SID)
179         {
180                 return "";
181         }
182
183         userrec* FindByID(const std::string &UID)
184         {
185                 return NULL;
186         }
187 };
188
189 /* Each server in the tree is represented by one class of
190  * type TreeServer. A locally connected TreeServer can
191  * have a class of type TreeSocket associated with it, for
192  * remote servers, the TreeSocket entry will be NULL.
193  * Each server also maintains a pointer to its parent
194  * (NULL if this server is ours, at the top of the tree)
195  * and a pointer to its "Route" (see the comments in the
196  * constructors below), and also a dynamic list of pointers
197  * to its children which can be iterated recursively
198  * if required. Creating or deleting objects of type
199  i* TreeServer automatically maintains the hash_map of
200  * TreeServer items, deleting and inserting them as they
201  * are created and destroyed.
202  */
203
204 class TreeServer : public classbase
205 {
206         TreeServer* Parent;                     /* Parent entry */
207         TreeServer* Route;                      /* Route entry */
208         std::vector<TreeServer*> Children;      /* List of child objects */
209         irc::string ServerName;                 /* Server's name */
210         std::string ServerDesc;                 /* Server's description */
211         std::string VersionString;              /* Version string or empty string */
212         int UserCount;                          /* Not used in this version */
213         int OperCount;                          /* Not used in this version */
214         TreeSocket* Socket;                     /* For directly connected servers this points at the socket object */
215         time_t NextPing;                        /* After this time, the server should be PINGed*/
216         bool LastPingWasGood;                   /* True if the server responded to the last PING with a PONG */
217         
218  public:
219
220         /* We don't use this constructor. Its a dummy, and won't cause any insertion
221          * of the TreeServer into the hash_map. See below for the two we DO use.
222          */
223         TreeServer()
224         {
225                 Parent = NULL;
226                 ServerName = "";
227                 ServerDesc = "";
228                 VersionString = "";
229                 UserCount = OperCount = 0;
230                 VersionString = Srv->GetVersion();
231         }
232
233         /* We use this constructor only to create the 'root' item, TreeRoot, which
234          * represents our own server. Therefore, it has no route, no parent, and
235          * no socket associated with it. Its version string is our own local version.
236          */
237         TreeServer(std::string Name, std::string Desc) : ServerName(Name.c_str()), ServerDesc(Desc)
238         {
239                 Parent = NULL;
240                 VersionString = "";
241                 UserCount = OperCount = 0;
242                 VersionString = Srv->GetVersion();
243                 Route = NULL;
244                 Socket = NULL; /* Fix by brain */
245                 AddHashEntry();
246         }
247
248         /* When we create a new server, we call this constructor to initialize it.
249          * This constructor initializes the server's Route and Parent, and sets up
250          * its ping counters so that it will be pinged one minute from now.
251          */
252         TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name.c_str()), ServerDesc(Desc), Socket(Sock)
253         {
254                 VersionString = "";
255                 UserCount = OperCount = 0;
256                 this->SetNextPingTime(time(NULL) + 120);
257                 this->SetPingFlag();
258
259                 /* find the 'route' for this server (e.g. the one directly connected
260                  * to the local server, which we can use to reach it)
261                  *
262                  * In the following example, consider we have just added a TreeServer
263                  * class for server G on our network, of which we are server A.
264                  * To route traffic to G (marked with a *) we must send the data to
265                  * B (marked with a +) so this algorithm initializes the 'Route'
266                  * value to point at whichever server traffic must be routed through
267                  * to get here. If we were to try this algorithm with server B,
268                  * the Route pointer would point at its own object ('this').
269                  *
270                  *              A
271                  *             / \
272                  *          + B   C
273                  *           / \   \
274                  *          D   E   F
275                  *         /         \
276                  *      * G           H
277                  *
278                  * We only run this algorithm when a server is created, as
279                  * the routes remain constant while ever the server exists, and
280                  * do not need to be re-calculated.
281                  */
282
283                 Route = Above;
284                 if (Route == TreeRoot)
285                 {
286                         Route = this;
287                 }
288                 else
289                 {
290                         while (this->Route->GetParent() != TreeRoot)
291                         {
292                                 this->Route = Route->GetParent();
293                         }
294                 }
295
296                 /* Because recursive code is slow and takes a lot of resources,
297                  * we store two representations of the server tree. The first
298                  * is a recursive structure where each server references its
299                  * children and its parent, which is used for netbursts and
300                  * netsplits to dump the whole dataset to the other server,
301                  * and the second is used for very fast lookups when routing
302                  * messages and is instead a hash_map, where each item can
303                  * be referenced by its server name. The AddHashEntry()
304                  * call below automatically inserts each TreeServer class
305                  * into the hash_map as it is created. There is a similar
306                  * maintainance call in the destructor to tidy up deleted
307                  * servers.
308                  */
309
310                 this->AddHashEntry();
311         }
312
313         int QuitUsers(const std::string &reason)
314         {
315                 log(DEBUG,"Removing all users from server %s",this->ServerName.c_str());
316                 const char* reason_s = reason.c_str();
317                 std::vector<userrec*> time_to_die;
318                 for (user_hash::iterator n = clientlist.begin(); n != clientlist.end(); n++)
319                 {
320                         if (!strcmp(n->second->server, this->ServerName.c_str()))
321                         {
322                                 time_to_die.push_back(n->second);
323                         }
324                 }
325                 for (std::vector<userrec*>::iterator n = time_to_die.begin(); n != time_to_die.end(); n++)
326                 {
327                         userrec* a = (userrec*)*n;
328                         log(DEBUG,"Kill %s fd=%d",a->nick,a->fd);
329                         if (!IS_LOCAL(a))
330                                 kill_link(a,reason_s);
331                 }
332                 return time_to_die.size();
333         }
334
335         /* This method is used to add the structure to the
336          * hash_map for linear searches. It is only called
337          * by the constructors.
338          */
339         void AddHashEntry()
340         {
341                 server_hash::iterator iter;
342                 iter = serverlist.find(this->ServerName.c_str());
343                 if (iter == serverlist.end())
344                         serverlist[this->ServerName.c_str()] = this;
345         }
346
347         /* This method removes the reference to this object
348          * from the hash_map which is used for linear searches.
349          * It is only called by the default destructor.
350          */
351         void DelHashEntry()
352         {
353                 server_hash::iterator iter;
354                 iter = serverlist.find(this->ServerName.c_str());
355                 if (iter != serverlist.end())
356                         serverlist.erase(iter);
357         }
358
359         /* These accessors etc should be pretty self-
360          * explanitory.
361          */
362
363         TreeServer* GetRoute()
364         {
365                 return Route;
366         }
367
368         std::string GetName()
369         {
370                 return ServerName.c_str();
371         }
372
373         std::string GetDesc()
374         {
375                 return ServerDesc;
376         }
377
378         std::string GetVersion()
379         {
380                 return VersionString;
381         }
382
383         void SetNextPingTime(time_t t)
384         {
385                 this->NextPing = t;
386                 LastPingWasGood = false;
387         }
388
389         time_t NextPingTime()
390         {
391                 return NextPing;
392         }
393
394         bool AnsweredLastPing()
395         {
396                 return LastPingWasGood;
397         }
398
399         void SetPingFlag()
400         {
401                 LastPingWasGood = true;
402         }
403
404         int GetUserCount()
405         {
406                 return UserCount;
407         }
408
409         void AddUserCount()
410         {
411                 UserCount++;
412         }
413
414         void DelUserCount()
415         {
416                 UserCount--;
417         }
418
419         int GetOperCount()
420         {
421                 return OperCount;
422         }
423
424         TreeSocket* GetSocket()
425         {
426                 return Socket;
427         }
428
429         TreeServer* GetParent()
430         {
431                 return Parent;
432         }
433
434         void SetVersion(std::string Version)
435         {
436                 VersionString = Version;
437         }
438
439         unsigned int ChildCount()
440         {
441                 return Children.size();
442         }
443
444         TreeServer* GetChild(unsigned int n)
445         {
446                 if (n < Children.size())
447                 {
448                         /* Make sure they  cant request
449                          * an out-of-range object. After
450                          * all we know what these programmer
451                          * types are like *grin*.
452                          */
453                         return Children[n];
454                 }
455                 else
456                 {
457                         return NULL;
458                 }
459         }
460
461         void AddChild(TreeServer* Child)
462         {
463                 Children.push_back(Child);
464         }
465
466         bool DelChild(TreeServer* Child)
467         {
468                 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
469                 {
470                         if (*a == Child)
471                         {
472                                 Children.erase(a);
473                                 return true;
474                         }
475                 }
476                 return false;
477         }
478
479         /* Removes child nodes of this node, and of that node, etc etc.
480          * This is used during netsplits to automatically tidy up the
481          * server tree. It is slow, we don't use it for much else.
482          */
483         bool Tidy()
484         {
485                 bool stillchildren = true;
486                 while (stillchildren)
487                 {
488                         stillchildren = false;
489                         for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
490                         {
491                                 TreeServer* s = (TreeServer*)*a;
492                                 s->Tidy();
493                                 Children.erase(a);
494                                 DELETE(s);
495                                 stillchildren = true;
496                                 break;
497                         }
498                 }
499                 return true;
500         }
501
502         ~TreeServer()
503         {
504                 /* We'd better tidy up after ourselves, eh? */
505                 this->DelHashEntry();
506         }
507 };
508
509 /* The Link class might as well be a struct,
510  * but this is C++ and we don't believe in structs (!).
511  * It holds the entire information of one <link>
512  * tag from the main config file. We maintain a list
513  * of them, and populate the list on rehash/load.
514  */
515
516 class Link : public classbase
517 {
518  public:
519          irc::string Name;
520          std::string IPAddr;
521          int Port;
522          std::string SendPass;
523          std::string RecvPass;
524          unsigned long AutoConnect;
525          time_t NextConnectTime;
526          std::string EncryptionKey;
527          bool HiddenFromStats;
528 };
529
530 /* The usual stuff for inspircd modules,
531  * plus the vector of Link classes which we
532  * use to store the <link> tags from the config
533  * file.
534  */
535 ConfigReader *Conf;
536 std::vector<Link> LinkBlocks;
537
538 /* Yay for fast searches!
539  * This is hundreds of times faster than recursion
540  * or even scanning a linked list, especially when
541  * there are more than a few servers to deal with.
542  * (read as: lots).
543  */
544 TreeServer* FindServer(std::string ServerName)
545 {
546         server_hash::iterator iter;
547         iter = serverlist.find(ServerName.c_str());
548         if (iter != serverlist.end())
549         {
550                 return iter->second;
551         }
552         else
553         {
554                 return NULL;
555         }
556 }
557
558 /* Returns the locally connected server we must route a
559  * message through to reach server 'ServerName'. This
560  * only applies to one-to-one and not one-to-many routing.
561  * See the comments for the constructor of TreeServer
562  * for more details.
563  */
564 TreeServer* BestRouteTo(std::string ServerName)
565 {
566         if (ServerName.c_str() == TreeRoot->GetName())
567                 return NULL;
568         TreeServer* Found = FindServer(ServerName);
569         if (Found)
570         {
571                 return Found->GetRoute();
572         }
573         else
574         {
575                 return NULL;
576         }
577 }
578
579 /* Find the first server matching a given glob mask.
580  * Theres no find-using-glob method of hash_map [awwww :-(]
581  * so instead, we iterate over the list using an iterator
582  * and match each one until we get a hit. Yes its slow,
583  * deal with it.
584  */
585 TreeServer* FindServerMask(std::string ServerName)
586 {
587         for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
588         {
589                 if (Srv->MatchText(i->first.c_str(),ServerName))
590                         return i->second;
591         }
592         return NULL;
593 }
594
595 /* A convenient wrapper that returns true if a server exists */
596 bool IsServer(std::string ServerName)
597 {
598         return (FindServer(ServerName) != NULL);
599 }
600
601
602 class cmd_rconnect : public command_t
603 {
604         Module* Creator;
605  public:
606         cmd_rconnect (Module* Callback) : command_t("RCONNECT", 'o', 2), Creator(Callback)
607         {
608                 this->source = "m_spanningtree.so";
609                 syntax = "<remote-server-mask> <servermask>";
610         }
611
612         void Handle (const char** parameters, int pcnt, userrec *user)
613         {
614                 WriteServ(user->fd,"NOTICE %s :*** RCONNECT: Sending remote connect to \002%s\002 to connect server \002%s\002.",user->nick,parameters[0],parameters[1]);
615                 /* Is this aimed at our server? */
616                 if (Srv->MatchText(Srv->GetServerName(),parameters[0]))
617                 {
618                         /* Yes, initiate the given connect */
619                         WriteOpers("*** Remote CONNECT from %s matching \002%s\002, connecting server \002%s\002",user->nick,parameters[0],parameters[1]);
620                         const char* para[1];
621                         para[0] = parameters[1];
622                         Creator->OnPreCommand("CONNECT", para, 1, user, true);
623                 }
624         }
625 };
626  
627
628
629 /* Every SERVER connection inbound or outbound is represented by
630  * an object of type TreeSocket.
631  * TreeSockets, being inherited from InspSocket, can be tied into
632  * the core socket engine, and we cn therefore receive activity events
633  * for them, just like activex objects on speed. (yes really, that
634  * is a technical term!) Each of these which relates to a locally
635  * connected server is assocated with it, by hooking it onto a
636  * TreeSocket class using its constructor. In this way, we can
637  * maintain a list of servers, some of which are directly connected,
638  * some of which are not.
639  */
640
641 class TreeSocket : public InspSocket
642 {
643         std::string myhost;
644         std::string in_buffer;
645         ServerState LinkState;
646         std::string InboundServerName;
647         std::string InboundDescription;
648         int num_lost_users;
649         int num_lost_servers;
650         time_t NextPing;
651         bool LastPingWasGood;
652         bool bursting;
653         AES* ctx_in;
654         AES* ctx_out;
655         unsigned int keylength;
656         
657  public:
658
659         /* Because most of the I/O gubbins are encapsulated within
660          * InspSocket, we just call the superclass constructor for
661          * most of the action, and append a few of our own values
662          * to it.
663          */
664         TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
665                 : InspSocket(host, port, listening, maxtime)
666         {
667                 myhost = host;
668                 this->LinkState = LISTENER;
669                 this->ctx_in = NULL;
670                 this->ctx_out = NULL;
671         }
672
673         TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
674                 : InspSocket(host, port, listening, maxtime)
675         {
676                 myhost = ServerName;
677                 this->LinkState = CONNECTING;
678                 this->ctx_in = NULL;
679                 this->ctx_out = NULL;
680         }
681
682         /* When a listening socket gives us a new file descriptor,
683          * we must associate it with a socket without creating a new
684          * connection. This constructor is used for this purpose.
685          */
686         TreeSocket(int newfd, char* ip)
687                 : InspSocket(newfd, ip)
688         {
689                 this->LinkState = WAIT_AUTH_1;
690                 this->ctx_in = NULL;
691                 this->ctx_out = NULL;
692                 this->SendCapabilities();
693         }
694
695         ~TreeSocket()
696         {
697                 if (ctx_in)
698                         DELETE(ctx_in);
699                 if (ctx_out)
700                         DELETE(ctx_out);
701         }
702
703         void InitAES(std::string key,std::string SName)
704         {
705                 if (key == "")
706                         return;
707
708                 ctx_in = new AES();
709                 ctx_out = new AES();
710                 log(DEBUG,"Initialized AES key %s",key.c_str());
711                 // key must be 16, 24, 32 etc bytes (multiple of 8)
712                 keylength = key.length();
713                 if (!(keylength == 16 || keylength == 24 || keylength == 32))
714                 {
715                         WriteOpers("*** \2ERROR\2: Key length for encryptionkey is not 16, 24 or 32 bytes in length!");
716                         log(DEBUG,"Key length not 16, 24 or 32 characters!");
717                 }
718                 else
719                 {
720                         WriteOpers("*** \2AES\2: Initialized %d bit encryption to server %s",keylength*8,SName.c_str());
721                         ctx_in->MakeKey(key.c_str(), "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\
722                                 \0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", keylength, keylength);
723                         ctx_out->MakeKey(key.c_str(), "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\
724                                 \0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", keylength, keylength);
725                 }
726         }
727         
728         /* When an outbound connection finishes connecting, we receive
729          * this event, and must send our SERVER string to the other
730          * side. If the other side is happy, as outlined in the server
731          * to server docs on the inspircd.org site, the other side
732          * will then send back its own server string.
733          */
734         virtual bool OnConnected()
735         {
736                 if (this->LinkState == CONNECTING)
737                 {
738                         /* we do not need to change state here. */
739                         for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
740                         {
741                                 if (x->Name == this->myhost)
742                                 {
743                                         Srv->SendOpers("*** Connection to \2"+myhost+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] established.");
744                                         this->SendCapabilities();
745                                         if (x->EncryptionKey != "")
746                                         {
747                                                 if (!(x->EncryptionKey.length() == 16 || x->EncryptionKey.length() == 24 || x->EncryptionKey.length() == 32))
748                                                 {
749                                                         WriteOpers("\2WARNING\2: Your encryption key is NOT 16, 24 or 32 characters in length, encryption will \2NOT\2 be enabled.");
750                                                 }
751                                                 else
752                                                 {
753                                                         this->WriteLine("AES "+Srv->GetServerName());
754                                                         this->InitAES(x->EncryptionKey,x->Name.c_str());
755                                                 }
756                                         }
757                                         /* found who we're supposed to be connecting to, send the neccessary gubbins. */
758                                         this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
759                                         return true;
760                                 }
761                         }
762                 }
763                 /* There is a (remote) chance that between the /CONNECT and the connection
764                  * being accepted, some muppet has removed the <link> block and rehashed.
765                  * If that happens the connection hangs here until it's closed. Unlikely
766                  * and rather harmless.
767                  */
768                 Srv->SendOpers("*** Connection to \2"+myhost+"\2 lost link tag(!)");
769                 return true;
770         }
771         
772         virtual void OnError(InspSocketError e)
773         {
774                 /* We don't handle this method, because all our
775                  * dirty work is done in OnClose() (see below)
776                  * which is still called on error conditions too.
777                  */
778                 if (e == I_ERR_CONNECT)
779                 {
780                         Srv->SendOpers("*** Connection failed: Connection refused");
781                 }
782         }
783
784         virtual int OnDisconnect()
785         {
786                 /* For the same reason as above, we don't
787                  * handle OnDisconnect()
788                  */
789                 return true;
790         }
791
792         /* Recursively send the server tree with distances as hops.
793          * This is used during network burst to inform the other server
794          * (and any of ITS servers too) of what servers we know about.
795          * If at any point any of these servers already exist on the other
796          * end, our connection may be terminated. The hopcounts given
797          * by this function are relative, this doesn't matter so long as
798          * they are all >1, as all the remote servers re-calculate them
799          * to be relative too, with themselves as hop 0.
800          */
801         void SendServers(TreeServer* Current, TreeServer* s, int hops)
802         {
803                 char command[1024];
804                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
805                 {
806                         TreeServer* recursive_server = Current->GetChild(q);
807                         if (recursive_server != s)
808                         {
809                                 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
810                                 this->WriteLine(command);
811                                 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
812                                 /* down to next level */
813                                 this->SendServers(recursive_server, s, hops+1);
814                         }
815                 }
816         }
817
818         std::string MyCapabilities()
819         {
820                 ServerConfig* Config = Srv->GetConfig();
821                 std::vector<std::string> modlist;
822                 std::string capabilities = "";
823
824                 for (int i = 0; i <= MODCOUNT; i++)
825                 {
826                         if ((modules[i]->GetVersion().Flags & VF_STATIC) || (modules[i]->GetVersion().Flags & VF_COMMON))
827                                 modlist.push_back(Config->module_names[i]);
828                 }
829                 sort(modlist.begin(),modlist.end());
830                 for (unsigned int i = 0; i < modlist.size(); i++)
831                 {
832                         if (i)
833                                 capabilities = capabilities + ",";
834                         capabilities = capabilities + modlist[i];
835                 }
836                 return capabilities;
837         }
838         
839         void SendCapabilities()
840         {
841                 this->WriteLine("CAPAB "+MyCapabilities());
842         }
843
844         bool Capab(std::deque<std::string> params)
845         {
846                 if (params.size() != 1)
847                 {
848                         this->WriteLine("ERROR :Invalid number of parameters for CAPAB");
849                         return false;
850                 }
851
852                 if (params[0] != this->MyCapabilities())
853                 {
854                         std::string quitserver = this->myhost;
855                         if (this->InboundServerName != "")
856                         {
857                                 quitserver = this->InboundServerName;
858                         }
859
860                         WriteOpers("*** \2ERROR\2: Server '%s' does not have the same set of modules loaded, cannot link!",quitserver.c_str());
861                         WriteOpers("*** Our networked module set is: '%s'",this->MyCapabilities().c_str());
862                         WriteOpers("*** Other server's networked module set is: '%s'",params[0].c_str());
863                         WriteOpers("*** These lists must match exactly on both servers. Please correct these errors, and try again.");
864                         this->WriteLine("ERROR :CAPAB mismatch; My capabilities: '"+this->MyCapabilities()+"'");
865                         return false;
866                 }
867
868                 return true;
869         }
870
871         /* This function forces this server to quit, removing this server
872          * and any users on it (and servers and users below that, etc etc).
873          * It's very slow and pretty clunky, but luckily unless your network
874          * is having a REAL bad hair day, this function shouldnt be called
875          * too many times a month ;-)
876          */
877         void SquitServer(std::string &from, TreeServer* Current)
878         {
879                 /* recursively squit the servers attached to 'Current'.
880                  * We're going backwards so we don't remove users
881                  * while we still need them ;)
882                  */
883                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
884                 {
885                         TreeServer* recursive_server = Current->GetChild(q);
886                         this->SquitServer(from,recursive_server);
887                 }
888                 /* Now we've whacked the kids, whack self */
889                 num_lost_servers++;
890                 num_lost_users += Current->QuitUsers(from);
891         }
892
893         /* This is a wrapper function for SquitServer above, which
894          * does some validation first and passes on the SQUIT to all
895          * other remaining servers.
896          */
897         void Squit(TreeServer* Current,std::string reason)
898         {
899                 if ((Current) && (Current != TreeRoot))
900                 {
901                         std::deque<std::string> params;
902                         params.push_back(Current->GetName());
903                         params.push_back(":"+reason);
904                         DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
905                         if (Current->GetParent() == TreeRoot)
906                         {
907                                 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
908                         }
909                         else
910                         {
911                                 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
912                         }
913                         num_lost_servers = 0;
914                         num_lost_users = 0;
915                         std::string from = Current->GetParent()->GetName()+" "+Current->GetName();
916                         SquitServer(from, Current);
917                         Current->Tidy();
918                         Current->GetParent()->DelChild(Current);
919                         DELETE(Current);
920                         WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
921                 }
922                 else
923                 {
924                         log(DEFAULT,"Squit from unknown server");
925                 }
926         }
927
928         /* FMODE command - server mode with timestamp checks */
929         bool ForceMode(std::string source, std::deque<std::string> &params)
930         {
931                 /* Chances are this is a 1.0 FMODE without TS */
932                 if (params.size() < 3)
933                 {
934                         this->WriteLine("ERROR :Version 1.0 FMODE sent to version 1.1 server");
935                         return false;
936                 }
937                 
938                 bool smode = false;
939                 std::string sourceserv;
940
941                 /* Are we dealing with an FMODE from a user, or from a server? */
942                 userrec* who = Srv->FindNick(source);
943                 if (who)
944                 {
945                         /* FMODE from a user, set sourceserv to the users server name */
946                         sourceserv = who->server;
947                 }
948                 else
949                 {
950                         /* FMODE from a server, create a fake user to receive mode feedback */
951                         who = new userrec();
952                         who->fd = FD_MAGIC_NUMBER;
953                         smode = true;           /* Setting this flag tells us we should free the userrec later */
954                         sourceserv = source;    /* Set sourceserv to the actual source string */
955                 }
956                 const char* modelist[64];
957                 time_t TS = 0;
958                 int n = 0;
959                 memset(&modelist,0,sizeof(modelist));
960                 for (unsigned int q = 0; (q < params.size()) && (q < 64); q++)
961                 {
962                         if (q == 1)
963                         {
964                                 /* The timestamp is in this position.
965                                  * We don't want to pass that up to the
966                                  * server->client protocol!
967                                  */
968                                 TS = atoi(params[q].c_str());
969                         }
970                         else
971                         {
972                                 /* Everything else is fine to append to the modelist */
973                                 modelist[n++] = params[q].c_str();
974                         }
975                                 
976                 }
977                 /* Extract the TS value of the object, either userrec or chanrec */
978                 userrec* dst = Srv->FindNick(params[0]);
979                 chanrec* chan = NULL;
980                 time_t ourTS = 0;
981                 if (dst)
982                 {
983                         ourTS = dst->age;
984                 }
985                 else
986                 {
987                         chan = Srv->FindChannel(params[0]);
988                         if (chan)
989                         {
990                                 ourTS = chan->age;
991                         }
992                 }
993
994                 /* TS is equal: Merge the mode changes, use voooodoooooo on modes
995                  * with parameters.
996                  */
997                 if (TS == ourTS)
998                 {
999                         log(DEBUG,"Entering TS equality check");
1000                         ModeHandler* mh = NULL;
1001                         unsigned long paramptr = 3;
1002                         std::string to_bounce = "";
1003                         std::string to_keep = "";
1004                         std::vector<std::string> params_to_keep;
1005                         std::string params_to_bounce = "";
1006                         bool adding = true;
1007                         char cur_change = 1;
1008                         char old_change = 0;
1009                         char old_bounce_change = 0;
1010                         /* Merge modes, basically do special stuff to mode with params */
1011                         for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
1012                         {
1013                                 switch (*x)
1014                                 {
1015                                         case '-':
1016                                                 adding = false;
1017                                         break;
1018                                         case '+':
1019                                                 adding = true;
1020                                         break;
1021                                         default:
1022                                                 if (adding)
1023                                                 {
1024                                                         /* We only care about whats being set,
1025                                                          * not whats being unset
1026                                                          */
1027                                                         mh = ServerInstance->ModeGrok->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1028
1029                                                         if ((mh->GetNumParams(adding) > 0) && (!mh->IsListMode()))
1030                                                         {
1031                                                                 /* We only want to do special things to
1032                                                                  * modes with parameters, we are going to rewrite
1033                                                                  * those parameters
1034                                                                  */
1035                                                                 ModePair ret;
1036                                                                 adding ? cur_change = '+' : cur_change = '-';
1037
1038                                                                 ret = mh->ModeSet(smode ? NULL : who, dst, chan, params[paramptr]);
1039
1040                                                                 /* The mode is set here, check which we should keep */
1041                                                                 if (ret.first)
1042                                                                 {
1043                                                                         bool which_to_keep = mh->CheckTimeStamp(TS, ourTS, params[paramptr], ret.second, chan);
1044
1045                                                                         if (which_to_keep == true)
1046                                                                         {
1047                                                                                 /* Keep ours, bounce theirs:
1048                                                                                  * Send back ours to them and
1049                                                                                  * drop their mode changs
1050                                                                                  */
1051                                                                                 adding ? cur_change = '+' : cur_change = '-';
1052                                                                                 if (cur_change != old_bounce_change)
1053                                                                                         to_bounce += cur_change;
1054                                                                                 to_bounce += *x;
1055                                                                                 old_bounce_change = cur_change;
1056
1057                                                                                 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1058                                                                                         params_to_bounce.append(" ").append(ret.second);
1059                                                                         }
1060                                                                         else
1061                                                                         {
1062                                                                                 /* Keep theirs: Accept their mode change,
1063                                                                                  * do nothing else
1064                                                                                  */
1065                                                                                 adding ? cur_change = '+' : cur_change = '-';
1066                                                                                 if (cur_change != old_change)
1067                                                                                         to_keep += cur_change;
1068                                                                                 to_keep += *x;
1069                                                                                 old_change = cur_change;
1070
1071                                                                                 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1072                                                                                         params_to_keep.push_back(params[paramptr]);
1073                                                                         }
1074                                                                 }
1075                                                                 else
1076                                                                 {
1077                                                                         /* Mode isnt set here, we want it */
1078                                                                         adding ? cur_change = '+' : cur_change = '-';
1079                                                                         if (cur_change != old_change)
1080                                                                                 to_keep += cur_change;
1081                                                                         to_keep += *x;
1082                                                                         old_change = cur_change;
1083
1084                                                                         if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1085                                                                                 params_to_keep.push_back(params[paramptr]);
1086                                                                 }
1087
1088                                                                 paramptr++;
1089                                                         }
1090                                                         else
1091                                                         {
1092                                                                 mh = ServerInstance->ModeGrok->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1093
1094                                                                 if (mh)
1095                                                                 {
1096                                                                         adding ? cur_change = '+' : cur_change = '-';
1097         
1098                                                                         /* Just keep this, safe to merge with no checks
1099                                                                          * it has no parameters
1100                                                                          */
1101         
1102                                                                         if (cur_change != old_change)
1103                                                                                 to_keep += cur_change;
1104                                                                         to_keep += *x;
1105                                                                         old_change = cur_change;
1106         
1107                                                                         if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1108                                                                         {
1109                                                                                 log(DEBUG,"Mode removal %d %d",adding, mh->GetNumParams(adding));
1110                                                                                 params_to_keep.push_back(params[paramptr++]);
1111                                                                         }
1112                                                                 }
1113                                                         }
1114                                                 }
1115                                                 else
1116                                                 {
1117                                                         mh = ServerInstance->ModeGrok->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1118
1119                                                         if (mh)
1120                                                         {
1121                                                                 /* Taking a mode away */
1122                                                                 adding ? cur_change = '+' : cur_change = '-';
1123
1124                                                                 if (cur_change != old_change)
1125                                                                         to_keep += cur_change;
1126                                                                 to_keep += *x;
1127                                                                 old_change = cur_change;
1128
1129                                                                 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1130                                                                         params_to_keep.push_back(params[paramptr++]);
1131                                                         }
1132                                                 }
1133                                         break;
1134                                 }
1135                         }
1136
1137                         if (to_bounce.length())
1138                         {
1139                                 std::deque<std::string> newparams;
1140                                 newparams.push_back(params[0]);
1141                                 newparams.push_back(ConvToStr(ourTS));
1142                                 newparams.push_back(to_bounce+params_to_bounce);
1143                                 DoOneToOne(Srv->GetServerName(),"FMODE",newparams,sourceserv);
1144                         }
1145
1146                         if (to_keep.length())
1147                         {
1148                                 n = 0;
1149                                 modelist[0] = params[0].c_str();
1150                                 modelist[1] = to_keep.c_str();
1151
1152                                 for (unsigned int q = 2; (q < params.size()) && (q < 64); q++)
1153                                                 modelist[q] = params_to_keep[n++].c_str();
1154
1155                                 if (smode)
1156                                 {
1157                                         Srv->SendMode(modelist, n+2, who);
1158                                 }
1159                                 else
1160                                 {
1161                                         Srv->CallCommandHandler("MODE", modelist, n+2, who);
1162                                 }
1163
1164                                 /* HOT POTATO! PASS IT ON! */
1165                                 DoOneToAllButSender(source,"FMODE",params,sourceserv);
1166                         }
1167                 }
1168                 else
1169                 /* U-lined servers always win regardless of their TS */
1170                 if ((TS > ourTS) && (!Srv->IsUlined(source)))
1171                 {
1172                         /* Bounce the mode back to its sender.* We use our lower TS, so the other end
1173                          * SHOULD accept it, if its clock is right.
1174                          *
1175                          * NOTE: We should check that we arent bouncing anything thats already set at this end.
1176                          * If we are, bounce +ourmode to 'reinforce' it. This prevents desyncs.
1177                          * e.g. They send +l 50, we have +l 10 set. rather than bounce -l 50, we bounce +l 10.
1178                          *
1179                          * Thanks to jilles for pointing out this one-hell-of-an-issue before i even finished
1180                          * writing the code. It took me a while to come up with this solution.
1181                          *
1182                          * XXX: BE SURE YOU UNDERSTAND THIS CODE FULLY BEFORE YOU MESS WITH IT.
1183                          */
1184
1185                         std::deque<std::string> newparams;      /* New parameter list we send back */
1186                         newparams.push_back(params[0]);         /* Target, user or channel */
1187                         newparams.push_back(ConvToStr(ourTS));  /* Timestamp value of the target */
1188                         newparams.push_back("");                /* This contains the mode string. For now
1189                                                                  * it's empty, we fill it below.
1190                                                                  */
1191
1192                         /* Intelligent mode bouncing. Don't just invert, reinforce any modes which are already
1193                          * set to avoid a desync here.
1194                          */
1195                         std::string modebounce = "";
1196                         bool adding = true;
1197                         unsigned int t = 3;
1198                         ModeHandler* mh = NULL;
1199                         char cur_change = 1;
1200                         char old_change = 0;
1201                         for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
1202                         {
1203                                 /* Iterate over all mode chars in the sent set */
1204                                 switch (*x)
1205                                 {
1206                                         /* Adding or subtracting modes? */
1207                                         case '-':
1208                                                 adding = false;
1209                                         break;
1210                                         case '+':
1211                                                 adding = true;
1212                                         break;
1213                                         default:
1214                                                 /* Find the mode handler for this mode */
1215                                                 mh = ServerInstance->ModeGrok->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1216
1217                                                 /* Got a mode handler?
1218                                                  * This also prevents us bouncing modes we have no handler for.
1219                                                  */
1220                                                 if (mh)
1221                                                 {
1222                                                         ModePair ret;
1223                                                         std::string p = "";
1224
1225                                                         /* Does the mode require a parameter right now?
1226                                                          * If it does, fetch it if we can
1227                                                          */
1228                                                         if ((mh->GetNumParams(adding) > 0) && (t < params.size()))
1229                                                                 p = params[t++];
1230
1231                                                         /* Call the ModeSet method to determine if its set with the
1232                                                          * given parameter here or not.
1233                                                          */
1234                                                         ret = mh->ModeSet(smode ? NULL : who, dst, chan, p);
1235
1236                                                         /* XXX: Really. Dont ask.
1237                                                          * Determine from if its set combined with what the current
1238                                                          * 'state' is (adding or not) as to wether we should 'invert'
1239                                                          * or 'reinforce' the mode change
1240                                                          */
1241                                                         (!ret.first ? (adding ? cur_change = '-' : cur_change = '+') : (!adding ? cur_change = '-' : cur_change = '+'));
1242
1243                                                         /* Quickly determine if we have 'flipped' from + to -,
1244                                                          * or - to +, to prevent unneccessary +/- chars in the
1245                                                          * output string that waste bandwidth
1246                                                          */
1247                                                         if (cur_change != old_change)
1248                                                                 modebounce += cur_change;
1249                                                         old_change = cur_change;
1250
1251                                                         /* Add the mode character to the output string */
1252                                                         modebounce += mh->GetModeChar();
1253
1254                                                         /* We got a parameter back from ModeHandler::ModeSet,
1255                                                          * are we supposed to be sending one out right now?
1256                                                          */
1257                                                         if (ret.second.length())
1258                                                         {
1259                                                                 if (mh->GetNumParams(cur_change == '+') > 0)
1260                                                                         /* Yes we're supposed to be sending out
1261                                                                          * the parameter. Make sure it goes
1262                                                                          */
1263                                                                         newparams.push_back(ret.second);
1264                                                         }
1265
1266                                                 }
1267                                         break;
1268                                 }
1269                         }
1270                         
1271                         /* Update the parameters for FMODE with the new 'bounced' string */
1272                         newparams[2] = modebounce;
1273                         /* Only send it back the way it came, no need to send it anywhere else */
1274                         DoOneToOne(Srv->GetServerName(),"FMODE",newparams,sourceserv);
1275                         log(DEBUG,"FMODE bounced intelligently, our TS less than theirs and the other server is NOT a uline.");
1276                 }
1277                 else
1278                 {
1279                         log(DEBUG,"Allow modes, TS lower for sender");
1280                         /* The server was ulined, but something iffy is up with the TS.
1281                          * Sound the alarm bells!
1282                          */
1283                         if ((Srv->IsUlined(sourceserv)) && (TS > ourTS))
1284                         {
1285                                 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());
1286                         }
1287                         /* Allow the mode, route it to either server or user command handling */
1288                         if (smode)
1289                                 Srv->SendMode(modelist,n,who);
1290                         else
1291                                 Srv->CallCommandHandler("MODE", modelist, n, who);
1292
1293                         /* HOT POTATO! PASS IT ON! */
1294                         DoOneToAllButSender(source,"FMODE",params,sourceserv);
1295                 }
1296                 /* Are we supposed to free the userrec? */
1297                 if (smode)
1298                         DELETE(who);
1299
1300                 return true;
1301         }
1302
1303         /* FTOPIC command */
1304         bool ForceTopic(std::string source, std::deque<std::string> &params)
1305         {
1306                 if (params.size() != 4)
1307                         return true;
1308                 time_t ts = atoi(params[1].c_str());
1309                 std::string nsource = source;
1310
1311                 chanrec* c = Srv->FindChannel(params[0]);
1312                 if (c)
1313                 {
1314                         if ((ts >= c->topicset) || (!*c->topic))
1315                         {
1316                                 std::string oldtopic = c->topic;
1317                                 strlcpy(c->topic,params[3].c_str(),MAXTOPIC);
1318                                 strlcpy(c->setby,params[2].c_str(),NICKMAX-1);
1319                                 c->topicset = ts;
1320                                 /* if the topic text is the same as the current topic,
1321                                  * dont bother to send the TOPIC command out, just silently
1322                                  * update the set time and set nick.
1323                                  */
1324                                 if (oldtopic != params[3])
1325                                 {
1326                                         userrec* user = Srv->FindNick(source);
1327                                         if (!user)
1328                                         {
1329                                                 WriteChannelWithServ(source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
1330                                         }
1331                                         else
1332                                         {
1333                                                 WriteChannel(c, user, "TOPIC %s :%s", c->name, c->topic);
1334                                                 nsource = user->server;
1335                                         }
1336                                         /* all done, send it on its way */
1337                                         params[3] = ":" + params[3];
1338                                         DoOneToAllButSender(source,"FTOPIC",params,nsource);
1339                                 }
1340                         }
1341                         
1342                 }
1343
1344                 return true;
1345         }
1346
1347         /* FJOIN, similar to unreal SJOIN */
1348         bool ForceJoin(std::string source, std::deque<std::string> &params)
1349         {
1350                 if (params.size() < 3)
1351                         return true;
1352
1353                 char first[MAXBUF];
1354                 char modestring[MAXBUF];
1355                 char* mode_users[127];
1356                 memset(&mode_users,0,sizeof(mode_users));
1357                 mode_users[0] = first;
1358                 mode_users[1] = modestring;
1359                 strcpy(first,"+");
1360                 unsigned int modectr = 2;
1361                 
1362                 userrec* who = NULL;
1363                 std::string channel = params[0];
1364                 time_t TS = atoi(params[1].c_str());
1365                 char* key = "";
1366                 
1367                 chanrec* chan = Srv->FindChannel(channel);
1368                 if (chan)
1369                 {
1370                         key = chan->key;
1371                 }
1372                 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
1373
1374                 /* default is a high value, which if we dont have this
1375                  * channel will let the other side apply their modes.
1376                  */
1377                 time_t ourTS = time(NULL)+600;
1378                 chanrec* us = Srv->FindChannel(channel);
1379                 if (us)
1380                 {
1381                         ourTS = us->age;
1382                 }
1383
1384                 log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
1385
1386                 /* do this first, so our mode reversals are correctly received by other servers
1387                  * if there is a TS collision.
1388                  */
1389                 DoOneToAllButSender(source,"FJOIN",params,source);
1390                 
1391                 for (unsigned int usernum = 2; usernum < params.size(); usernum++)
1392                 {
1393                         /* process one channel at a time, applying modes. */
1394                         char* usr = (char*)params[usernum].c_str();
1395                         /* Safety check just to make sure someones not sent us an FJOIN full of spaces
1396                          * (is this even possible?) */
1397                         if (usr && *usr)
1398                         {
1399                                 char permissions = *usr;
1400                                 switch (permissions)
1401                                 {
1402                                         case '@':
1403                                                 usr++;
1404                                                 mode_users[modectr++] = usr;
1405                                                 strlcat(modestring,"o",MAXBUF);
1406                                         break;
1407                                         case '%':
1408                                                 usr++;
1409                                                 mode_users[modectr++] = usr;
1410                                                 strlcat(modestring,"h",MAXBUF);
1411                                         break;
1412                                         case '+':
1413                                                 usr++;
1414                                                 mode_users[modectr++] = usr;
1415                                                 strlcat(modestring,"v",MAXBUF);
1416                                         break;
1417                                 }
1418                                 who = Srv->FindNick(usr);
1419                                 if (who)
1420                                 {
1421                                         Srv->JoinUserToChannel(who,channel,key);
1422                                         if (modectr >= (MAXMODES-1))
1423                                         {
1424                                                 /* theres a mode for this user. push them onto the mode queue, and flush it
1425                                                  * if there are more than MAXMODES to go.
1426                                                  */
1427                                                 if ((ourTS >= TS) || (Srv->IsUlined(who->server)))
1428                                                 {
1429                                                         /* We also always let u-lined clients win, no matter what the TS value */
1430                                                         log(DEBUG,"Our our channel newer than theirs, accepting their modes");
1431                                                         Srv->SendMode((const char**)mode_users,modectr,who);
1432                                                         if (ourTS != TS)
1433                                                         {
1434                                                                 log(DEFAULT,"Channel TS for %s changed from %lu to %lu",us,ourTS,TS);
1435                                                                 us->age = TS;
1436                                                         }
1437                                                 }
1438                                                 else
1439                                                 {
1440                                                         log(DEBUG,"Their channel newer than ours, bouncing their modes");
1441                                                         /* bouncy bouncy! */
1442                                                         std::deque<std::string> params;
1443                                                         /* modes are now being UNSET... */
1444                                                         *mode_users[1] = '-';
1445                                                         for (unsigned int x = 0; x < modectr; x++)
1446                                                         {
1447                                                                 if (x == 1)
1448                                                                 {
1449                                                                         params.push_back(ConvToStr(us->age));
1450                                                                 }
1451                                                                 params.push_back(mode_users[x]);
1452                                                         }
1453                                                         // tell everyone to bounce the modes. bad modes, bad!
1454                                                         DoOneToMany(Srv->GetServerName(),"FMODE",params);
1455                                                 }
1456                                                 strcpy(mode_users[1],"+");
1457                                                 modectr = 2;
1458                                         }
1459                                 }
1460                         }
1461                 }
1462                 /* there werent enough modes built up to flush it during FJOIN,
1463                  * or, there are a number left over. flush them out.
1464                  */
1465                 if ((modectr > 2) && (who))
1466                 {
1467                         if (ourTS >= TS)
1468                         {
1469                                 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
1470                                 Srv->SendMode((const char**)mode_users,modectr,who);
1471                                 if (ourTS != TS)
1472                                 {
1473                                         log(DEFAULT,"Channel TS for %s changed from %lu to %lu",us,ourTS,TS);
1474                                         us->age = TS;
1475                                 }
1476                         }
1477                         else
1478                         {
1479                                 log(DEBUG,"Their channel newer than ours, bouncing their modes");
1480                                 std::deque<std::string> params;
1481                                 *mode_users[1] = '-';
1482                                 for (unsigned int x = 0; x < modectr; x++)
1483                                 {
1484                                         if (x == 1)
1485                                         {
1486                                                 params.push_back(ConvToStr(us->age));
1487                                         }
1488                                         params.push_back(mode_users[x]);
1489                                 }
1490                                 DoOneToMany(Srv->GetServerName(),"FMODE",params);
1491                         }
1492                 }
1493                 return true;
1494         }
1495
1496         bool SyncChannelTS(std::string source, std::deque<std::string> &params)
1497         {
1498                 if (params.size() >= 2)
1499                 {
1500                         chanrec* c = Srv->FindChannel(params[0]);
1501                         if (c)
1502                         {
1503                                 time_t theirTS = atoi(params[1].c_str());
1504                                 time_t ourTS = c->age;
1505                                 if (ourTS >= theirTS)
1506                                 {
1507                                         log(DEBUG,"Updating timestamp for %s, our timestamp was %lu and theirs is %lu",c->name,ourTS,theirTS);
1508                                         c->age = theirTS;
1509                                 }
1510                         }
1511                 }
1512                 DoOneToAllButSender(Srv->GetServerName(),"SYNCTS",params,source);
1513                 return true;
1514         }
1515
1516         /* NICK command */
1517         bool IntroduceClient(std::string source, std::deque<std::string> &params)
1518         {
1519                 if (params.size() < 8)
1520                         return true;
1521                 if (params.size() > 8)
1522                 {
1523                         this->WriteLine(":"+Srv->GetServerName()+" KILL "+params[1]+" :Invalid client introduction ("+params[1]+"?)");
1524                         return true;
1525                 }
1526                 // NICK age nick host dhost ident +modes ip :gecos
1527                 //   0   123  4 56   7
1528                 time_t age = atoi(params[0].c_str());
1529                 
1530                 /* This used to have a pretty craq'y loop doing the same thing,
1531                  * now we just let the STL do the hard work (more efficiently)
1532                  */
1533                 params[5] = params[5].substr(params[5].find_first_not_of('+'));
1534                 
1535                 const char* tempnick = params[1].c_str();
1536                 log(DEBUG,"Introduce client %s!%s@%s",tempnick,params[4].c_str(),params[2].c_str());
1537                 
1538                 user_hash::iterator iter = clientlist.find(tempnick);
1539                 
1540                 if (iter != clientlist.end())
1541                 {
1542                         // nick collision
1543                         log(DEBUG,"Nick collision on %s!%s@%s: %lu %lu",tempnick,params[4].c_str(),params[2].c_str(),(unsigned long)age,(unsigned long)iter->second->age);
1544                         this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
1545                         return true;
1546                 }
1547
1548                 clientlist[tempnick] = new userrec();
1549                 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
1550                 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX-1);
1551                 strlcpy(clientlist[tempnick]->host, params[2].c_str(),63);
1552                 strlcpy(clientlist[tempnick]->dhost, params[3].c_str(),63);
1553                 clientlist[tempnick]->server = FindServerNamePtr(source.c_str());
1554                 strlcpy(clientlist[tempnick]->ident, params[4].c_str(),IDENTMAX);
1555                 strlcpy(clientlist[tempnick]->fullname, params[7].c_str(),MAXGECOS);
1556                 clientlist[tempnick]->registered = REG_ALL;
1557                 clientlist[tempnick]->signon = age;
1558                 
1559                 for (std::string::iterator v = params[5].begin(); v != params[5].end(); v++)
1560                 {
1561                         clientlist[tempnick]->modes[(*v)-65] = 1;
1562                 }
1563                 insp_aton(params[6].c_str(),&clientlist[tempnick]->ip4);
1564
1565                 WriteOpers("*** Client connecting at %s: %s!%s@%s [%s]",clientlist[tempnick]->server,clientlist[tempnick]->nick,clientlist[tempnick]->ident,clientlist[tempnick]->host, insp_ntoa(clientlist[tempnick]->ip4));
1566
1567                 params[7] = ":" + params[7];
1568                 DoOneToAllButSender(source,"NICK",params,source);
1569
1570                 // Increment the Source Servers User Count..
1571                 TreeServer* SourceServer = FindServer(source);
1572                 if (SourceServer)
1573                 {
1574                         log(DEBUG,"Found source server of %s",clientlist[tempnick]->nick);
1575                         SourceServer->AddUserCount();
1576                 }
1577
1578                 return true;
1579         }
1580
1581         /* Send one or more FJOINs for a channel of users.
1582          * If the length of a single line is more than 480-NICKMAX
1583          * in length, it is split over multiple lines.
1584          */
1585         void SendFJoins(TreeServer* Current, chanrec* c)
1586         {
1587                 log(DEBUG,"Sending FJOINs to other server for %s",c->name);
1588                 char list[MAXBUF];
1589                 std::string individual_halfops = ":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age);
1590                 
1591                 size_t dlen, curlen;
1592                 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
1593                 int numusers = 0;
1594                 char* ptr = list + dlen;
1595
1596                 CUList *ulist = c->GetUsers();
1597                 std::vector<userrec*> specific_halfop;
1598                 std::vector<userrec*> specific_voice;
1599                 std::string modes = "";
1600                 std::string params = "";
1601
1602                 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1603                 {
1604                         int x = cflags(i->second,c);
1605                         if ((x & UCMODE_HOP) && (x & UCMODE_OP))
1606                         {
1607                                 specific_halfop.push_back(i->second);
1608                         }
1609                         if (((x & UCMODE_HOP) || (x & UCMODE_OP)) && (x & UCMODE_VOICE))
1610                         {
1611                                 specific_voice.push_back(i->second);
1612                         }
1613
1614                         const char* n = "";
1615                         if (x & UCMODE_OP)
1616                         {
1617                                 n = "@";
1618                         }
1619                         else if (x & UCMODE_HOP)
1620                         {
1621                                 n = "%";
1622                         }
1623                         else if (x & UCMODE_VOICE)
1624                         {
1625                                 n = "+";
1626                         }
1627
1628                         size_t ptrlen = snprintf(ptr, MAXBUF, " %s%s", n, i->second->nick);
1629
1630                         curlen += ptrlen;
1631                         ptr += ptrlen;
1632
1633                         numusers++;
1634
1635                         if (curlen > (480-NICKMAX))
1636                         {
1637                                 this->WriteLine(list);
1638                                 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
1639                                 ptr = list + dlen;
1640                                 ptrlen = 0;
1641                                 numusers = 0;
1642                                 for (unsigned int y = 0; y < specific_voice.size(); y++)
1643                                 {
1644                                         modes.append("v");
1645                                         params.append(specific_voice[y]->nick).append(" ");
1646                                         //this->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" +v "+specific_voice[y]->nick);
1647                                 }
1648                                 for (unsigned int y = 0; y < specific_halfop.size(); y++)
1649                                 {
1650                                         modes.append("h");
1651                                         params.append(specific_halfop[y]->nick).append(" ");
1652                                         //this->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" +h "+specific_halfop[y]->nick);
1653                                 }
1654                         }
1655                 }
1656                 if (numusers)
1657                 {
1658                         this->WriteLine(list);
1659                         for (unsigned int y = 0; y < specific_voice.size(); y++)
1660                         {
1661                                 modes.append("v");
1662                                 params.append(specific_voice[y]->nick).append(" ");
1663                                 //this->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" +v "+specific_voice[y]->nick);
1664                         }
1665                         for (unsigned int y = 0; y < specific_halfop.size(); y++)
1666                         {
1667                                 modes.append("h");
1668                                 params.append(specific_halfop[y]->nick).append(" ");
1669                                 //this->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" +h "+specific_halfop[y]->nick);
1670                         }
1671                 }
1672                 //std::string modes = "";
1673                 //std::string params = "";
1674                 for (BanList::iterator b = c->bans.begin(); b != c->bans.end(); b++)
1675                 {
1676                         modes.append("b");
1677                         params.append(b->data).append(" ");
1678                 }
1679                 /* XXX: Send each channel mode and its params -- we'll need a method for this in ModeHandler? */
1680                 //FOREACH_MOD(I_OnSyncChannel,OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this));
1681                 this->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" +"+chanmodes(c,true)+modes+" "+params);
1682         }
1683
1684         /* Send G, Q, Z and E lines */
1685         void SendXLines(TreeServer* Current)
1686         {
1687                 char data[MAXBUF];
1688                 std::string n = Srv->GetServerName();
1689                 const char* sn = n.c_str();
1690                 int iterations = 0;
1691                 /* Yes, these arent too nice looking, but they get the job done */
1692                 for (std::vector<ZLine>::iterator i = zlines.begin(); i != zlines.end(); i++, iterations++)
1693                 {
1694                         snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s",sn,i->ipaddr,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1695                         this->WriteLine(data);
1696                 }
1697                 for (std::vector<QLine>::iterator i = qlines.begin(); i != qlines.end(); i++, iterations++)
1698                 {
1699                         snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s",sn,i->nick,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1700                         this->WriteLine(data);
1701                 }
1702                 for (std::vector<GLine>::iterator i = glines.begin(); i != glines.end(); i++, iterations++)
1703                 {
1704                         snprintf(data,MAXBUF,":%s ADDLINE G %s %s %lu %lu :%s",sn,i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1705                         this->WriteLine(data);
1706                 }
1707                 for (std::vector<ELine>::iterator i = elines.begin(); i != elines.end(); i++, iterations++)
1708                 {
1709                         snprintf(data,MAXBUF,":%s ADDLINE E %s %s %lu %lu :%s",sn,i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1710                         this->WriteLine(data);
1711                 }
1712                 for (std::vector<ZLine>::iterator i = pzlines.begin(); i != pzlines.end(); i++, iterations++)
1713                 {
1714                         snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s",sn,i->ipaddr,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1715                         this->WriteLine(data);
1716                 }
1717                 for (std::vector<QLine>::iterator i = pqlines.begin(); i != pqlines.end(); i++, iterations++)
1718                 {
1719                         snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s",sn,i->nick,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1720                         this->WriteLine(data);
1721                 }
1722                 for (std::vector<GLine>::iterator i = pglines.begin(); i != pglines.end(); i++, iterations++)
1723                 {
1724                         snprintf(data,MAXBUF,":%s ADDLINE G %s %s %lu %lu :%s",sn,i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1725                         this->WriteLine(data);
1726                 }
1727                 for (std::vector<ELine>::iterator i = pelines.begin(); i != pelines.end(); i++, iterations++)
1728                 {
1729                         snprintf(data,MAXBUF,":%s ADDLINE E %s %s %lu %lu :%s",sn,i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1730                         this->WriteLine(data);
1731                 }
1732         }
1733
1734         /* Send channel modes and topics */
1735         void SendChannelModes(TreeServer* Current)
1736         {
1737                 char data[MAXBUF];
1738                 std::deque<std::string> list;
1739                 int iterations = 0;
1740                 std::string n = Srv->GetServerName();
1741                 const char* sn = n.c_str();
1742                 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++, iterations++)
1743                 {
1744                         SendFJoins(Current, c->second);
1745                         if (*c->second->topic)
1746                         {
1747                                 snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",sn,c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
1748                                 this->WriteLine(data);
1749                         }
1750                         FOREACH_MOD(I_OnSyncChannel,OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this));
1751                         list.clear();
1752                         c->second->GetExtList(list);
1753                         for (unsigned int j = 0; j < list.size(); j++)
1754                         {
1755                                 FOREACH_MOD(I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
1756                         }
1757                 }
1758         }
1759
1760         /* send all users and their oper state/modes */
1761         void SendUsers(TreeServer* Current)
1762         {
1763                 char data[MAXBUF];
1764                 std::deque<std::string> list;
1765                 int iterations = 0;
1766                 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++, iterations++)
1767                 {
1768                         if (u->second->registered == REG_ALL)
1769                         {
1770                                 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(),insp_ntoa(u->second->ip4),u->second->fullname);
1771                                 this->WriteLine(data);
1772                                 if (*u->second->oper)
1773                                 {
1774                                         this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
1775                                 }
1776                                 if (*u->second->awaymsg)
1777                                 {
1778                                         this->WriteLine(":"+std::string(u->second->nick)+" AWAY :"+std::string(u->second->awaymsg));
1779                                 }
1780                                 FOREACH_MOD(I_OnSyncUser,OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this));
1781                                 list.clear();
1782                                 u->second->GetExtList(list);
1783                                 for (unsigned int j = 0; j < list.size(); j++)
1784                                 {
1785                                         FOREACH_MOD(I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
1786                                 }
1787                         }
1788                 }
1789         }
1790
1791         /* This function is called when we want to send a netburst to a local
1792          * server. There is a set order we must do this, because for example
1793          * users require their servers to exist, and channels require their
1794          * users to exist. You get the idea.
1795          */
1796         void DoBurst(TreeServer* s)
1797         {
1798                 /* The calls here to ServerInstance-> yield the processing
1799                  * back to the core so that a large burst is split into at least 6 sections
1800                  * (possibly more)
1801                  */
1802                 std::string burst = "BURST "+ConvToStr(time(NULL));
1803                 std::string endburst = "ENDBURST";
1804                 // Because by the end of the netburst, it  could be gone!
1805                 std::string name = s->GetName();
1806                 Srv->SendOpers("*** Bursting to \2"+name+"\2.");
1807                 this->WriteLine(burst);
1808                 /* send our version string */
1809                 this->WriteLine(":"+Srv->GetServerName()+" VERSION :"+Srv->GetVersion());
1810                 /* Send server tree */
1811                 this->SendServers(TreeRoot,s,1);
1812                 /* Send users and their oper status */
1813                 this->SendUsers(s);
1814                 /* Send everything else (channel modes, xlines etc) */
1815                 this->SendChannelModes(s);
1816                 this->SendXLines(s);            
1817                 FOREACH_MOD(I_OnSyncOtherMetaData,OnSyncOtherMetaData((Module*)TreeProtocolModule,(void*)this));
1818                 this->WriteLine(endburst);
1819                 Srv->SendOpers("*** Finished bursting to \2"+name+"\2.");
1820         }
1821
1822         /* This function is called when we receive data from a remote
1823          * server. We buffer the data in a std::string (it doesnt stay
1824          * there for long), reading using InspSocket::Read() which can
1825          * read up to 16 kilobytes in one operation.
1826          *
1827          * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
1828          * THE SOCKET OBJECT FOR US.
1829          */
1830         virtual bool OnDataReady()
1831         {
1832                 char* data = this->Read();
1833                 /* Check that the data read is a valid pointer and it has some content */
1834                 if (data && *data)
1835                 {
1836                         this->in_buffer.append(data);
1837                         /* While there is at least one new line in the buffer,
1838                          * do something useful (we hope!) with it.
1839                          */
1840                         while (in_buffer.find("\n") != std::string::npos)
1841                         {
1842                                 std::string ret = in_buffer.substr(0,in_buffer.find("\n")-1);
1843                                 in_buffer = in_buffer.substr(in_buffer.find("\n")+1,in_buffer.length()-in_buffer.find("\n"));
1844                                 if (ret.find("\r") != std::string::npos)
1845                                         ret = in_buffer.substr(0,in_buffer.find("\r")-1);
1846                                 /* Process this one, abort if it
1847                                  * didnt return true.
1848                                  */
1849                                 if (this->ctx_in)
1850                                 {
1851                                         char out[1024];
1852                                         char result[1024];
1853                                         memset(result,0,1024);
1854                                         memset(out,0,1024);
1855                                         log(DEBUG,"Original string '%s'",ret.c_str());
1856                                         /* ERROR + CAPAB is still allowed unencryped */
1857                                         if ((ret.substr(0,7) != "ERROR :") && (ret.substr(0,6) != "CAPAB "))
1858                                         {
1859                                                 int nbytes = from64tobits(out, ret.c_str(), 1024);
1860                                                 if ((nbytes > 0) && (nbytes < 1024))
1861                                                 {
1862                                                         log(DEBUG,"m_spanningtree: decrypt %d bytes",nbytes);
1863                                                         ctx_in->Decrypt(out, result, nbytes, 0);
1864                                                         for (int t = 0; t < nbytes; t++)
1865                                                                 if (result[t] == '\7') result[t] = 0;
1866                                                         ret = result;
1867                                                 }
1868                                         }
1869                                 }
1870                                 if (!this->ProcessLine(ret))
1871                                 {
1872                                         log(DEBUG,"ProcessLine says no!");
1873                                         return false;
1874                                 }
1875                         }
1876                         return true;
1877                 }
1878                 /* EAGAIN returns an empty but non-NULL string, so this
1879                  * evaluates to TRUE for EAGAIN but to FALSE for EOF.
1880                  */
1881                 return (data && !*data);
1882         }
1883
1884         int WriteLine(std::string line)
1885         {
1886                 log(DEBUG,"OUT: %s",line.c_str());
1887                 if (this->ctx_out)
1888                 {
1889                         char result[10240];
1890                         char result64[10240];
1891                         if (this->keylength)
1892                         {
1893                                 // pad it to the key length
1894                                 int n = this->keylength - (line.length() % this->keylength);
1895                                 if (n)
1896                                 {
1897                                         log(DEBUG,"Append %d chars to line to make it %d long from %d, key length %d",n,n+line.length(),line.length(),this->keylength);
1898                                         line.append(n,'\7');
1899                                 }
1900                         }
1901                         unsigned int ll = line.length();
1902                         ctx_out->Encrypt(line.c_str(), result, ll, 0);
1903                         to64frombits((unsigned char*)result64,(unsigned char*)result,ll);
1904                         line = result64;
1905                         //int from64tobits(char *out, const char *in, int maxlen);
1906                 }
1907                 return this->Write(line + "\r\n");
1908         }
1909
1910         /* Handle ERROR command */
1911         bool Error(std::deque<std::string> &params)
1912         {
1913                 if (params.size() < 1)
1914                         return false;
1915                 WriteOpers("*** ERROR from %s: %s",(InboundServerName != "" ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
1916                 /* we will return false to cause the socket to close. */
1917                 return false;
1918         }
1919
1920         bool Stats(std::string prefix, std::deque<std::string> &params)
1921         {
1922                 /* Get the reply to a STATS query if it matches this servername,
1923                  * and send it back as a load of PUSH queries
1924                  */
1925                 if (params.size() > 1)
1926                 {
1927                         if (Srv->MatchText(Srv->GetServerName(), params[1]))
1928                         {
1929                                 /* It's for our server */
1930                                 string_list results;
1931                                 userrec* source = Srv->FindNick(prefix);
1932                                 if (source)
1933                                 {
1934                                         std::deque<std::string> par;
1935                                         par.push_back(prefix);
1936                                         par.push_back("");
1937                                         DoStats(*(params[0].c_str()), source, results);
1938                                         for (size_t i = 0; i < results.size(); i++)
1939                                         {
1940                                                 par[1] = "::" + results[i];
1941                                                 DoOneToOne(Srv->GetServerName(), "PUSH",par, source->server);
1942                                         }
1943                                 }
1944                         }
1945                         else
1946                         {
1947                                 /* Pass it on */
1948                                 userrec* source = Srv->FindNick(prefix);
1949                                 if (source)
1950                                         DoOneToOne(prefix, "STATS", params, params[1]);
1951                         }
1952                 }
1953                 return true;
1954         }
1955
1956
1957         /* Because the core won't let users or even SERVERS set +o,
1958          * we use the OPERTYPE command to do this.
1959          */
1960         bool OperType(std::string prefix, std::deque<std::string> &params)
1961         {
1962                 if (params.size() != 1)
1963                 {
1964                         log(DEBUG,"Received invalid oper type from %s",prefix.c_str());
1965                         return true;
1966                 }
1967                 std::string opertype = params[0];
1968                 userrec* u = Srv->FindNick(prefix);
1969                 if (u)
1970                 {
1971                         u->modes[UM_OPERATOR] = 1;
1972                         strlcpy(u->oper,opertype.c_str(),NICKMAX-1);
1973                         DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
1974                 }
1975                 return true;
1976         }
1977
1978         /* Because Andy insists that services-compatible servers must
1979          * implement SVSNICK and SVSJOIN, that's exactly what we do :p
1980          */
1981         bool ForceNick(std::string prefix, std::deque<std::string> &params)
1982         {
1983                 if (params.size() < 3)
1984                         return true;
1985
1986                 userrec* u = Srv->FindNick(params[0]);
1987
1988                 if (u)
1989                 {
1990                         DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
1991                         if (IS_LOCAL(u))
1992                         {
1993                                 std::deque<std::string> par;
1994                                 par.push_back(params[1]);
1995                                 /* This is not required as one is sent in OnUserPostNick below
1996                                  */
1997                                 //DoOneToMany(u->nick,"NICK",par);
1998                                 Srv->ChangeUserNick(u,params[1]);
1999                                 u->age = atoi(params[2].c_str());
2000                         }
2001                 }
2002                 return true;
2003         }
2004
2005         bool ServiceJoin(std::string prefix, std::deque<std::string> &params)
2006         {
2007                 if (params.size() < 2)
2008                         return true;
2009
2010                 userrec* u = Srv->FindNick(params[0]);
2011
2012                 if (u)
2013                 {
2014                         Srv->JoinUserToChannel(u,params[1],"");
2015                         DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
2016                 }
2017                 return true;
2018         }
2019
2020         bool RemoteRehash(std::string prefix, std::deque<std::string> &params)
2021         {
2022                 if (params.size() < 1)
2023                         return false;
2024
2025                 std::string servermask = params[0];
2026
2027                 if (Srv->MatchText(Srv->GetServerName(),servermask))
2028                 {
2029                         Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
2030                         Srv->RehashServer();
2031                         ReadConfiguration(false);
2032                 }
2033                 DoOneToAllButSender(prefix,"REHASH",params,prefix);
2034                 return true;
2035         }
2036
2037         bool RemoteKill(std::string prefix, std::deque<std::string> &params)
2038         {
2039                 if (params.size() != 2)
2040                         return true;
2041
2042                 std::string nick = params[0];
2043                 userrec* u = Srv->FindNick(prefix);
2044                 userrec* who = Srv->FindNick(nick);
2045
2046                 if (who)
2047                 {
2048                         /* Prepend kill source, if we don't have one */
2049                         std::string sourceserv = prefix;
2050                         if (u)
2051                         {
2052                                 sourceserv = u->server;
2053                         }
2054                         if (*(params[1].c_str()) != '[')
2055                         {
2056                                 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
2057                         }
2058                         std::string reason = params[1];
2059                         params[1] = ":" + params[1];
2060                         DoOneToAllButSender(prefix,"KILL",params,sourceserv);
2061                         ::Write(who->fd, ":%s KILL %s :%s (%s)", sourceserv.c_str(), who->nick, sourceserv.c_str(), reason.c_str());
2062                         Srv->QuitUser(who,reason);
2063                 }
2064                 return true;
2065         }
2066
2067         bool LocalPong(std::string prefix, std::deque<std::string> &params)
2068         {
2069                 if (params.size() < 1)
2070                         return true;
2071
2072                 if (params.size() == 1)
2073                 {
2074                         TreeServer* ServerSource = FindServer(prefix);
2075                         if (ServerSource)
2076                         {
2077                                 ServerSource->SetPingFlag();
2078                         }
2079                 }
2080                 else
2081                 {
2082                         std::string forwardto = params[1];
2083                         if (forwardto == Srv->GetServerName())
2084                         {
2085                                 /*
2086                                  * this is a PONG for us
2087                                  * if the prefix is a user, check theyre local, and if they are,
2088                                  * dump the PONG reply back to their fd. If its a server, do nowt.
2089                                  * Services might want to send these s->s, but we dont need to yet.
2090                                  */
2091                                 userrec* u = Srv->FindNick(prefix);
2092
2093                                 if (u)
2094                                 {
2095                                         WriteServ(u->fd,"PONG %s %s",params[0].c_str(),params[1].c_str());
2096                                 }
2097                         }
2098                         else
2099                         {
2100                                 // not for us, pass it on :)
2101                                 DoOneToOne(prefix,"PONG",params,forwardto);
2102                         }
2103                 }
2104
2105                 return true;
2106         }
2107         
2108         bool MetaData(std::string prefix, std::deque<std::string> &params)
2109         {
2110                 if (params.size() < 3)
2111                         return true;
2112
2113                 TreeServer* ServerSource = FindServer(prefix);
2114
2115                 if (ServerSource)
2116                 {
2117                         if (params[0] == "*")
2118                         {
2119                                 FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));
2120                         }
2121                         else if (*(params[0].c_str()) == '#')
2122                         {
2123                                 chanrec* c = Srv->FindChannel(params[0]);
2124                                 if (c)
2125                                 {
2126                                         FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
2127                                 }
2128                         }
2129                         else if (*(params[0].c_str()) != '#')
2130                         {
2131                                 userrec* u = Srv->FindNick(params[0]);
2132                                 if (u)
2133                                 {
2134                                         FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
2135                                 }
2136                         }
2137                 }
2138
2139                 params[2] = ":" + params[2];
2140                 DoOneToAllButSender(prefix,"METADATA",params,prefix);
2141                 return true;
2142         }
2143
2144         bool ServerVersion(std::string prefix, std::deque<std::string> &params)
2145         {
2146                 if (params.size() < 1)
2147                         return true;
2148
2149                 TreeServer* ServerSource = FindServer(prefix);
2150
2151                 if (ServerSource)
2152                 {
2153                         ServerSource->SetVersion(params[0]);
2154                 }
2155                 params[0] = ":" + params[0];
2156                 DoOneToAllButSender(prefix,"VERSION",params,prefix);
2157                 return true;
2158         }
2159
2160         bool ChangeHost(std::string prefix, std::deque<std::string> &params)
2161         {
2162                 if (params.size() < 1)
2163                         return true;
2164
2165                 userrec* u = Srv->FindNick(prefix);
2166
2167                 if (u)
2168                 {
2169                         Srv->ChangeHost(u,params[0]);
2170                         DoOneToAllButSender(prefix,"FHOST",params,u->server);
2171                 }
2172                 return true;
2173         }
2174
2175         bool AddLine(std::string prefix, std::deque<std::string> &params)
2176         {
2177                 if (params.size() < 6)
2178                         return true;
2179
2180                 bool propogate = false;
2181
2182                 switch (*(params[0].c_str()))
2183                 {
2184                         case 'Z':
2185                                 propogate = add_zline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2186                                 zline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2187                         break;
2188                         case 'Q':
2189                                 propogate = add_qline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2190                                 qline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2191                         break;
2192                         case 'E':
2193                                 propogate = add_eline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2194                                 eline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2195                         break;
2196                         case 'G':
2197                                 propogate = add_gline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2198                                 gline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2199                         break;
2200                         case 'K':
2201                                 propogate = add_kline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2202                         break;
2203                         default:
2204                                 /* Just in case... */
2205                                 Srv->SendOpers("*** \2WARNING\2: Invalid xline type '"+params[0]+"' sent by server "+prefix+", ignored!");
2206                                 propogate = false;
2207                         break;
2208                 }
2209
2210                 /* Send it on its way */
2211                 if (propogate)
2212                 {
2213                         if (atoi(params[4].c_str()))
2214                         {
2215                                 WriteOpers("*** %s Added %cLINE on %s to expire in %lu seconds (%s).",prefix.c_str(),*(params[0].c_str()),params[1].c_str(),atoi(params[4].c_str()),params[5].c_str());
2216                         }
2217                         else
2218                         {
2219                                 WriteOpers("*** %s Added permenant %cLINE on %s (%s).",prefix.c_str(),*(params[0].c_str()),params[1].c_str(),params[5].c_str());
2220                         }
2221                         params[5] = ":" + params[5];
2222                         DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
2223                 }
2224                 if (!this->bursting)
2225                 {
2226                         log(DEBUG,"Applying lines...");
2227                         apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2228                 }
2229                 return true;
2230         }
2231
2232         bool ChangeName(std::string prefix, std::deque<std::string> &params)
2233         {
2234                 if (params.size() < 1)
2235                         return true;
2236
2237                 userrec* u = Srv->FindNick(prefix);
2238
2239                 if (u)
2240                 {
2241                         Srv->ChangeGECOS(u,params[0]);
2242                         params[0] = ":" + params[0];
2243                         DoOneToAllButSender(prefix,"FNAME",params,u->server);
2244                 }
2245                 return true;
2246         }
2247
2248         bool Whois(std::string prefix, std::deque<std::string> &params)
2249         {
2250                 if (params.size() < 1)
2251                         return true;
2252
2253                 log(DEBUG,"In IDLE command");
2254                 userrec* u = Srv->FindNick(prefix);
2255
2256                 if (u)
2257                 {
2258                         log(DEBUG,"USER EXISTS: %s",u->nick);
2259                         // an incoming request
2260                         if (params.size() == 1)
2261                         {
2262                                 userrec* x = Srv->FindNick(params[0]);
2263                                 if ((x) && (IS_LOCAL(x)))
2264                                 {
2265                                         userrec* x = Srv->FindNick(params[0]);
2266                                         log(DEBUG,"Got IDLE");
2267                                         char signon[MAXBUF];
2268                                         char idle[MAXBUF];
2269                                         log(DEBUG,"Sending back IDLE 3");
2270                                         snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
2271                                         snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-time(NULL)));
2272                                         std::deque<std::string> par;
2273                                         par.push_back(prefix);
2274                                         par.push_back(signon);
2275                                         par.push_back(idle);
2276                                         // ours, we're done, pass it BACK
2277                                         DoOneToOne(params[0],"IDLE",par,u->server);
2278                                 }
2279                                 else
2280                                 {
2281                                         // not ours pass it on
2282                                         DoOneToOne(prefix,"IDLE",params,x->server);
2283                                 }
2284                         }
2285                         else if (params.size() == 3)
2286                         {
2287                                 std::string who_did_the_whois = params[0];
2288                                 userrec* who_to_send_to = Srv->FindNick(who_did_the_whois);
2289                                 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2290                                 {
2291                                         log(DEBUG,"Got final IDLE");
2292                                         // an incoming reply to a whois we sent out
2293                                         std::string nick_whoised = prefix;
2294                                         unsigned long signon = atoi(params[1].c_str());
2295                                         unsigned long idle = atoi(params[2].c_str());
2296                                         if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2297                                                 do_whois(who_to_send_to,u,signon,idle,nick_whoised.c_str());
2298                                 }
2299                                 else
2300                                 {
2301                                         // not ours, pass it on
2302                                         DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
2303                                 }
2304                         }
2305                 }
2306                 return true;
2307         }
2308
2309         bool Push(std::string prefix, std::deque<std::string> &params)
2310         {
2311                 if (params.size() < 2)
2312                         return true;
2313
2314                 userrec* u = Srv->FindNick(params[0]);
2315
2316                 if (!u)
2317                         return true;
2318
2319                 if (IS_LOCAL(u))
2320                 {
2321                         ::Write(u->fd,"%s",params[1].c_str());
2322                 }
2323                 else
2324                 {
2325                         // continue the raw onwards
2326                         params[1] = ":" + params[1];
2327                         DoOneToOne(prefix,"PUSH",params,u->server);
2328                 }
2329                 return true;
2330         }
2331
2332         bool Time(std::string prefix, std::deque<std::string> &params)
2333         {
2334                 // :source.server TIME remote.server sendernick
2335                 // :remote.server TIME source.server sendernick TS
2336                 if (params.size() == 2)
2337                 {
2338                         // someone querying our time?
2339                         if (Srv->GetServerName() == params[0])
2340                         {
2341                                 userrec* u = Srv->FindNick(params[1]);
2342                                 if (u)
2343                                 {
2344                                         char curtime[256];
2345                                         snprintf(curtime,256,"%lu",(unsigned long)time(NULL));
2346                                         params.push_back(curtime);
2347                                         params[0] = prefix;
2348                                         DoOneToOne(Srv->GetServerName(),"TIME",params,params[0]);
2349                                 }
2350                         }
2351                         else
2352                         {
2353                                 // not us, pass it on
2354                                 userrec* u = Srv->FindNick(params[1]);
2355                                 if (u)
2356                                         DoOneToOne(prefix,"TIME",params,params[0]);
2357                         }
2358                 }
2359                 else if (params.size() == 3)
2360                 {
2361                         // a response to a previous TIME
2362                         userrec* u = Srv->FindNick(params[1]);
2363                         if ((u) && (IS_LOCAL(u)))
2364                         {
2365                         time_t rawtime = atol(params[2].c_str());
2366                         struct tm * timeinfo;
2367                         timeinfo = localtime(&rawtime);
2368                                 char tms[26];
2369                                 snprintf(tms,26,"%s",asctime(timeinfo));
2370                                 tms[24] = 0;
2371                         WriteServ(u->fd,"391 %s %s :%s",u->nick,prefix.c_str(),tms);
2372                         }
2373                         else
2374                         {
2375                                 if (u)
2376                                         DoOneToOne(prefix,"TIME",params,u->server);
2377                         }
2378                 }
2379                 return true;
2380         }
2381         
2382         bool LocalPing(std::string prefix, std::deque<std::string> &params)
2383         {
2384                 if (params.size() < 1)
2385                         return true;
2386
2387                 if (params.size() == 1)
2388                 {
2389                         std::string stufftobounce = params[0];
2390                         this->WriteLine(":"+Srv->GetServerName()+" PONG "+stufftobounce);
2391                         return true;
2392                 }
2393                 else
2394                 {
2395                         std::string forwardto = params[1];
2396                         if (forwardto == Srv->GetServerName())
2397                         {
2398                                 // this is a ping for us, send back PONG to the requesting server
2399                                 params[1] = params[0];
2400                                 params[0] = forwardto;
2401                                 DoOneToOne(forwardto,"PONG",params,params[1]);
2402                         }
2403                         else
2404                         {
2405                                 // not for us, pass it on :)
2406                                 DoOneToOne(prefix,"PING",params,forwardto);
2407                         }
2408                         return true;
2409                 }
2410         }
2411
2412         bool RemoteServer(std::string prefix, std::deque<std::string> &params)
2413         {
2414                 if (params.size() < 4)
2415                         return false;
2416
2417                 std::string servername = params[0];
2418                 std::string password = params[1];
2419                 // hopcount is not used for a remote server, we calculate this ourselves
2420                 std::string description = params[3];
2421                 TreeServer* ParentOfThis = FindServer(prefix);
2422
2423                 if (!ParentOfThis)
2424                 {
2425                         this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
2426                         return false;
2427                 }
2428                 TreeServer* CheckDupe = FindServer(servername);
2429                 if (CheckDupe)
2430                 {
2431                         this->WriteLine("ERROR :Server "+servername+" already exists!");
2432                         Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists");
2433                         return false;
2434                 }
2435                 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
2436                 ParentOfThis->AddChild(Node);
2437                 params[3] = ":" + params[3];
2438                 DoOneToAllButSender(prefix,"SERVER",params,prefix);
2439                 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
2440                 return true;
2441         }
2442
2443         bool Outbound_Reply_Server(std::deque<std::string> &params)
2444         {
2445                 if (params.size() < 4)
2446                         return false;
2447
2448                 irc::string servername = params[0].c_str();
2449                 std::string sname = params[0];
2450                 std::string password = params[1];
2451                 int hops = atoi(params[2].c_str());
2452
2453                 if (hops)
2454                 {
2455                         this->WriteLine("ERROR :Server too far away for authentication");
2456                         Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2457                         return false;
2458                 }
2459                 std::string description = params[3];
2460                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2461                 {
2462                         if ((x->Name == servername) && (x->RecvPass == password))
2463                         {
2464                                 TreeServer* CheckDupe = FindServer(sname);
2465                                 if (CheckDupe)
2466                                 {
2467                                         this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
2468                                         Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
2469                                         return false;
2470                                 }
2471                                 // Begin the sync here. this kickstarts the
2472                                 // other side, waiting in WAIT_AUTH_2 state,
2473                                 // into starting their burst, as it shows
2474                                 // that we're happy.
2475                                 this->LinkState = CONNECTED;
2476                                 // we should add the details of this server now
2477                                 // to the servers tree, as a child of the root
2478                                 // node.
2479                                 TreeServer* Node = new TreeServer(sname,description,TreeRoot,this);
2480                                 TreeRoot->AddChild(Node);
2481                                 params[3] = ":" + params[3];
2482                                 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,sname);
2483                                 this->bursting = true;
2484                                 this->DoBurst(Node);
2485                                 return true;
2486                         }
2487                 }
2488                 this->WriteLine("ERROR :Invalid credentials");
2489                 Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, invalid link credentials");
2490                 return false;
2491         }
2492
2493         bool Inbound_Server(std::deque<std::string> &params)
2494         {
2495                 if (params.size() < 4)
2496                         return false;
2497
2498                 irc::string servername = params[0].c_str();
2499                 std::string sname = params[0];
2500                 std::string password = params[1];
2501                 int hops = atoi(params[2].c_str());
2502
2503                 if (hops)
2504                 {
2505                         this->WriteLine("ERROR :Server too far away for authentication");
2506                         Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2507                         return false;
2508                 }
2509                 std::string description = params[3];
2510                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2511                 {
2512                         if ((x->Name == servername) && (x->RecvPass == password))
2513                         {
2514                                 TreeServer* CheckDupe = FindServer(sname);
2515                                 if (CheckDupe)
2516                                 {
2517                                         this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
2518                                         Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
2519                                         return false;
2520                                 }
2521                                 /* If the config says this link is encrypted, but the remote side
2522                                  * hasnt bothered to send the AES command before SERVER, then we
2523                                  * boot them off as we MUST have this connection encrypted.
2524                                  */
2525                                 if ((x->EncryptionKey != "") && (!this->ctx_in))
2526                                 {
2527                                         this->WriteLine("ERROR :This link requires AES encryption to be enabled. Plaintext connection refused.");
2528                                         Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, remote server did not enable AES.");
2529                                         return false;
2530                                 }
2531                                 Srv->SendOpers("*** Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
2532                                 this->InboundServerName = sname;
2533                                 this->InboundDescription = description;
2534                                 // this is good. Send our details: Our server name and description and hopcount of 0,
2535                                 // along with the sendpass from this block.
2536                                 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
2537                                 // move to the next state, we are now waiting for THEM.
2538                                 this->LinkState = WAIT_AUTH_2;
2539                                 return true;
2540                         }
2541                 }
2542                 this->WriteLine("ERROR :Invalid credentials");
2543                 Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, invalid link credentials");
2544                 return false;
2545         }
2546
2547         void Split(std::string line, std::deque<std::string> &n)
2548         {
2549                 n.clear();
2550                 irc::tokenstream tokens(line);
2551                 std::string param;
2552                 while ((param = tokens.GetToken()) != "")
2553                         n.push_back(param);
2554                 return;
2555         }
2556
2557         bool ProcessLine(std::string line)
2558         {
2559                 std::deque<std::string> params;
2560                 irc::string command;
2561                 std::string prefix;
2562                 
2563                 if (line.empty())
2564                         return true;
2565                 
2566                 line = line.substr(0, line.find_first_of("\r\n"));
2567                 
2568                 log(DEBUG,"IN: %s", line.c_str());
2569                 
2570                 this->Split(line.c_str(),params);
2571                         
2572                 if ((params[0][0] == ':') && (params.size() > 1))
2573                 {
2574                         prefix = params[0].substr(1);
2575                         params.pop_front();
2576                 }
2577
2578                 command = params[0].c_str();
2579                 params.pop_front();
2580
2581                 if ((!this->ctx_in) && (command == "AES"))
2582                 {
2583                         std::string sserv = params[0];
2584                         for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2585                         {
2586                                 if ((x->EncryptionKey != "") && (x->Name == sserv))
2587                                 {
2588                                         this->InitAES(x->EncryptionKey,sserv);
2589                                 }
2590                         }
2591
2592                         return true;
2593                 }
2594                 else if ((this->ctx_in) && (command == "AES"))
2595                 {
2596                         WriteOpers("*** \2AES\2: Encryption already enabled on this connection yet %s is trying to enable it twice!",params[0].c_str());
2597                 }
2598
2599                 switch (this->LinkState)
2600                 {
2601                         TreeServer* Node;
2602                         
2603                         case WAIT_AUTH_1:
2604                                 // Waiting for SERVER command from remote server. Server initiating
2605                                 // the connection sends the first SERVER command, listening server
2606                                 // replies with theirs if its happy, then if the initiator is happy,
2607                                 // it starts to send its net sync, which starts the merge, otherwise
2608                                 // it sends an ERROR.
2609                                 if (command == "PASS")
2610                                 {
2611                                         /* Silently ignored */
2612                                 }
2613                                 else if (command == "SERVER")
2614                                 {
2615                                         return this->Inbound_Server(params);
2616                                 }
2617                                 else if (command == "ERROR")
2618                                 {
2619                                         return this->Error(params);
2620                                 }
2621                                 else if (command == "USER")
2622                                 {
2623                                         this->WriteLine("ERROR :Client connections to this port are prohibited.");
2624                                         return false;
2625                                 }
2626                                 else if (command == "CAPAB")
2627                                 {
2628                                         return this->Capab(params);
2629                                 }
2630                                 else if ((command == "U") || (command == "S"))
2631                                 {
2632                                         this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
2633                                         return false;
2634                                 }
2635                                 else
2636                                 {
2637                                         this->WriteLine("ERROR :Invalid command in negotiation phase.");
2638                                         return false;
2639                                 }
2640                         break;
2641                         case WAIT_AUTH_2:
2642                                 // Waiting for start of other side's netmerge to say they liked our
2643                                 // password.
2644                                 if (command == "SERVER")
2645                                 {
2646                                         // cant do this, they sent it to us in the WAIT_AUTH_1 state!
2647                                         // silently ignore.
2648                                         return true;
2649                                 }
2650                                 else if ((command == "U") || (command == "S"))
2651                                 {
2652                                         this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
2653                                         return false;
2654                                 }
2655                                 else if (command == "BURST")
2656                                 {
2657                                         if (params.size())
2658                                         {
2659                                                 /* If a time stamp is provided, try and check syncronization */
2660                                                 time_t THEM = atoi(params[0].c_str());
2661                                                 long delta = THEM-time(NULL);
2662                                                 if ((delta < -600) || (delta > 600))
2663                                                 {
2664                                                         WriteOpers("*** \2ERROR\2: Your clocks are out by %d seconds (this is more than ten minutes). Link aborted, \2PLEASE SYNC YOUR CLOCKS!\2",abs(delta));
2665                                                         this->WriteLine("ERROR :Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than ten minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
2666                                                         return false;
2667                                                 }
2668                                                 else if ((delta < -60) || (delta > 60))
2669                                                 {
2670                                                         WriteOpers("*** \2WARNING\2: Your clocks are out by %d seconds, please consider synching your clocks.",abs(delta));
2671                                                 }
2672                                         }
2673                                         this->LinkState = CONNECTED;
2674                                         Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
2675                                         TreeRoot->AddChild(Node);
2676                                         params.clear();
2677                                         params.push_back(InboundServerName);
2678                                         params.push_back("*");
2679                                         params.push_back("1");
2680                                         params.push_back(":"+InboundDescription);
2681                                         DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
2682                                         this->bursting = true;
2683                                         this->DoBurst(Node);
2684                                 }
2685                                 else if (command == "ERROR")
2686                                 {
2687                                         return this->Error(params);
2688                                 }
2689                                 else if (command == "CAPAB")
2690                                 {
2691                                         return this->Capab(params);
2692                                 }
2693                                 
2694                         break;
2695                         case LISTENER:
2696                                 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
2697                                 return false;
2698                         break;
2699                         case CONNECTING:
2700                                 if (command == "SERVER")
2701                                 {
2702                                         // another server we connected to, which was in WAIT_AUTH_1 state,
2703                                         // has just sent us their credentials. If we get this far, theyre
2704                                         // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
2705                                         // if we're happy with this, we should send our netburst which
2706                                         // kickstarts the merge.
2707                                         return this->Outbound_Reply_Server(params);
2708                                 }
2709                                 else if (command == "ERROR")
2710                                 {
2711                                         return this->Error(params);
2712                                 }
2713                         break;
2714                         case CONNECTED:
2715                                 // This is the 'authenticated' state, when all passwords
2716                                 // have been exchanged and anything past this point is taken
2717                                 // as gospel.
2718                                 
2719                                 if (prefix != "")
2720                                 {
2721                                         std::string direction = prefix;
2722                                         userrec* t = Srv->FindNick(prefix);
2723                                         if (t)
2724                                         {
2725                                                 direction = t->server;
2726                                         }
2727                                         TreeServer* route_back_again = BestRouteTo(direction);
2728                                         if ((!route_back_again) || (route_back_again->GetSocket() != this))
2729                                         {
2730                                                 if (route_back_again)
2731                                                         log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
2732                                                 return true;
2733                                         }
2734
2735                                         /* Fix by brain:
2736                                          * When there is activity on the socket, reset the ping counter so
2737                                          * that we're not wasting bandwidth pinging an active server.
2738                                          */ 
2739                                         route_back_again->SetNextPingTime(time(NULL) + 120);
2740                                         route_back_again->SetPingFlag();
2741                                 }
2742                                 
2743                                 if (command == "SVSMODE")
2744                                 {
2745                                         /* Services expects us to implement
2746                                          * SVSMODE. In inspircd its the same as
2747                                          * MODE anyway.
2748                                          */
2749                                         command = "MODE";
2750                                 }
2751                                 std::string target = "";
2752                                 /* Yes, know, this is a mess. Its reasonably fast though as we're
2753                                  * working with std::string here.
2754                                  */
2755                                 if ((command == "NICK") && (params.size() > 1))
2756                                 {
2757                                         return this->IntroduceClient(prefix,params);
2758                                 }
2759                                 else if (command == "FJOIN")
2760                                 {
2761                                         return this->ForceJoin(prefix,params);
2762                                 }
2763                                 else if (command == "STATS")
2764                                 {
2765                                         return this->Stats(prefix, params);
2766                                 }
2767                                 else if (command == "SERVER")
2768                                 {
2769                                         return this->RemoteServer(prefix,params);
2770                                 }
2771                                 else if (command == "ERROR")
2772                                 {
2773                                         return this->Error(params);
2774                                 }
2775                                 else if (command == "OPERTYPE")
2776                                 {
2777                                         return this->OperType(prefix,params);
2778                                 }
2779                                 else if (command == "FMODE")
2780                                 {
2781                                         return this->ForceMode(prefix,params);
2782                                 }
2783                                 else if (command == "KILL")
2784                                 {
2785                                         return this->RemoteKill(prefix,params);
2786                                 }
2787                                 else if (command == "FTOPIC")
2788                                 {
2789                                         return this->ForceTopic(prefix,params);
2790                                 }
2791                                 else if (command == "REHASH")
2792                                 {
2793                                         return this->RemoteRehash(prefix,params);
2794                                 }
2795                                 else if (command == "METADATA")
2796                                 {
2797                                         return this->MetaData(prefix,params);
2798                                 }
2799                                 else if (command == "PING")
2800                                 {
2801                                         /*
2802                                          * We just got a ping from a server that's bursting.
2803                                          * This can't be right, so set them to not bursting, and
2804                                          * apply their lines.
2805                                          */
2806                                         if (this->bursting)
2807                                         {
2808                                                 this->bursting = false;
2809                                                 apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2810                                         }
2811                                         if (prefix == "")
2812                                         {
2813                                                 prefix = this->GetName();
2814                                         }
2815                                         return this->LocalPing(prefix,params);
2816                                 }
2817                                 else if (command == "PONG")
2818                                 {
2819                                         /*
2820                                          * We just got a pong from a server that's bursting.
2821                                          * This can't be right, so set them to not bursting, and
2822                                          * apply their lines.
2823                                          */
2824                                         if (this->bursting)
2825                                         {
2826                                                 this->bursting = false;
2827                                                 apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2828                                         }
2829                                         if (prefix == "")
2830                                         {
2831                                                 prefix = this->GetName();
2832                                         }
2833                                         return this->LocalPong(prefix,params);
2834                                 }
2835                                 else if (command == "VERSION")
2836                                 {
2837                                         return this->ServerVersion(prefix,params);
2838                                 }
2839                                 else if (command == "FHOST")
2840                                 {
2841                                         return this->ChangeHost(prefix,params);
2842                                 }
2843                                 else if (command == "FNAME")
2844                                 {
2845                                         return this->ChangeName(prefix,params);
2846                                 }
2847                                 else if (command == "ADDLINE")
2848                                 {
2849                                         return this->AddLine(prefix,params);
2850                                 }
2851                                 else if (command == "SVSNICK")
2852                                 {
2853                                         if (prefix == "")
2854                                         {
2855                                                 prefix = this->GetName();
2856                                         }
2857                                         return this->ForceNick(prefix,params);
2858                                 }
2859                                 else if (command == "IDLE")
2860                                 {
2861                                         return this->Whois(prefix,params);
2862                                 }
2863                                 else if (command == "PUSH")
2864                                 {
2865                                         return this->Push(prefix,params);
2866                                 }
2867                                 else if (command == "TIME")
2868                                 {
2869                                         return this->Time(prefix,params);
2870                                 }
2871                                 else if ((command == "KICK") && (IsServer(prefix)))
2872                                 {
2873                                         std::string sourceserv = this->myhost;
2874                                         if (params.size() == 3)
2875                                         {
2876                                                 userrec* user = Srv->FindNick(params[1]);
2877                                                 chanrec* chan = Srv->FindChannel(params[0]);
2878                                                 if (user && chan)
2879                                                 {
2880                                                         server_kick_channel(user,chan,(char*)params[2].c_str(),false);
2881                                                 }
2882                                         }
2883                                         if (this->InboundServerName != "")
2884                                         {
2885                                                 sourceserv = this->InboundServerName;
2886                                         }
2887                                         return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
2888                                 }
2889                                 else if (command == "SVSJOIN")
2890                                 {
2891                                         if (prefix == "")
2892                                         {
2893                                                 prefix = this->GetName();
2894                                         }
2895                                         return this->ServiceJoin(prefix,params);
2896                                 }
2897                                 else if (command == "SQUIT")
2898                                 {
2899                                         if (params.size() == 2)
2900                                         {
2901                                                 this->Squit(FindServer(params[0]),params[1]);
2902                                         }
2903                                         return true;
2904                                 }
2905                                 else if (command == "ENDBURST")
2906                                 {
2907                                         this->bursting = false;
2908                                         apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2909                                         std::string sourceserv = this->myhost;
2910                                         if (this->InboundServerName != "")
2911                                         {
2912                                                 sourceserv = this->InboundServerName;
2913                                         }
2914                                         WriteOpers("*** Received end of netburst from \2%s\2",sourceserv.c_str());
2915                                         return true;
2916                                 }
2917                                 else
2918                                 {
2919                                         // not a special inter-server command.
2920                                         // Emulate the actual user doing the command,
2921                                         // this saves us having a huge ugly parser.
2922                                         userrec* who = Srv->FindNick(prefix);
2923                                         std::string sourceserv = this->myhost;
2924                                         if (this->InboundServerName != "")
2925                                         {
2926                                                 sourceserv = this->InboundServerName;
2927                                         }
2928                                         if (who)
2929                                         {
2930                                                 if ((command == "NICK") && (params.size() > 0))
2931                                                 {
2932                                                         /* On nick messages, check that the nick doesnt
2933                                                          * already exist here. If it does, kill their copy,
2934                                                          * and our copy.
2935                                                          */
2936                                                         userrec* x = Srv->FindNick(params[0]);
2937                                                         if ((x) && (x != who))
2938                                                         {
2939                                                                 std::deque<std::string> p;
2940                                                                 p.push_back(params[0]);
2941                                                                 p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
2942                                                                 DoOneToMany(Srv->GetServerName(),"KILL",p);
2943                                                                 p.clear();
2944                                                                 p.push_back(prefix);
2945                                                                 p.push_back("Nickname collision");
2946                                                                 DoOneToMany(Srv->GetServerName(),"KILL",p);
2947                                                                 Srv->QuitUser(x,"Nickname collision ("+prefix+" -> "+params[0]+")");
2948                                                                 userrec* y = Srv->FindNick(prefix);
2949                                                                 if (y)
2950                                                                 {
2951                                                                         Srv->QuitUser(y,"Nickname collision");
2952                                                                 }
2953                                                                 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
2954                                                         }
2955                                                 }
2956                                                 // its a user
2957                                                 target = who->server;
2958                                                 const char* strparams[127];
2959                                                 for (unsigned int q = 0; q < params.size(); q++)
2960                                                 {
2961                                                         strparams[q] = params[q].c_str();
2962                                                 }
2963                                                 if (!Srv->CallCommandHandler(command.c_str(), strparams, params.size(), who))
2964                                                 {
2965                                                         this->WriteLine("ERROR :Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
2966                                                         return false;
2967                                                 }
2968                                         }
2969                                         else
2970                                         {
2971                                                 // its not a user. Its either a server, or somethings screwed up.
2972                                                 if (IsServer(prefix))
2973                                                 {
2974                                                         target = Srv->GetServerName();
2975                                                 }
2976                                                 else
2977                                                 {
2978                                                         log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
2979                                                         return true;
2980                                                 }
2981                                         }
2982                                         return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
2983
2984                                 }
2985                                 return true;
2986                         break;
2987                 }
2988                 return true;
2989         }
2990
2991         virtual std::string GetName()
2992         {
2993                 std::string sourceserv = this->myhost;
2994                 if (this->InboundServerName != "")
2995                 {
2996                         sourceserv = this->InboundServerName;
2997                 }
2998                 return sourceserv;
2999         }
3000
3001         virtual void OnTimeout()
3002         {
3003                 if (this->LinkState == CONNECTING)
3004                 {
3005                         Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
3006                 }
3007         }
3008
3009         virtual void OnClose()
3010         {
3011                 // Connection closed.
3012                 // If the connection is fully up (state CONNECTED)
3013                 // then propogate a netsplit to all peers.
3014                 std::string quitserver = this->myhost;
3015                 if (this->InboundServerName != "")
3016                 {
3017                         quitserver = this->InboundServerName;
3018                 }
3019                 TreeServer* s = FindServer(quitserver);
3020                 if (s)
3021                 {
3022                         Squit(s,"Remote host closed the connection");
3023                 }
3024                 WriteOpers("Server '\2%s\2' closed the connection.",quitserver.c_str());
3025         }
3026
3027         virtual int OnIncomingConnection(int newsock, char* ip)
3028         {
3029                 /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
3030                  * or discovering if this port is the server port, we don't allow connections from any
3031                  * IPs for which we don't have a link block.
3032                  */
3033                 bool found = false;
3034                 char resolved_host[MAXBUF];
3035                 vector<Link>::iterator i;
3036                 for (i = LinkBlocks.begin(); i != LinkBlocks.end(); i++)
3037                 {
3038                         if (i->IPAddr == ip)
3039                         {
3040                                 found = true;
3041                                 break;
3042                         }
3043                         /* XXX: Fixme: blocks for a very short amount of time,
3044                          * we should cache these on rehash/startup
3045                          */
3046                         if (CleanAndResolve(resolved_host,i->IPAddr.c_str(),true,1))
3047                         {
3048                                 if (std::string(resolved_host) == ip)
3049                                 {
3050                                         found = true;
3051                                         break;
3052                                 }
3053                         }
3054                 }
3055                 if (!found)
3056                 {
3057                         WriteOpers("Server connection from %s denied (no link blocks with that IP address)", ip);
3058                         close(newsock);
3059                         return false;
3060                 }
3061                 TreeSocket* s = new TreeSocket(newsock, ip);
3062                 Srv->AddSocket(s);
3063                 return true;
3064         }
3065 };
3066
3067 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
3068 {
3069         for (unsigned int c = 0; c < list.size(); c++)
3070         {
3071                 if (list[c] == server)
3072                 {
3073                         return;
3074                 }
3075         }
3076         list.push_back(server);
3077 }
3078
3079 // returns a list of DIRECT servernames for a specific channel
3080 void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
3081 {
3082         CUList *ulist = c->GetUsers();
3083         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
3084         {
3085                 if (i->second->fd < 0)
3086                 {
3087                         TreeServer* best = BestRouteTo(i->second->server);
3088                         if (best)
3089                                 AddThisServer(best,list);
3090                 }
3091         }
3092         return;
3093 }
3094
3095 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, irc::string command, std::deque<std::string> &params)
3096 {
3097         TreeServer* omitroute = BestRouteTo(omit);
3098         if ((command == "NOTICE") || (command == "PRIVMSG"))
3099         {
3100                 if (params.size() >= 2)
3101                 {
3102                         /* Prefixes */
3103                         if ((*(params[0].c_str()) == '@') || (*(params[0].c_str()) == '%') || (*(params[0].c_str()) == '+'))
3104                         {
3105                                 params[0] = params[0].substr(1, params[0].length()-1);
3106                         }
3107                         if ((*(params[0].c_str()) != '#') && (*(params[0].c_str()) != '$'))
3108                         {
3109                                 // special routing for private messages/notices
3110                                 userrec* d = Srv->FindNick(params[0]);
3111                                 if (d)
3112                                 {
3113                                         std::deque<std::string> par;
3114                                         par.push_back(params[0]);
3115                                         par.push_back(":"+params[1]);
3116                                         DoOneToOne(prefix,command.c_str(),par,d->server);
3117                                         return true;
3118                                 }
3119                         }
3120                         else if (*(params[0].c_str()) == '$')
3121                         {
3122                                 std::deque<std::string> par;
3123                                 par.push_back(params[0]);
3124                                 par.push_back(":"+params[1]);
3125                                 DoOneToAllButSender(prefix,command.c_str(),par,omitroute->GetName());
3126                                 return true;
3127                         }
3128                         else
3129                         {
3130                                 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
3131                                 chanrec* c = Srv->FindChannel(params[0]);
3132                                 if (c)
3133                                 {
3134                                         std::deque<TreeServer*> list;
3135                                         GetListOfServersForChannel(c,list);
3136                                         log(DEBUG,"Got a list of %d servers",list.size());
3137                                         unsigned int lsize = list.size();
3138                                         for (unsigned int i = 0; i < lsize; i++)
3139                                         {
3140                                                 TreeSocket* Sock = list[i]->GetSocket();
3141                                                 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
3142                                                 {
3143                                                         log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
3144                                                         Sock->WriteLine(data);
3145                                                 }
3146                                         }
3147                                         return true;
3148                                 }
3149                         }
3150                 }
3151         }
3152         unsigned int items = TreeRoot->ChildCount();
3153         for (unsigned int x = 0; x < items; x++)
3154         {
3155                 TreeServer* Route = TreeRoot->GetChild(x);
3156                 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3157                 {
3158                         TreeSocket* Sock = Route->GetSocket();
3159                         Sock->WriteLine(data);
3160                 }
3161         }
3162         return true;
3163 }
3164
3165 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> &params, std::string omit)
3166 {
3167         TreeServer* omitroute = BestRouteTo(omit);
3168         std::string FullLine = ":" + prefix + " " + command;
3169         unsigned int words = params.size();
3170         for (unsigned int x = 0; x < words; x++)
3171         {
3172                 FullLine = FullLine + " " + params[x];
3173         }
3174         unsigned int items = TreeRoot->ChildCount();
3175         for (unsigned int x = 0; x < items; x++)
3176         {
3177                 TreeServer* Route = TreeRoot->GetChild(x);
3178                 // Send the line IF:
3179                 // The route has a socket (its a direct connection)
3180                 // The route isnt the one to be omitted
3181                 // The route isnt the path to the one to be omitted
3182                 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3183                 {
3184                         TreeSocket* Sock = Route->GetSocket();
3185                         Sock->WriteLine(FullLine);
3186                 }
3187         }
3188         return true;
3189 }
3190
3191 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> &params)
3192 {
3193         std::string FullLine = ":" + prefix + " " + command;
3194         unsigned int words = params.size();
3195         for (unsigned int x = 0; x < words; x++)
3196         {
3197                 FullLine = FullLine + " " + params[x];
3198         }
3199         unsigned int items = TreeRoot->ChildCount();
3200         for (unsigned int x = 0; x < items; x++)
3201         {
3202                 TreeServer* Route = TreeRoot->GetChild(x);
3203                 if (Route->GetSocket())
3204                 {
3205                         TreeSocket* Sock = Route->GetSocket();
3206                         Sock->WriteLine(FullLine);
3207                 }
3208         }
3209         return true;
3210 }
3211
3212 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> &params, std::string target)
3213 {
3214         TreeServer* Route = BestRouteTo(target);
3215         if (Route)
3216         {
3217                 std::string FullLine = ":" + prefix + " " + command;
3218                 unsigned int words = params.size();
3219                 for (unsigned int x = 0; x < words; x++)
3220                 {
3221                         FullLine = FullLine + " " + params[x];
3222                 }
3223                 if (Route->GetSocket())
3224                 {
3225                         TreeSocket* Sock = Route->GetSocket();
3226                         Sock->WriteLine(FullLine);
3227                 }
3228                 return true;
3229         }
3230         else
3231         {
3232                 return true;
3233         }
3234 }
3235
3236 std::vector<TreeSocket*> Bindings;
3237
3238 void ReadConfiguration(bool rebind)
3239 {
3240         Conf = new ConfigReader;
3241         if (rebind)
3242         {
3243                 for (int j =0; j < Conf->Enumerate("bind"); j++)
3244                 {
3245                         std::string Type = Conf->ReadValue("bind","type",j);
3246                         std::string IP = Conf->ReadValue("bind","address",j);
3247                         long Port = Conf->ReadInteger("bind","port",j,true);
3248                         if (Type == "servers")
3249                         {
3250                                 if (IP == "*")
3251                                 {
3252                                         IP = "";
3253                                 }
3254                                 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
3255                                 if (listener->GetState() == I_LISTENING)
3256                                 {
3257                                         Srv->AddSocket(listener);
3258                                         Bindings.push_back(listener);
3259                                 }
3260                                 else
3261                                 {
3262                                         log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
3263                                         listener->Close();
3264                                         DELETE(listener);
3265                                 }
3266                         }
3267                 }
3268         }
3269         FlatLinks = Conf->ReadFlag("options","flatlinks",0);
3270         HideULines = Conf->ReadFlag("options","hideulines",0);
3271         LinkBlocks.clear();
3272         for (int j =0; j < Conf->Enumerate("link"); j++)
3273         {
3274                 Link L;
3275                 L.Name = (Conf->ReadValue("link","name",j)).c_str();
3276                 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
3277                 L.Port = Conf->ReadInteger("link","port",j,true);
3278                 L.SendPass = Conf->ReadValue("link","sendpass",j);
3279                 L.RecvPass = Conf->ReadValue("link","recvpass",j);
3280                 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
3281                 L.EncryptionKey =  Conf->ReadValue("link","encryptionkey",j);
3282                 L.HiddenFromStats = Conf->ReadFlag("link","hidden",j);
3283                 L.NextConnectTime = time(NULL) + L.AutoConnect;
3284                 /* Bugfix by brain, do not allow people to enter bad configurations */
3285                 if ((L.IPAddr != "") && (L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
3286                 {
3287                         LinkBlocks.push_back(L);
3288                         log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
3289                 }
3290                 else
3291                 {
3292                         if (L.IPAddr == "")
3293                         {
3294                                 log(DEFAULT,"Invalid configuration for server '%s', IP address not defined!",L.Name.c_str());
3295                         }
3296                         else if (L.RecvPass == "")
3297                         {
3298                                 log(DEFAULT,"Invalid configuration for server '%s', recvpass not defined!",L.Name.c_str());
3299                         }
3300                         else if (L.SendPass == "")
3301                         {
3302                                 log(DEFAULT,"Invalid configuration for server '%s', sendpass not defined!",L.Name.c_str());
3303                         }
3304                         else if (L.Name == "")
3305                         {
3306                                 log(DEFAULT,"Invalid configuration, link tag without a name!");
3307                         }
3308                         else if (!L.Port)
3309                         {
3310                                 log(DEFAULT,"Invalid configuration for server '%s', no port specified!",L.Name.c_str());
3311                         }
3312                 }
3313         }
3314         DELETE(Conf);
3315 }
3316
3317
3318 class ModuleSpanningTree : public Module
3319 {
3320         std::vector<TreeSocket*> Bindings;
3321         int line;
3322         int NumServers;
3323         unsigned int max_local;
3324         unsigned int max_global;
3325         cmd_rconnect* command_rconnect;
3326
3327  public:
3328
3329         ModuleSpanningTree(Server* Me)
3330                 : Module::Module(Me), max_local(0), max_global(0)
3331         {
3332                 Srv = Me;
3333                 Bindings.clear();
3334
3335                 // Create the root of the tree
3336                 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
3337
3338                 ReadConfiguration(true);
3339
3340                 command_rconnect = new cmd_rconnect(this);
3341                 Srv->AddCommand(command_rconnect);
3342         }
3343
3344         void ShowLinks(TreeServer* Current, userrec* user, int hops)
3345         {
3346                 std::string Parent = TreeRoot->GetName();
3347                 if (Current->GetParent())
3348                 {
3349                         Parent = Current->GetParent()->GetName();
3350                 }
3351                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
3352                 {
3353                         if ((HideULines) && (Srv->IsUlined(Current->GetChild(q)->GetName())))
3354                         {
3355                                 if (*user->oper)
3356                                 {
3357                                          ShowLinks(Current->GetChild(q),user,hops+1);
3358                                 }
3359                         }
3360                         else
3361                         {
3362                                 ShowLinks(Current->GetChild(q),user,hops+1);
3363                         }
3364                 }
3365                 /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
3366                 if ((HideULines) && (Srv->IsUlined(Current->GetName())) && (!*user->oper))
3367                         return;
3368                 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),(FlatLinks && (!*user->oper)) ? Srv->GetServerName().c_str() : Parent.c_str(),(FlatLinks && (!*user->oper)) ? 0 : hops,Current->GetDesc().c_str());
3369         }
3370
3371         int CountLocalServs()
3372         {
3373                 return TreeRoot->ChildCount();
3374         }
3375
3376         int CountServs()
3377         {
3378                 return serverlist.size();
3379         }
3380
3381         void HandleLinks(const char** parameters, int pcnt, userrec* user)
3382         {
3383                 ShowLinks(TreeRoot,user,0);
3384                 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
3385                 return;
3386         }
3387
3388         void HandleLusers(const char** parameters, int pcnt, userrec* user)
3389         {
3390                 unsigned int n_users = usercnt();
3391
3392                 /* Only update these when someone wants to see them, more efficient */
3393                 if ((unsigned int)local_count() > max_local)
3394                         max_local = local_count();
3395                 if (n_users > max_global)
3396                         max_global = n_users;
3397
3398                 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,n_users-usercount_invisible(),usercount_invisible(),this->CountServs());
3399                 if (usercount_opers())
3400                         WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
3401                 if (usercount_unknown())
3402                         WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
3403                 if (chancount())
3404                         WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
3405                 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),this->CountLocalServs());
3406                 WriteServ(user->fd,"265 %s :Current Local Users: %d  Max: %d",user->nick,local_count(),max_local);
3407                 WriteServ(user->fd,"266 %s :Current Global Users: %d  Max: %d",user->nick,n_users,max_global);
3408                 return;
3409         }
3410
3411         // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
3412
3413         void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80], float &totusers, float &totservers)
3414         {
3415                 if (line < 128)
3416                 {
3417                         for (int t = 0; t < depth; t++)
3418                         {
3419                                 matrix[line][t] = ' ';
3420                         }
3421
3422                         // For Aligning, we need to work out exactly how deep this thing is, and produce
3423                         // a 'Spacer' String to compensate.
3424                         char spacer[40];
3425
3426                         memset(spacer,' ',40);
3427                         if ((40 - Current->GetName().length() - depth) > 1) {
3428                                 spacer[40 - Current->GetName().length() - depth] = '\0';
3429                         }
3430                         else
3431                         {
3432                                 spacer[5] = '\0';
3433                         }
3434
3435                         float percent;
3436                         char text[80];
3437                         if (clientlist.size() == 0) {
3438                                 // If there are no users, WHO THE HELL DID THE /MAP?!?!?!
3439                                 percent = 0;
3440                         }
3441                         else
3442                         {
3443                                 percent = ((float)Current->GetUserCount() / (float)clientlist.size()) * 100;
3444                         }
3445                         snprintf(text, 80, "%s %s%5d [%5.2f%%]", Current->GetName().c_str(), spacer, Current->GetUserCount(), percent);
3446                         totusers += Current->GetUserCount();
3447                         totservers++;
3448                         strlcpy(&matrix[line][depth],text,80);
3449                         line++;
3450                         for (unsigned int q = 0; q < Current->ChildCount(); q++)
3451                         {
3452                                 if ((HideULines) && (Srv->IsUlined(Current->GetChild(q)->GetName())))
3453                                 {
3454                                         if (*user->oper)
3455                                         {
3456                                                 ShowMap(Current->GetChild(q),user,(FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
3457                                         }
3458                                 }
3459                                 else
3460                                 {
3461                                         ShowMap(Current->GetChild(q),user,(FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
3462                                 }
3463                         }
3464                 }
3465         }
3466
3467         int HandleStats(const char** parameters, int pcnt, userrec* user)
3468         {
3469                 if (pcnt > 1)
3470                 {
3471                         /* Remote STATS, the server is within the 2nd parameter */
3472                         std::deque<std::string> params;
3473                         params.push_back(parameters[0]);
3474                         params.push_back(parameters[1]);
3475                         /* Send it out remotely, generate no reply yet */
3476                         TreeServer* s = FindServerMask(parameters[1]);
3477                         if (s)
3478                         {
3479                                 params[1] = s->GetName();
3480                                 DoOneToOne(user->nick, "STATS", params, s->GetName());
3481                         }
3482                         return 1;
3483                 }
3484                 return 0;
3485         }
3486
3487         // Ok, prepare to be confused.
3488         // After much mulling over how to approach this, it struck me that
3489         // the 'usual' way of doing a /MAP isnt the best way. Instead of
3490         // keeping track of a ton of ascii characters, and line by line
3491         // under recursion working out where to place them using multiplications
3492         // and divisons, we instead render the map onto a backplane of characters
3493         // (a character matrix), then draw the branches as a series of "L" shapes
3494         // from the nodes. This is not only friendlier on CPU it uses less stack.
3495
3496         void HandleMap(const char** parameters, int pcnt, userrec* user)
3497         {
3498                 // This array represents a virtual screen which we will
3499                 // "scratch" draw to, as the console device of an irc
3500                 // client does not provide for a proper terminal.
3501                 float totusers = 0;
3502                 float totservers = 0;
3503                 char matrix[128][80];
3504                 for (unsigned int t = 0; t < 128; t++)
3505                 {
3506                         matrix[t][0] = '\0';
3507                 }
3508                 line = 0;
3509                 // The only recursive bit is called here.
3510                 ShowMap(TreeRoot,user,0,matrix,totusers,totservers);
3511                 // Process each line one by one. The algorithm has a limit of
3512                 // 128 servers (which is far more than a spanning tree should have
3513                 // anyway, so we're ok). This limit can be raised simply by making
3514                 // the character matrix deeper, 128 rows taking 10k of memory.
3515                 for (int l = 1; l < line; l++)
3516                 {
3517                         // scan across the line looking for the start of the
3518                         // servername (the recursive part of the algorithm has placed
3519                         // the servers at indented positions depending on what they
3520                         // are related to)
3521                         int first_nonspace = 0;
3522                         while (matrix[l][first_nonspace] == ' ')
3523                         {
3524                                 first_nonspace++;
3525                         }
3526                         first_nonspace--;
3527                         // Draw the `- (corner) section: this may be overwritten by
3528                         // another L shape passing along the same vertical pane, becoming
3529                         // a |- (branch) section instead.
3530                         matrix[l][first_nonspace] = '-';
3531                         matrix[l][first_nonspace-1] = '`';
3532                         int l2 = l - 1;
3533                         // Draw upwards until we hit the parent server, causing possibly
3534                         // other corners (`-) to become branches (|-)
3535                         while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
3536                         {
3537                                 matrix[l2][first_nonspace-1] = '|';
3538                                 l2--;
3539                         }
3540                 }
3541                 // dump the whole lot to the user. This is the easy bit, honest.
3542                 for (int t = 0; t < line; t++)
3543                 {
3544                         WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
3545                 }
3546                 float avg_users = totusers / totservers;
3547                 WriteServ(user->fd,"270 %s :%.0f server%s and %.0f user%s, average %.2f users per server",user->nick,totservers,(totservers > 1 ? "s" : ""),totusers,(totusers > 1 ? "s" : ""),avg_users);
3548         WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
3549                 return;
3550         }
3551
3552         int HandleSquit(const char** parameters, int pcnt, userrec* user)
3553         {
3554                 TreeServer* s = FindServerMask(parameters[0]);
3555                 if (s)
3556                 {
3557                         if (s == TreeRoot)
3558                         {
3559                                  WriteServ(user->fd,"NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
3560                                 return 1;
3561                         }
3562                         TreeSocket* sock = s->GetSocket();
3563                         if (sock)
3564                         {
3565                                 log(DEBUG,"Splitting server %s",s->GetName().c_str());
3566                                 WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
3567                                 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
3568                                 Srv->RemoveSocket(sock);
3569                         }
3570                         else
3571                         {
3572                                 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
3573                         }
3574                 }
3575                 else
3576                 {
3577                          WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
3578                 }
3579                 return 1;
3580         }
3581
3582         int HandleTime(const char** parameters, int pcnt, userrec* user)
3583         {
3584                 if ((IS_LOCAL(user)) && (pcnt))
3585                 {
3586                         TreeServer* found = FindServerMask(parameters[0]);
3587                         if (found)
3588                         {
3589                                 // we dont' override for local server
3590                                 if (found == TreeRoot)
3591                                         return 0;
3592                                 
3593                                 std::deque<std::string> params;
3594                                 params.push_back(found->GetName());
3595                                 params.push_back(user->nick);
3596                                 DoOneToOne(Srv->GetServerName(),"TIME",params,found->GetName());
3597                         }
3598                         else
3599                         {
3600                                 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
3601                         }
3602                 }
3603                 return 1;
3604         }
3605
3606         int HandleRemoteWhois(const char** parameters, int pcnt, userrec* user)
3607         {
3608                 if ((IS_LOCAL(user)) && (pcnt > 1))
3609                 {
3610                         userrec* remote = Srv->FindNick(parameters[1]);
3611                         if ((remote) && (remote->fd < 0))
3612                         {
3613                                 std::deque<std::string> params;
3614                                 params.push_back(parameters[1]);
3615                                 DoOneToOne(user->nick,"IDLE",params,remote->server);
3616                                 return 1;
3617                         }
3618                         else if (!remote)
3619                         {
3620                                 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
3621                                 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
3622                                 return 1;
3623                         }
3624                 }
3625                 return 0;
3626         }
3627
3628         void DoPingChecks(time_t curtime)
3629         {
3630                 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
3631                 {
3632                         TreeServer* serv = TreeRoot->GetChild(j);
3633                         TreeSocket* sock = serv->GetSocket();
3634                         if (sock)
3635                         {
3636                                 if (curtime >= serv->NextPingTime())
3637                                 {
3638                                         if (serv->AnsweredLastPing())
3639                                         {
3640                                                 sock->WriteLine(":"+Srv->GetServerName()+" PING "+serv->GetName());
3641                                                 serv->SetNextPingTime(curtime + 120);
3642                                         }
3643                                         else
3644                                         {
3645                                                 // they didnt answer, boot them
3646                                                 WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
3647                                                 sock->Squit(serv,"Ping timeout");
3648                                                 Srv->RemoveSocket(sock);
3649                                                 return;
3650                                         }
3651                                 }
3652                         }
3653                 }
3654         }
3655
3656         void AutoConnectServers(time_t curtime)
3657         {
3658                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
3659                 {
3660                         if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
3661                         {
3662                                 log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
3663                                 x->NextConnectTime = curtime + x->AutoConnect;
3664                                 TreeServer* CheckDupe = FindServer(x->Name.c_str());
3665                                 if (!CheckDupe)
3666                                 {
3667                                         // an autoconnected server is not connected. Check if its time to connect it
3668                                         WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
3669                                         TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name.c_str());
3670                                         if (newsocket->GetFd() > -1)
3671                                         {
3672                                                 Srv->AddSocket(newsocket);
3673                                         }
3674                                         else
3675                                         {
3676                                                 WriteOpers("*** AUTOCONNECT: Error autoconnecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
3677                                                 DELETE(newsocket);
3678                                         }
3679                                 }
3680                         }
3681                 }
3682         }
3683
3684         int HandleVersion(const char** parameters, int pcnt, userrec* user)
3685         {
3686                 // we've already checked if pcnt > 0, so this is safe
3687                 TreeServer* found = FindServerMask(parameters[0]);
3688                 if (found)
3689                 {
3690                         std::string Version = found->GetVersion();
3691                         WriteServ(user->fd,"351 %s :%s",user->nick,Version.c_str());
3692                         if (found == TreeRoot)
3693                         {
3694                                 std::stringstream out(Config->data005);
3695                                 std::string token = "";
3696                                 std::string line5 = "";
3697                                 int token_counter = 0;
3698
3699                                 while (!out.eof())
3700                                 {
3701                                         out >> token;
3702                                         line5 = line5 + token + " ";   
3703                                         token_counter++;
3704
3705                                         if ((token_counter >= 13) || (out.eof() == true))
3706                                         {
3707                                                 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
3708                                                 line5 = "";
3709                                                 token_counter = 0;
3710                                         }
3711                                 }
3712                         }
3713                 }
3714                 else
3715                 {
3716                         WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
3717                 }
3718                 return 1;
3719         }
3720         
3721         int HandleConnect(const char** parameters, int pcnt, userrec* user)
3722         {
3723                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
3724                 {
3725                         if (Srv->MatchText(x->Name.c_str(),parameters[0]))
3726                         {
3727                                 TreeServer* CheckDupe = FindServer(x->Name.c_str());
3728                                 if (!CheckDupe)
3729                                 {
3730                                         WriteServ(user->fd,"NOTICE %s :*** CONNECT: Connecting to server: \002%s\002 (%s:%d)",user->nick,x->Name.c_str(),(x->HiddenFromStats ? "<hidden>" : x->IPAddr.c_str()),x->Port);
3731                                         TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name.c_str());
3732                                         if (newsocket->GetFd() > -1)
3733                                         {
3734                                                 Srv->AddSocket(newsocket);
3735                                         }
3736                                         else
3737                                         {
3738                                                 WriteServ(user->fd,"NOTICE %s :*** CONNECT: Error connecting \002%s\002: %s.",user->nick,x->Name.c_str(),strerror(errno));
3739                                                 DELETE(newsocket);
3740                                         }
3741                                         return 1;
3742                                 }
3743                                 else
3744                                 {
3745                                         WriteServ(user->fd,"NOTICE %s :*** CONNECT: Server \002%s\002 already exists on the network and is connected via \002%s\002",user->nick,x->Name.c_str(),CheckDupe->GetParent()->GetName().c_str());
3746                                         return 1;
3747                                 }
3748                         }
3749                 }
3750                 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
3751                 return 1;
3752         }
3753
3754         virtual int OnStats(char statschar, userrec* user, string_list &results)
3755         {
3756                 if (statschar == 'c')
3757                 {
3758                         for (unsigned int i = 0; i < LinkBlocks.size(); i++)
3759                         {
3760                                 results.push_back(Srv->GetServerName()+" 213 "+user->nick+" C *@"+(LinkBlocks[i].HiddenFromStats ? "<hidden>" : LinkBlocks[i].IPAddr)+" * "+LinkBlocks[i].Name.c_str()+" "+ConvToStr(LinkBlocks[i].Port)+" "+(LinkBlocks[i].EncryptionKey != "" ? 'e' : '-')+(LinkBlocks[i].AutoConnect ? 'a' : '-')+'s');
3761                                 results.push_back(Srv->GetServerName()+" 244 "+user->nick+" H * * "+LinkBlocks[i].Name.c_str());
3762                         }
3763                         results.push_back(Srv->GetServerName()+" 219 "+user->nick+" "+statschar+" :End of /STATS report");
3764                         WriteOpers("*** Notice: %s '%c' requested by %s (%s@%s)",(!strcmp(user->server,Config->ServerName) ? "Stats" : "Remote stats"),statschar,user->nick,user->ident,user->host);
3765                         return 1;
3766                 }
3767                 return 0;
3768         }
3769
3770         virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated)
3771         {
3772                 /* If the command doesnt appear to be valid, we dont want to mess with it. */
3773                 if (!validated)
3774                         return 0;
3775
3776                 if (command == "CONNECT")
3777                 {
3778                         return this->HandleConnect(parameters,pcnt,user);
3779                 }
3780                 else if (command == "STATS")
3781                 {
3782                         return this->HandleStats(parameters,pcnt,user);
3783                 }
3784                 else if (command == "SQUIT")
3785                 {
3786                         return this->HandleSquit(parameters,pcnt,user);
3787                 }
3788                 else if (command == "MAP")
3789                 {
3790                         this->HandleMap(parameters,pcnt,user);
3791                         return 1;
3792                 }
3793                 else if ((command == "TIME") && (pcnt > 0))
3794                 {
3795                         return this->HandleTime(parameters,pcnt,user);
3796                 }
3797                 else if (command == "LUSERS")
3798                 {
3799                         this->HandleLusers(parameters,pcnt,user);
3800                         return 1;
3801                 }
3802                 else if (command == "LINKS")
3803                 {
3804                         this->HandleLinks(parameters,pcnt,user);
3805                         return 1;
3806                 }
3807                 else if (command == "WHOIS")
3808                 {
3809                         if (pcnt > 1)
3810                         {
3811                                 // remote whois
3812                                 return this->HandleRemoteWhois(parameters,pcnt,user);
3813                         }
3814                 }
3815                 else if ((command == "VERSION") && (pcnt > 0))
3816                 {
3817                         this->HandleVersion(parameters,pcnt,user);
3818                         return 1;
3819                 }
3820                 else if (Srv->IsValidModuleCommand(command, pcnt, user))
3821                 {
3822                         // this bit of code cleverly routes all module commands
3823                         // to all remote severs *automatically* so that modules
3824                         // can just handle commands locally, without having
3825                         // to have any special provision in place for remote
3826                         // commands and linking protocols.
3827                         std::deque<std::string> params;
3828                         params.clear();
3829                         for (int j = 0; j < pcnt; j++)
3830                         {
3831                                 if (strchr(parameters[j],' '))
3832                                 {
3833                                         params.push_back(":" + std::string(parameters[j]));
3834                                 }
3835                                 else
3836                                 {
3837                                         params.push_back(std::string(parameters[j]));
3838                                 }
3839                         }
3840                         log(DEBUG,"Globally route '%s'",command.c_str());
3841                         DoOneToMany(user->nick,command,params);
3842                 }
3843                 return 0;
3844         }
3845
3846         virtual void OnGetServerDescription(const std::string &servername,std::string &description)
3847         {
3848                 TreeServer* s = FindServer(servername);
3849                 if (s)
3850                 {
3851                         description = s->GetDesc();
3852                 }
3853         }
3854
3855         virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
3856         {
3857                 if (IS_LOCAL(source))
3858                 {
3859                         std::deque<std::string> params;
3860                         params.push_back(dest->nick);
3861                         params.push_back(channel->name);
3862                         DoOneToMany(source->nick,"INVITE",params);
3863                 }
3864         }
3865
3866         virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, const std::string &topic)
3867         {
3868                 std::deque<std::string> params;
3869                 params.push_back(chan->name);
3870                 params.push_back(":"+topic);
3871                 DoOneToMany(user->nick,"TOPIC",params);
3872         }
3873
3874         virtual void OnWallops(userrec* user, const std::string &text)
3875         {
3876                 if (IS_LOCAL(user))
3877                 {
3878                         std::deque<std::string> params;
3879                         params.push_back(":"+text);
3880                         DoOneToMany(user->nick,"WALLOPS",params);
3881                 }
3882         }
3883
3884         virtual void OnUserNotice(userrec* user, void* dest, int target_type, const std::string &text, char status)
3885         {
3886                 if (target_type == TYPE_USER)
3887                 {
3888                         userrec* d = (userrec*)dest;
3889                         if ((d->fd < 0) && (IS_LOCAL(user)))
3890                         {
3891                                 std::deque<std::string> params;
3892                                 params.clear();
3893                                 params.push_back(d->nick);
3894                                 params.push_back(":"+text);
3895                                 DoOneToOne(user->nick,"NOTICE",params,d->server);
3896                         }
3897                 }
3898                 else if (target_type == TYPE_CHANNEL)
3899                 {
3900                         if (IS_LOCAL(user))
3901                         {
3902                                 chanrec *c = (chanrec*)dest;
3903                                 std::string cname = c->name;
3904                                 if (status)
3905                                         cname = status + cname;
3906                                 std::deque<TreeServer*> list;
3907                                 GetListOfServersForChannel(c,list);
3908                                 unsigned int ucount = list.size();
3909                                 for (unsigned int i = 0; i < ucount; i++)
3910                                 {
3911                                         TreeSocket* Sock = list[i]->GetSocket();
3912                                         if (Sock)
3913                                                 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+cname+" :"+text);
3914                                 }
3915                         }
3916                 }
3917                 else if (target_type == TYPE_SERVER)
3918                 {
3919                         if (IS_LOCAL(user))
3920                         {
3921                                 char* target = (char*)dest;
3922                                 std::deque<std::string> par;
3923                                 par.push_back(target);
3924                                 par.push_back(":"+text);
3925                                 DoOneToMany(user->nick,"NOTICE",par);
3926                         }
3927                 }
3928         }
3929
3930         virtual void OnUserMessage(userrec* user, void* dest, int target_type, const std::string &text, char status)
3931         {
3932                 if (target_type == TYPE_USER)
3933                 {
3934                         // route private messages which are targetted at clients only to the server
3935                         // which needs to receive them
3936                         userrec* d = (userrec*)dest;
3937                         if ((d->fd < 0) && (IS_LOCAL(user)))
3938                         {
3939                                 std::deque<std::string> params;
3940                                 params.clear();
3941                                 params.push_back(d->nick);
3942                                 params.push_back(":"+text);
3943                                 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
3944                         }
3945                 }
3946                 else if (target_type == TYPE_CHANNEL)
3947                 {
3948                         if (IS_LOCAL(user))
3949                         {
3950                                 chanrec *c = (chanrec*)dest;
3951                                 std::string cname = c->name;
3952                                 if (status)
3953                                         cname = status + cname;
3954                                 std::deque<TreeServer*> list;
3955                                 GetListOfServersForChannel(c,list);
3956                                 unsigned int ucount = list.size();
3957                                 for (unsigned int i = 0; i < ucount; i++)
3958                                 {
3959                                         TreeSocket* Sock = list[i]->GetSocket();
3960                                         if (Sock)
3961                                                 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+cname+" :"+text);
3962                                 }
3963                         }
3964                 }
3965                 else if (target_type == TYPE_SERVER)
3966                 {
3967                         if (IS_LOCAL(user))
3968                         {
3969                                 char* target = (char*)dest;
3970                                 std::deque<std::string> par;
3971                                 par.push_back(target);
3972                                 par.push_back(":"+text);
3973                                 DoOneToMany(user->nick,"PRIVMSG",par);
3974                         }
3975                 }
3976         }
3977
3978         virtual void OnBackgroundTimer(time_t curtime)
3979         {
3980                 AutoConnectServers(curtime);
3981                 DoPingChecks(curtime);
3982         }
3983
3984         virtual void OnUserJoin(userrec* user, chanrec* channel)
3985         {
3986                 // Only do this for local users
3987                 if (IS_LOCAL(user))
3988                 {
3989                         std::deque<std::string> params;
3990                         params.clear();
3991                         params.push_back(channel->name);
3992
3993                         if (channel->GetUserCounter() > 1)
3994                         {
3995                                 // not the first in the channel
3996                                 DoOneToMany(user->nick,"JOIN",params);
3997                         }
3998                         else
3999                         {
4000                                 // first in the channel, set up their permissions
4001                                 // and the channel TS with FJOIN.
4002                                 char ts[24];
4003                                 snprintf(ts,24,"%lu",(unsigned long)channel->age);
4004                                 params.clear();
4005                                 params.push_back(channel->name);
4006                                 params.push_back(ts);
4007                                 params.push_back("@"+std::string(user->nick));
4008                                 DoOneToMany(Srv->GetServerName(),"FJOIN",params);
4009                         }
4010                 }
4011         }
4012
4013         virtual void OnChangeHost(userrec* user, const std::string &newhost)
4014         {
4015                 // only occurs for local clients
4016                 if (user->registered != REG_ALL)
4017                         return;
4018                 std::deque<std::string> params;
4019                 params.push_back(newhost);
4020                 DoOneToMany(user->nick,"FHOST",params);
4021         }
4022
4023         virtual void OnChangeName(userrec* user, const std::string &gecos)
4024         {
4025                 // only occurs for local clients
4026                 if (user->registered != REG_ALL)
4027                         return;
4028                 std::deque<std::string> params;
4029                 params.push_back(gecos);
4030                 DoOneToMany(user->nick,"FNAME",params);
4031         }
4032
4033         virtual void OnUserPart(userrec* user, chanrec* channel, const std::string &partmessage)
4034         {
4035                 if (IS_LOCAL(user))
4036                 {
4037                         std::deque<std::string> params;
4038                         params.push_back(channel->name);
4039                         if (partmessage != "")
4040                                 params.push_back(":"+partmessage);
4041                         DoOneToMany(user->nick,"PART",params);
4042                 }
4043         }
4044
4045         virtual void OnUserConnect(userrec* user)
4046         {
4047                 char agestr[MAXBUF];
4048                 if (IS_LOCAL(user))
4049                 {
4050                         std::deque<std::string> params;
4051                         snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
4052                         params.push_back(agestr);
4053                         params.push_back(user->nick);
4054                         params.push_back(user->host);
4055                         params.push_back(user->dhost);
4056                         params.push_back(user->ident);
4057                         params.push_back("+"+std::string(user->FormatModes()));
4058                         params.push_back((char*)insp_ntoa(user->ip4));
4059                         params.push_back(":"+std::string(user->fullname));
4060                         DoOneToMany(Srv->GetServerName(),"NICK",params);
4061
4062                         // User is Local, change needs to be reflected!
4063                         TreeServer* SourceServer = FindServer(user->server);
4064                         if (SourceServer)
4065                         {
4066                                 SourceServer->AddUserCount();
4067                         }
4068
4069                 }
4070         }
4071
4072         virtual void OnUserQuit(userrec* user, const std::string &reason)
4073         {
4074                 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
4075                 {
4076                         std::deque<std::string> params;
4077                         params.push_back(":"+reason);
4078                         DoOneToMany(user->nick,"QUIT",params);
4079                 }
4080                 // Regardless, We need to modify the user Counts..
4081                 TreeServer* SourceServer = FindServer(user->server);
4082                 if (SourceServer)
4083                 {
4084                         SourceServer->DelUserCount();
4085                 }
4086
4087         }
4088
4089         virtual void OnUserPostNick(userrec* user, const std::string &oldnick)
4090         {
4091                 if (IS_LOCAL(user))
4092                 {
4093                         std::deque<std::string> params;
4094                         params.push_back(user->nick);
4095                         DoOneToMany(oldnick,"NICK",params);
4096                 }
4097         }
4098
4099         virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, const std::string &reason)
4100         {
4101                 if ((source) && (IS_LOCAL(source)))
4102                 {
4103                         std::deque<std::string> params;
4104                         params.push_back(chan->name);
4105                         params.push_back(user->nick);
4106                         params.push_back(":"+reason);
4107                         DoOneToMany(source->nick,"KICK",params);
4108                 }
4109                 else if (!source)
4110                 {
4111                         std::deque<std::string> params;
4112                         params.push_back(chan->name);
4113                         params.push_back(user->nick);
4114                         params.push_back(":"+reason);
4115                         DoOneToMany(Srv->GetServerName(),"KICK",params);
4116                 }
4117         }
4118
4119         virtual void OnRemoteKill(userrec* source, userrec* dest, const std::string &reason)
4120         {
4121                 std::deque<std::string> params;
4122                 params.push_back(dest->nick);
4123                 params.push_back(":"+reason);
4124                 DoOneToMany(source->nick,"KILL",params);
4125         }
4126
4127         virtual void OnRehash(const std::string &parameter)
4128         {
4129                 if (parameter != "")
4130                 {
4131                         std::deque<std::string> params;
4132                         params.push_back(parameter);
4133                         DoOneToMany(Srv->GetServerName(),"REHASH",params);
4134                         // check for self
4135                         if (Srv->MatchText(Srv->GetServerName(),parameter))
4136                         {
4137                                 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
4138                                 Srv->RehashServer();
4139                         }
4140                 }
4141                 ReadConfiguration(false);
4142         }
4143
4144         // note: the protocol does not allow direct umode +o except
4145         // via NICK with 8 params. sending OPERTYPE infers +o modechange
4146         // locally.
4147         virtual void OnOper(userrec* user, const std::string &opertype)
4148         {
4149                 if (IS_LOCAL(user))
4150                 {
4151                         std::deque<std::string> params;
4152                         params.push_back(opertype);
4153                         DoOneToMany(user->nick,"OPERTYPE",params);
4154                 }
4155         }
4156
4157         void OnLine(userrec* source, const std::string &host, bool adding, char linetype, long duration, const std::string &reason)
4158         {
4159                 if (IS_LOCAL(source))
4160                 {
4161                         char type[8];
4162                         snprintf(type,8,"%cLINE",linetype);
4163                         std::string stype = type;
4164                         if (adding)
4165                         {
4166                                 char sduration[MAXBUF];
4167                                 snprintf(sduration,MAXBUF,"%ld",duration);
4168                                 std::deque<std::string> params;
4169                                 params.push_back(host);
4170                                 params.push_back(sduration);
4171                                 params.push_back(":"+reason);
4172                                 DoOneToMany(source->nick,stype,params);
4173                         }
4174                         else
4175                         {
4176                                 std::deque<std::string> params;
4177                                 params.push_back(host);
4178                                 DoOneToMany(source->nick,stype,params);
4179                         }
4180                 }
4181         }
4182
4183         virtual void OnAddGLine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
4184         {
4185                 OnLine(source,hostmask,true,'G',duration,reason);
4186         }
4187         
4188         virtual void OnAddZLine(long duration, userrec* source, const std::string &reason, const std::string &ipmask)
4189         {
4190                 OnLine(source,ipmask,true,'Z',duration,reason);
4191         }
4192
4193         virtual void OnAddQLine(long duration, userrec* source, const std::string &reason, const std::string &nickmask)
4194         {
4195                 OnLine(source,nickmask,true,'Q',duration,reason);
4196         }
4197
4198         virtual void OnAddELine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
4199         {
4200                 OnLine(source,hostmask,true,'E',duration,reason);
4201         }
4202
4203         virtual void OnDelGLine(userrec* source, const std::string &hostmask)
4204         {
4205                 OnLine(source,hostmask,false,'G',0,"");
4206         }
4207
4208         virtual void OnDelZLine(userrec* source, const std::string &ipmask)
4209         {
4210                 OnLine(source,ipmask,false,'Z',0,"");
4211         }
4212
4213         virtual void OnDelQLine(userrec* source, const std::string &nickmask)
4214         {
4215                 OnLine(source,nickmask,false,'Q',0,"");
4216         }
4217
4218         virtual void OnDelELine(userrec* source, const std::string &hostmask)
4219         {
4220                 OnLine(source,hostmask,false,'E',0,"");
4221         }
4222
4223         virtual void OnMode(userrec* user, void* dest, int target_type, const std::string &text)
4224         {
4225                 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
4226                 {
4227                         if (target_type == TYPE_USER)
4228                         {
4229                                 userrec* u = (userrec*)dest;
4230                                 std::deque<std::string> params;
4231                                 params.push_back(u->nick);
4232                                 params.push_back(text);
4233                                 DoOneToMany(user->nick,"MODE",params);
4234                         }
4235                         else
4236                         {
4237                                 chanrec* c = (chanrec*)dest;
4238                                 std::deque<std::string> params;
4239                                 params.push_back(c->name);
4240                                 params.push_back(text);
4241                                 DoOneToMany(user->nick,"MODE",params);
4242                         }
4243                 }
4244         }
4245
4246         virtual void OnSetAway(userrec* user)
4247         {
4248                 if (IS_LOCAL(user))
4249                 {
4250                         std::deque<std::string> params;
4251                         params.push_back(":"+std::string(user->awaymsg));
4252                         DoOneToMany(user->nick,"AWAY",params);
4253                 }
4254         }
4255
4256         virtual void OnCancelAway(userrec* user)
4257         {
4258                 if (IS_LOCAL(user))
4259                 {
4260                         std::deque<std::string> params;
4261                         params.clear();
4262                         DoOneToMany(user->nick,"AWAY",params);
4263                 }
4264         }
4265
4266         virtual void ProtoSendMode(void* opaque, int target_type, void* target, const std::string &modeline)
4267         {
4268                 TreeSocket* s = (TreeSocket*)opaque;
4269                 if (target)
4270                 {
4271                         if (target_type == TYPE_USER)
4272                         {
4273                                 userrec* u = (userrec*)target;
4274                                 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+ConvToStr(u->age)+" "+modeline);
4275                         }
4276                         else
4277                         {
4278                                 chanrec* c = (chanrec*)target;
4279                                 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" "+modeline);
4280                         }
4281                 }
4282         }
4283
4284         virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, const std::string &extname, const std::string &extdata)
4285         {
4286                 TreeSocket* s = (TreeSocket*)opaque;
4287                 if (target)
4288                 {
4289                         if (target_type == TYPE_USER)
4290                         {
4291                                 userrec* u = (userrec*)target;
4292                                 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+u->nick+" "+extname+" :"+extdata);
4293                         }
4294                         else if (target_type == TYPE_OTHER)
4295                         {
4296                                 s->WriteLine(":"+Srv->GetServerName()+" METADATA * "+extname+" :"+extdata);
4297                         }
4298                         else if (target_type == TYPE_CHANNEL)
4299                         {
4300                                 chanrec* c = (chanrec*)target;
4301                                 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+c->name+" "+extname+" :"+extdata);
4302                         }
4303                 }
4304         }
4305
4306         virtual void OnEvent(Event* event)
4307         {
4308                 if (event->GetEventID() == "send_metadata")
4309                 {
4310                         std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
4311                         if (params->size() < 3)
4312                                 return;
4313                         (*params)[2] = ":" + (*params)[2];
4314                         DoOneToMany(Srv->GetServerName(),"METADATA",*params);
4315                 }
4316                 else if (event->GetEventID() == "send_mode")
4317                 {
4318                         std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
4319                         if (params->size() < 2)
4320                                 return;
4321                         // Insert the TS value of the object, either userrec or chanrec
4322                         time_t ourTS = 0;
4323                         userrec* a = Srv->FindNick((*params)[0]);
4324                         if (a)
4325                         {
4326                                 ourTS = a->age;
4327                         }
4328                         else
4329                         {
4330                                 chanrec* a = Srv->FindChannel((*params)[0]);
4331                                 if (a)
4332                                 {
4333                                         ourTS = a->age;
4334                                 }
4335                         }
4336                         params->insert(params->begin() + 1,ConvToStr(ourTS));
4337                         DoOneToMany(Srv->GetServerName(),"FMODE",*params);
4338                 }
4339         }
4340
4341         virtual ~ModuleSpanningTree()
4342         {
4343         }
4344
4345         virtual Version GetVersion()
4346         {
4347                 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
4348         }
4349
4350         void Implements(char* List)
4351         {
4352                 List[I_OnPreCommand] = List[I_OnGetServerDescription] = List[I_OnUserInvite] = List[I_OnPostLocalTopicChange] = 1;
4353                 List[I_OnWallops] = List[I_OnUserNotice] = List[I_OnUserMessage] = List[I_OnBackgroundTimer] = 1;
4354                 List[I_OnUserJoin] = List[I_OnChangeHost] = List[I_OnChangeName] = List[I_OnUserPart] = List[I_OnUserConnect] = 1;
4355                 List[I_OnUserQuit] = List[I_OnUserPostNick] = List[I_OnUserKick] = List[I_OnRemoteKill] = List[I_OnRehash] = 1;
4356                 List[I_OnOper] = List[I_OnAddGLine] = List[I_OnAddZLine] = List[I_OnAddQLine] = List[I_OnAddELine] = 1;
4357                 List[I_OnDelGLine] = List[I_OnDelZLine] = List[I_OnDelQLine] = List[I_OnDelELine] = List[I_ProtoSendMode] = List[I_OnMode] = 1;
4358                 List[I_OnStats] = List[I_ProtoSendMetaData] = List[I_OnEvent] = List[I_OnSetAway] = List[I_OnCancelAway] = 1;
4359         }
4360
4361         /* It is IMPORTANT that m_spanningtree is the last module in the chain
4362          * so that any activity it sees is FINAL, e.g. we arent going to send out
4363          * a NICK message before m_cloaking has finished putting the +x on the user,
4364          * etc etc.
4365          * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
4366          * the module call queue.
4367          */
4368         Priority Prioritize()
4369         {
4370                 return PRIORITY_LAST;
4371         }
4372 };
4373
4374
4375 class ModuleSpanningTreeFactory : public ModuleFactory
4376 {
4377  public:
4378         ModuleSpanningTreeFactory()
4379         {
4380         }
4381         
4382         ~ModuleSpanningTreeFactory()
4383         {
4384         }
4385         
4386         virtual Module * CreateModule(Server* Me)
4387         {
4388                 TreeProtocolModule = new ModuleSpanningTree(Me);
4389                 return TreeProtocolModule;
4390         }
4391         
4392 };
4393
4394
4395 extern "C" void * init_module( void )
4396 {
4397         return new ModuleSpanningTreeFactory;
4398 }