]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/main.cpp
Fixed an issue that could cause empty parameters in module commands to not be sent...
[user/henk/code/inspircd.git] / src / modules / m_spanningtree / main.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2007 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *          the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 /* $ModDesc: Provides a spanning tree server link protocol */
15
16 #include "inspircd.h"
17 #include "commands/cmd_whois.h"
18 #include "commands/cmd_stats.h"
19 #include "socket.h"
20 #include "wildcard.h"
21 #include "xline.h"
22 #include "transport.h"
23
24 #include "m_spanningtree/timesynctimer.h"
25 #include "m_spanningtree/resolvers.h"
26 #include "m_spanningtree/main.h"
27 #include "m_spanningtree/utils.h"
28 #include "m_spanningtree/treeserver.h"
29 #include "m_spanningtree/link.h"
30 #include "m_spanningtree/treesocket.h"
31 #include "m_spanningtree/rconnect.h"
32 #include "m_spanningtree/rsquit.h"
33
34 /* $ModDep: m_spanningtree/timesynctimer.h m_spanningtree/resolvers.h m_spanningtree/main.h m_spanningtree/utils.h m_spanningtree/treeserver.h m_spanningtree/link.h m_spanningtree/treesocket.h m_spanningtree/rconnect.h m_spanningtree/rsquit.h */
35
36 ModuleSpanningTree::ModuleSpanningTree(InspIRCd* Me)
37         : Module(Me), max_local(0), max_global(0)
38 {
39         ServerInstance->Modules->UseInterface("InspSocketHook");
40         Utils = new SpanningTreeUtilities(Me, this);
41         command_rconnect = new cmd_rconnect(ServerInstance, this, Utils);
42         ServerInstance->AddCommand(command_rconnect);
43         command_rsquit = new cmd_rsquit(ServerInstance, this, Utils);
44         ServerInstance->AddCommand(command_rsquit);
45         if (Utils->EnableTimeSync)
46         {
47                 SyncTimer = new TimeSyncTimer(ServerInstance, this);
48                 ServerInstance->Timers->AddTimer(SyncTimer);
49         }
50         else
51                 SyncTimer = NULL;
52
53         RefreshTimer = new CacheRefreshTimer(ServerInstance, Utils);
54         ServerInstance->Timers->AddTimer(RefreshTimer);
55 }
56
57 void ModuleSpanningTree::ShowLinks(TreeServer* Current, userrec* user, int hops)
58 {
59         std::string Parent = Utils->TreeRoot->GetName();
60         if (Current->GetParent())
61         {
62                 Parent = Current->GetParent()->GetName();
63         }
64         for (unsigned int q = 0; q < Current->ChildCount(); q++)
65         {
66                 if ((Current->GetChild(q)->Hidden) || ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str()))))
67                 {
68                         if (*user->oper)
69                         {
70                                  ShowLinks(Current->GetChild(q),user,hops+1);
71                         }
72                 }
73                 else
74                 {
75                         ShowLinks(Current->GetChild(q),user,hops+1);
76                 }
77         }
78         /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
79         if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetName().c_str())) && (!IS_OPER(user)))
80                 return;
81         /* Or if the server is hidden and they're not an oper */
82         else if ((Current->Hidden) && (!IS_OPER(user)))
83                 return;
84
85         user->WriteServ("364 %s %s %s :%d %s",  user->nick,Current->GetName().c_str(),
86                         (Utils->FlatLinks && (!IS_OPER(user))) ? ServerInstance->Config->ServerName : Parent.c_str(),
87                         (Utils->FlatLinks && (!IS_OPER(user))) ? 0 : hops,
88                         Current->GetDesc().c_str());
89 }
90
91 int ModuleSpanningTree::CountLocalServs()
92 {
93         return Utils->TreeRoot->ChildCount();
94 }
95
96 int ModuleSpanningTree::CountServs()
97 {
98         return Utils->serverlist.size();
99 }
100
101 void ModuleSpanningTree::HandleLinks(const char** parameters, int pcnt, userrec* user)
102 {
103         ShowLinks(Utils->TreeRoot,user,0);
104         user->WriteServ("365 %s * :End of /LINKS list.",user->nick);
105         return;
106 }
107
108 void ModuleSpanningTree::HandleLusers(const char** parameters, int pcnt, userrec* user)
109 {
110         unsigned int n_users = ServerInstance->UserCount();
111
112         /* Only update these when someone wants to see them, more efficient */
113         if ((unsigned int)ServerInstance->LocalUserCount() > max_local)
114                 max_local = ServerInstance->LocalUserCount();
115         if (n_users > max_global)
116                 max_global = n_users;
117
118         unsigned int ulined_count = 0;
119         unsigned int ulined_local_count = 0;
120
121         /* If ulined are hidden and we're not an oper, count the number of ulined servers hidden,
122          * locally and globally (locally means directly connected to us)
123          */
124         if ((Utils->HideULines) && (!*user->oper))
125         {
126                 for (server_hash::iterator q = Utils->serverlist.begin(); q != Utils->serverlist.end(); q++)
127                 {
128                         if (ServerInstance->ULine(q->second->GetName().c_str()))
129                         {
130                                 ulined_count++;
131                                 if (q->second->GetParent() == Utils->TreeRoot)
132                                         ulined_local_count++;
133                         }
134                 }
135         }
136         user->WriteServ("251 %s :There are %d users and %d invisible on %d servers",user->nick,
137                         n_users-ServerInstance->InvisibleUserCount(),
138                         ServerInstance->InvisibleUserCount(),
139                         ulined_count ? this->CountServs() - ulined_count : this->CountServs());
140
141         if (ServerInstance->OperCount())
142                 user->WriteServ("252 %s %d :operator(s) online",user->nick,ServerInstance->OperCount());
143
144         if (ServerInstance->UnregisteredUserCount())
145                 user->WriteServ("253 %s %d :unknown connections",user->nick,ServerInstance->UnregisteredUserCount());
146         
147         if (ServerInstance->ChannelCount())
148                 user->WriteServ("254 %s %d :channels formed",user->nick,ServerInstance->ChannelCount());
149         
150         user->WriteServ("255 %s :I have %d clients and %d servers",user->nick,ServerInstance->LocalUserCount(),ulined_local_count ? this->CountLocalServs() - ulined_local_count : this->CountLocalServs());
151         user->WriteServ("265 %s :Current Local Users: %d  Max: %d",user->nick,ServerInstance->LocalUserCount(),max_local);
152         user->WriteServ("266 %s :Current Global Users: %d  Max: %d",user->nick,n_users,max_global);
153         return;
154 }
155
156 std::string ModuleSpanningTree::TimeToStr(time_t secs)
157 {
158         time_t mins_up = secs / 60;
159         time_t hours_up = mins_up / 60;
160         time_t days_up = hours_up / 24;
161         secs = secs % 60;
162         mins_up = mins_up % 60;
163         hours_up = hours_up % 24;
164         return ((days_up ? (ConvToStr(days_up) + "d") : std::string(""))
165                         + (hours_up ? (ConvToStr(hours_up) + "h") : std::string(""))
166                         + (mins_up ? (ConvToStr(mins_up) + "m") : std::string(""))
167                         + ConvToStr(secs) + "s");
168 }
169
170 const std::string ModuleSpanningTree::MapOperInfo(TreeServer* Current)
171 {
172         time_t secs_up = ServerInstance->Time() - Current->age;
173         return (" [Up: " + TimeToStr(secs_up) + " Lag: "+ConvToStr(Current->rtt)+"ms]");
174 }
175
176 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
177 void ModuleSpanningTree::ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][128], float &totusers, float &totservers)
178 {
179         if (line < 128)
180         {
181                 for (int t = 0; t < depth; t++)
182                 {
183                         matrix[line][t] = ' ';
184                 }
185                 // For Aligning, we need to work out exactly how deep this thing is, and produce
186                 // a 'Spacer' String to compensate.
187                 char spacer[40];
188                 memset(spacer,' ',40);
189                 if ((40 - Current->GetName().length() - depth) > 1) {
190                         spacer[40 - Current->GetName().length() - depth] = '\0';
191                 }
192                 else
193                 {
194                         spacer[5] = '\0';
195                 }
196                 float percent;
197                 char text[128];
198                 /* Neat and tidy default values, as we're dealing with a matrix not a simple string */
199                 memset(text, 0, 128);
200
201                 if (ServerInstance->clientlist->size() == 0) {
202                         // If there are no users, WHO THE HELL DID THE /MAP?!?!?!
203                         percent = 0;
204                 }
205                 else
206                 {
207                         percent = ((float)Current->GetUserCount() / (float)ServerInstance->clientlist->size()) * 100;
208                 }
209                 const std::string operdata = IS_OPER(user) ? MapOperInfo(Current) : "";
210                 snprintf(text, 126, "%s %s%5d [%5.2f%%]%s", Current->GetName().c_str(), spacer, Current->GetUserCount(), percent, operdata.c_str());
211                 totusers += Current->GetUserCount();
212                 totservers++;
213                 strlcpy(&matrix[line][depth],text,126);
214                 line++;
215                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
216                 {
217                         if ((Current->GetChild(q)->Hidden) || ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str()))))
218                         {
219                                 if (*user->oper)
220                                 {
221                                         ShowMap(Current->GetChild(q),user,(Utils->FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
222                                 }
223                         }
224                         else
225                         {
226                                 ShowMap(Current->GetChild(q),user,(Utils->FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
227                         }
228                 }
229         }
230 }
231
232 int ModuleSpanningTree::HandleMotd(const char** parameters, int pcnt, userrec* user)
233 {
234         if (pcnt > 0)
235         {
236                 if (match(ServerInstance->Config->ServerName, parameters[0]))
237                         return 0;
238
239                 /* Remote MOTD, the server is within the 1st parameter */
240                 std::deque<std::string> params;
241                 params.push_back(parameters[0]);
242                 /* Send it out remotely, generate no reply yet */
243                 TreeServer* s = Utils->FindServerMask(parameters[0]);
244                 if (s)
245                 {
246                         params[0] = s->GetName();
247                         Utils->DoOneToOne(user->uuid, "MOTD", params, s->GetName());
248                 }
249                 else
250                         user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
251                 return 1;
252         }
253         return 0;
254 }
255
256 int ModuleSpanningTree::HandleAdmin(const char** parameters, int pcnt, userrec* user)
257 {
258         if (pcnt > 0)
259         {
260                 if (match(ServerInstance->Config->ServerName, parameters[0]))
261                         return 0;
262
263                 /* Remote ADMIN, the server is within the 1st parameter */
264                 std::deque<std::string> params;
265                 params.push_back(parameters[0]);
266                 /* Send it out remotely, generate no reply yet */
267                 TreeServer* s = Utils->FindServerMask(parameters[0]);
268                 if (s)
269                 {
270                         params[0] = s->GetName();
271                         Utils->DoOneToOne(user->uuid, "ADMIN", params, s->GetName());
272                 }
273                 else
274                         user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
275                 return 1;
276         }
277         return 0;
278 }
279
280 int ModuleSpanningTree::HandleModules(const char** parameters, int pcnt, userrec* user)
281 {
282         if (pcnt > 0)
283         {
284                 if (match(ServerInstance->Config->ServerName, parameters[0]))
285                         return 0;
286
287                 std::deque<std::string> params;
288                 params.push_back(parameters[0]);
289                 TreeServer* s = Utils->FindServerMask(parameters[0]);
290                 if (s)
291                 {
292                         params[0] = s->GetName();
293                         Utils->DoOneToOne(user->uuid, "MODULES", params, s->GetName());
294                 }
295                 else
296                         user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
297                 return 1;
298         }
299         return 0;
300 }
301
302 int ModuleSpanningTree::HandleStats(const char** parameters, int pcnt, userrec* user)
303 {
304         if (pcnt > 1)
305         {
306                 if (match(ServerInstance->Config->ServerName, parameters[1]))
307                         return 0;
308
309                 /* Remote STATS, the server is within the 2nd parameter */
310                 std::deque<std::string> params;
311                 params.push_back(parameters[0]);
312                 params.push_back(parameters[1]);
313                 /* Send it out remotely, generate no reply yet */
314
315                 TreeServer* s = Utils->FindServerMask(parameters[1]);
316                 if (s)
317                 {
318                         params[1] = s->GetName();
319                         Utils->DoOneToOne(user->uuid, "STATS", params, s->GetName());
320                 }
321                 else
322                 {
323                         user->WriteServ( "402 %s %s :No such server", user->nick, parameters[1]);
324                 }
325                 return 1;
326         }
327         return 0;
328 }
329
330 // Ok, prepare to be confused.
331 // After much mulling over how to approach this, it struck me that
332 // the 'usual' way of doing a /MAP isnt the best way. Instead of
333 // keeping track of a ton of ascii characters, and line by line
334 // under recursion working out where to place them using multiplications
335 // and divisons, we instead render the map onto a backplane of characters
336 // (a character matrix), then draw the branches as a series of "L" shapes
337 // from the nodes. This is not only friendlier on CPU it uses less stack.
338 void ModuleSpanningTree::HandleMap(const char** parameters, int pcnt, userrec* user)
339 {
340         // This array represents a virtual screen which we will
341         // "scratch" draw to, as the console device of an irc
342         // client does not provide for a proper terminal.
343         float totusers = 0;
344         float totservers = 0;
345         char matrix[128][128];
346         for (unsigned int t = 0; t < 128; t++)
347         {
348                 matrix[t][0] = '\0';
349         }
350         line = 0;
351         // The only recursive bit is called here.
352         ShowMap(Utils->TreeRoot,user,0,matrix,totusers,totservers);
353         // Process each line one by one. The algorithm has a limit of
354         // 128 servers (which is far more than a spanning tree should have
355         // anyway, so we're ok). This limit can be raised simply by making
356         // the character matrix deeper, 128 rows taking 10k of memory.
357         for (int l = 1; l < line; l++)
358         {
359                 // scan across the line looking for the start of the
360                 // servername (the recursive part of the algorithm has placed
361                 // the servers at indented positions depending on what they
362                 // are related to)
363                 int first_nonspace = 0;
364                 while (matrix[l][first_nonspace] == ' ')
365                 {
366                         first_nonspace++;
367                 }
368                 first_nonspace--;
369                 // Draw the `- (corner) section: this may be overwritten by
370                 // another L shape passing along the same vertical pane, becoming
371                 // a |- (branch) section instead.
372                 matrix[l][first_nonspace] = '-';
373                 matrix[l][first_nonspace-1] = '`';
374                 int l2 = l - 1;
375                 // Draw upwards until we hit the parent server, causing possibly
376                 // other corners (`-) to become branches (|-)
377                 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
378                 {
379                         matrix[l2][first_nonspace-1] = '|';
380                         l2--;
381                 }
382         }
383         // dump the whole lot to the user. This is the easy bit, honest.
384         for (int t = 0; t < line; t++)
385         {
386                 user->WriteServ("006 %s :%s",user->nick,&matrix[t][0]);
387         }
388         float avg_users = totusers / totservers;
389         user->WriteServ("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);
390         user->WriteServ("007 %s :End of /MAP",user->nick);
391         return;
392 }
393
394 int ModuleSpanningTree::HandleSquit(const char** parameters, int pcnt, userrec* user)
395 {
396         TreeServer* s = Utils->FindServerMask(parameters[0]);
397         if (s)
398         {
399                 if (s == Utils->TreeRoot)
400                 {
401                         user->WriteServ("NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
402                         return 1;
403                 }
404                 TreeSocket* sock = s->GetSocket();
405                 if (sock)
406                 {
407                         ServerInstance->SNO->WriteToSnoMask('l',"SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
408                         sock->Squit(s,std::string("Server quit by ") + user->GetFullRealHost());
409                         ServerInstance->SE->DelFd(sock);
410                         sock->Close();
411                 }
412                 else
413                 {
414                         if (IS_LOCAL(user))
415                                 user->WriteServ("NOTICE %s :*** WARNING: Using SQUIT to split remote servers is deprecated. Please use RSQUIT instead.",user->nick);
416                 }
417         }
418         else
419         {
420                  user->WriteServ("NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
421         }
422         return 1;
423 }
424
425 int ModuleSpanningTree::HandleTime(const char** parameters, int pcnt, userrec* user)
426 {
427         if ((IS_LOCAL(user)) && (pcnt))
428         {
429                 TreeServer* found = Utils->FindServerMask(parameters[0]);
430                 if (found)
431                 {
432                         // we dont' override for local server
433                         if (found == Utils->TreeRoot)
434                                 return 0;
435                         
436                         std::deque<std::string> params;
437                         params.push_back(found->GetName());
438                         params.push_back(user->uuid);
439                         Utils->DoOneToOne(ServerInstance->Config->GetSID(),"TIME",params,found->GetName());
440                 }
441                 else
442                 {
443                         user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
444                 }
445         }
446         return 1;
447 }
448
449 int ModuleSpanningTree::HandleRemoteWhois(const char** parameters, int pcnt, userrec* user)
450 {
451         if ((IS_LOCAL(user)) && (pcnt > 1))
452         {
453                 userrec* remote = ServerInstance->FindNick(parameters[1]);
454                 if ((remote) && (remote->GetFd() < 0))
455                 {
456                         std::deque<std::string> params;
457                         params.push_back(parameters[1]);
458                         Utils->DoOneToOne(user->uuid,"IDLE",params,remote->server);
459                         return 1;
460                 }
461                 else if (!remote)
462                 {
463                         user->WriteServ("401 %s %s :No such nick/channel",user->nick, parameters[1]);
464                         user->WriteServ("318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
465                         return 1;
466                 }
467         }
468         return 0;
469 }
470
471 void ModuleSpanningTree::DoPingChecks(time_t curtime)
472 {
473         for (unsigned int j = 0; j < Utils->TreeRoot->ChildCount(); j++)
474         {
475                 TreeServer* serv = Utils->TreeRoot->GetChild(j);
476                 TreeSocket* sock = serv->GetSocket();
477                 if (sock)
478                 {
479                         if (curtime >= serv->NextPingTime())
480                         {
481                                 if (serv->AnsweredLastPing())
482                                 {
483                                         sock->WriteLine(std::string(":")+ServerInstance->Config->GetSID()+" PING "+serv->GetName());
484                                         serv->SetNextPingTime(curtime + Utils->PingFreq);
485                                         serv->LastPing = curtime;
486                                         timeval t;
487                                         gettimeofday(&t, NULL);
488                                         long ts = (t.tv_sec * 1000) + (t.tv_usec / 1000);
489                                         serv->LastPingMsec = ts;
490                                         serv->Warned = false;
491                                 }
492                                 else
493                                 {
494                                         /* they didnt answer, boot them */
495                                         sock->SendError("Ping timeout");
496                                         sock->Squit(serv,"Ping timeout");
497                                         ServerInstance->SE->DelFd(sock);
498                                         sock->Close();
499                                         return;
500                                 }
501                         }
502                         else if ((Utils->PingWarnTime) && (!serv->Warned) && (curtime >= serv->NextPingTime() - (Utils->PingFreq - Utils->PingWarnTime)) && (!serv->AnsweredLastPing()))
503                         {
504                                 /* The server hasnt responded, send a warning to opers */
505                                 ServerInstance->SNO->WriteToSnoMask('l',"Server \002%s\002 has not responded to PING for %d seconds, high latency.", serv->GetName().c_str(), Utils->PingWarnTime);
506                                 serv->Warned = true;
507                         }
508                 }
509         }
510
511         /* Cancel remote burst mode on any servers which still have it enabled due to latency/lack of data.
512          * This prevents lost REMOTECONNECT notices
513          */
514         for (server_hash::iterator i = Utils->serverlist.begin(); i != Utils->serverlist.end(); i++)
515                 Utils->SetRemoteBursting(i->second, false);
516 }
517
518 void ModuleSpanningTree::ConnectServer(Link* x)
519 {
520         bool ipvalid = true;
521         QueryType start_type = DNS_QUERY_A;
522 #ifdef IPV6
523         start_type = DNS_QUERY_AAAA;
524         if (strchr(x->IPAddr.c_str(),':'))
525         {
526                 in6_addr n;
527                 if (inet_pton(AF_INET6, x->IPAddr.c_str(), &n) < 1)
528                         ipvalid = false;
529         }
530         else
531 #endif
532         {
533                 in_addr n;
534                 if (inet_aton(x->IPAddr.c_str(),&n) < 1)
535                         ipvalid = false;
536         }
537
538         /* Do we already have an IP? If so, no need to resolve it. */
539         if (ipvalid)
540         {
541                 /* Gave a hook, but it wasnt one we know */
542                 if ((!x->Hook.empty()) && (Utils->hooks.find(x->Hook.c_str()) == Utils->hooks.end()))
543                         return;
544                 TreeSocket* newsocket = new TreeSocket(Utils, ServerInstance, x->IPAddr,x->Port,false,x->Timeout ? x->Timeout : 10,x->Name.c_str(), x->Bind, x->Hook.empty() ? NULL : Utils->hooks[x->Hook.c_str()]);
545                 if (newsocket->GetFd() > -1)
546                 {
547                         /* Handled automatically on success */
548                 }
549                 else
550                 {
551                         RemoteMessage(NULL, "CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
552                         if (ServerInstance->SocketCull.find(newsocket) == ServerInstance->SocketCull.end())
553                                 ServerInstance->SocketCull[newsocket] = newsocket;
554                         Utils->DoFailOver(x);
555                 }
556         }
557         else
558         {
559                 try
560                 {
561                         bool cached;
562                         ServernameResolver* snr = new ServernameResolver((Module*)this, Utils, ServerInstance,x->IPAddr, *x, cached, start_type);
563                         ServerInstance->AddResolver(snr, cached);
564                 }
565                 catch (ModuleException& e)
566                 {
567                         RemoteMessage(NULL, "CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(), e.GetReason());
568                         Utils->DoFailOver(x);
569                 }
570         }
571 }
572
573 void ModuleSpanningTree::AutoConnectServers(time_t curtime)
574 {
575         for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
576         {
577                 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
578                 {
579                         x->NextConnectTime = curtime + x->AutoConnect;
580                         TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
581                         if (x->FailOver.length())
582                         {
583                                 TreeServer* CheckFailOver = Utils->FindServer(x->FailOver.c_str());
584                                 if (CheckFailOver)
585                                 {
586                                         /* The failover for this server is currently a member of the network.
587                                          * The failover probably succeeded, where the main link did not.
588                                          * Don't try the main link until the failover is gone again.
589                                          */
590                                         continue;
591                                 }
592                         }
593                         if (!CheckDupe)
594                         {
595                                 // an autoconnected server is not connected. Check if its time to connect it
596                                 ServerInstance->SNO->WriteToSnoMask('l',"AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
597                                 this->ConnectServer(&(*x));
598                         }
599                 }
600         }
601 }
602
603 int ModuleSpanningTree::HandleVersion(const char** parameters, int pcnt, userrec* user)
604 {
605         // we've already checked if pcnt > 0, so this is safe
606         TreeServer* found = Utils->FindServerMask(parameters[0]);
607         if (found)
608         {
609                 std::string Version = found->GetVersion();
610                 user->WriteServ("351 %s :%s",user->nick,Version.c_str());
611                 if (found == Utils->TreeRoot)
612                 {
613                         ServerInstance->Config->Send005(user);
614                 }
615         }
616         else
617         {
618                 user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
619         }
620         return 1;
621 }
622
623 /* This method will attempt to get a link message out to as many people as is required.
624  * If a user is provided, and that user is local, then the user is sent the message using
625  * WriteServ (they are the local initiator of that message). If the user is remote, they are
626  * sent that message remotely via PUSH.
627  * If the user is NULL, then the notice is sent locally via WriteToSnoMask with snomask 'l',
628  * and remotely via SNONOTICE with mask 'l'.
629  */
630 void ModuleSpanningTree::RemoteMessage(userrec* user, const char* format, ...)
631 {
632         /* This could cause an infinite loop, because DoOneToMany() will, on error,
633          * call TreeSocket::OnError(), which in turn will call this function to
634          * notify everyone of the error. So, drop any messages that are generated
635          * during the sending of another message. -Special */
636         static bool SendingRemoteMessage = false;
637         if (SendingRemoteMessage)
638                 return;
639         SendingRemoteMessage = true;
640
641         std::deque<std::string> params;
642         char text[MAXBUF];
643         va_list argsPtr;
644
645         va_start(argsPtr, format);
646         vsnprintf(text, MAXBUF, format, argsPtr);
647         va_end(argsPtr);
648
649         if (!user)
650         {
651                 /* No user, target it generically at everyone */
652                 ServerInstance->SNO->WriteToSnoMask('l', "%s", text);
653                 params.push_back("l");
654                 params.push_back(std::string(":") + text);
655                 Utils->DoOneToMany(ServerInstance->Config->GetSID(), "SNONOTICE", params);
656         }
657         else
658         {
659                 if (IS_LOCAL(user))
660                         user->WriteServ("NOTICE %s :%s", user->nick, text);
661                 else
662                 {
663                         params.push_back(user->uuid);
664                         params.push_back(std::string("::") + ServerInstance->Config->ServerName + " NOTICE " + user->nick + " :*** From " +
665                                         ServerInstance->Config->ServerName+ ": " + text);
666                         Utils->DoOneToMany(ServerInstance->Config->GetSID(), "PUSH", params);
667                 }
668         }
669         
670         SendingRemoteMessage = false;
671 }
672         
673 int ModuleSpanningTree::HandleConnect(const char** parameters, int pcnt, userrec* user)
674 {
675         for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
676         {
677                 if (ServerInstance->MatchText(x->Name.c_str(),parameters[0]))
678                 {
679                         TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
680                         if (!CheckDupe)
681                         {
682                                 RemoteMessage(user, "*** CONNECT: Connecting to server: \002%s\002 (%s:%d)",user->nick,x->Name.c_str(),(x->HiddenFromStats ? "<hidden>" : x->IPAddr.c_str()),x->Port);
683                                 ConnectServer(&(*x));
684                                 return 1;
685                         }
686                         else
687                         {
688                                 RemoteMessage(user, "*** 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());
689                                 return 1;
690                         }
691                 }
692         }
693         RemoteMessage(user, "NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
694         return 1;
695 }
696
697 void ModuleSpanningTree::BroadcastTimeSync()
698 {
699         if (Utils->MasterTime)
700         {
701                 std::deque<std::string> params;
702                 params.push_back(ConvToStr(ServerInstance->Time(false)));
703                 params.push_back("FORCE");
704                 Utils->DoOneToMany(ServerInstance->Config->GetSID(), "TIMESET", params);
705         }
706 }
707
708 int ModuleSpanningTree::OnStats(char statschar, userrec* user, string_list &results)
709 {
710         if ((statschar == 'c') || (statschar == 'n'))
711         {
712                 for (unsigned int i = 0; i < Utils->LinkBlocks.size(); i++)
713                 {
714                         results.push_back(std::string(ServerInstance->Config->ServerName)+" 213 "+user->nick+" "+statschar+" *@"+(Utils->LinkBlocks[i].HiddenFromStats ? "<hidden>" : Utils->LinkBlocks[i].IPAddr)+" * "+Utils->LinkBlocks[i].Name.c_str()+" "+ConvToStr(Utils->LinkBlocks[i].Port)+" "+(Utils->LinkBlocks[i].Hook.empty() ? "plaintext" : Utils->LinkBlocks[i].Hook)+" "+(Utils->LinkBlocks[i].AutoConnect ? 'a' : '-')+'s');
715                         if (statschar == 'c')
716                                 results.push_back(std::string(ServerInstance->Config->ServerName)+" 244 "+user->nick+" H * * "+Utils->LinkBlocks[i].Name.c_str());
717                 }
718                 results.push_back(std::string(ServerInstance->Config->ServerName)+" 219 "+user->nick+" "+statschar+" :End of /STATS report");
719                 ServerInstance->SNO->WriteToSnoMask('t',"%s '%c' requested by %s (%s@%s)",(!strcmp(user->server,ServerInstance->Config->ServerName) ? "Stats" : "Remote stats"),statschar,user->nick,user->ident,user->host);
720                 return 1;
721         }
722
723         if (statschar == 'p')
724         {
725                 /* show all server ports, after showing client ports. -- w00t */
726
727                 for (unsigned int i = 0; i < Utils->Bindings.size(); i++)
728                 {
729                         std::string ip = Utils->Bindings[i]->IP;
730                         if (ip.empty())
731                                 ip = "*";
732
733                         std::string transport("plaintext");
734                         if (Utils->Bindings[i]->GetHook())
735                                 transport = InspSocketNameRequest(this, Utils->Bindings[i]->GetHook()).Send();
736
737                         results.push_back(ConvToStr(ServerInstance->Config->ServerName) + " 249 "+user->nick+" :" + ip + ":" + ConvToStr(Utils->Bindings[i]->port)+
738                                 " (server, " + transport + ")");
739                 }
740         }
741         return 0;
742 }
743
744 int ModuleSpanningTree::OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated, const std::string &original_line)
745 {
746         /* If the command doesnt appear to be valid, we dont want to mess with it. */
747         if (!validated)
748                 return 0;
749
750         if (command == "CONNECT")
751         {
752                 return this->HandleConnect(parameters,pcnt,user);
753         }
754         else if (command == "STATS")
755         {
756                 return this->HandleStats(parameters,pcnt,user);
757         }
758         else if (command == "MOTD")
759         {
760                 return this->HandleMotd(parameters,pcnt,user);
761         }
762         else if (command == "ADMIN")
763         {
764                 return this->HandleAdmin(parameters,pcnt,user);
765         }
766         else if (command == "SQUIT")
767         {
768                 return this->HandleSquit(parameters,pcnt,user);
769         }
770         else if (command == "MAP")
771         {
772                 this->HandleMap(parameters,pcnt,user);
773                 return 1;
774         }
775         else if ((command == "TIME") && (pcnt > 0))
776         {
777                 return this->HandleTime(parameters,pcnt,user);
778         }
779         else if (command == "LUSERS")
780         {
781                 this->HandleLusers(parameters,pcnt,user);
782                 return 1;
783         }
784         else if (command == "LINKS")
785         {
786                 this->HandleLinks(parameters,pcnt,user);
787                 return 1;
788         }
789         else if (command == "WHOIS")
790         {
791                 if (pcnt > 1)
792                 {
793                         // remote whois
794                         return this->HandleRemoteWhois(parameters,pcnt,user);
795                 }
796         }
797         else if ((command == "VERSION") && (pcnt > 0))
798         {
799                 this->HandleVersion(parameters,pcnt,user);
800                 return 1;
801         }
802         else if ((command == "MODULES") && (pcnt > 0))
803         {
804                 return this->HandleModules(parameters,pcnt,user);
805         }
806         return 0;
807 }
808
809 void ModuleSpanningTree::OnPostCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, CmdResult result, const std::string &original_line)
810 {
811         if ((result == CMD_SUCCESS) && (ServerInstance->IsValidModuleCommand(command, pcnt, user)))
812         {
813                 /* Safe, we know its non-null because IsValidModuleCommand returned true */
814                 command_t* thiscmd = ServerInstance->Parser->GetHandler(command);
815                 // this bit of code cleverly routes all module commands
816                 // to all remote severs *automatically* so that modules
817                 // can just handle commands locally, without having
818                 // to have any special provision in place for remote
819                 // commands and linking protocols.
820                 std::deque<std::string> params;
821                 params.clear();
822                 int n_translate = thiscmd->translation.size();
823                 TranslateType translate_to;
824
825                 /* To make sure that parameters with spaces, or empty
826                  * parameters, etc, are always sent properly, *always*
827                  * prefix the last parameter with a :. This also removes
828                  * an extra strchr() */
829                 for (int j = 0; j < pcnt; j++)
830                 {
831                         std::string target;
832
833                         /* Map all items to UUIDs where neccessary */
834                         if (j < n_translate)
835                         {
836                                 /* We have a translation mapping for this index */
837                                 translate_to = thiscmd->translation[j] != TR_END ? thiscmd->translation[j] : TR_TEXT;
838                         }
839                         else
840                                 translate_to = TR_TEXT;
841
842                         ServerInstance->Log(DEBUG,"TRANSLATION: %s - type is %d", parameters[j], translate_to);
843                         ServerInstance->Parser->TranslateUIDs(translate_to, parameters[j], target);
844                         
845                         if (j == (pcnt - 1))
846                                 params.push_back(":" + target);
847                         else
848                                 params.push_back(target);
849                 }
850                 Utils->DoOneToMany(user->uuid, command, params);
851         }
852 }
853
854 void ModuleSpanningTree::OnGetServerDescription(const std::string &servername,std::string &description)
855 {
856         TreeServer* s = Utils->FindServer(servername);
857         if (s)
858         {
859                 description = s->GetDesc();
860         }
861 }
862
863 void ModuleSpanningTree::OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
864 {
865         if (IS_LOCAL(source))
866         {
867                 std::deque<std::string> params;
868                 params.push_back(dest->uuid);
869                 params.push_back(channel->name);
870                 Utils->DoOneToMany(source->uuid,"INVITE",params);
871         }
872 }
873
874 void ModuleSpanningTree::OnPostLocalTopicChange(userrec* user, chanrec* chan, const std::string &topic)
875 {
876         std::deque<std::string> params;
877         params.push_back(chan->name);
878         params.push_back(":"+topic);
879         Utils->DoOneToMany(user->uuid,"TOPIC",params);
880 }
881
882 void ModuleSpanningTree::OnWallops(userrec* user, const std::string &text)
883 {
884         if (IS_LOCAL(user))
885         {
886                 std::deque<std::string> params;
887                 params.push_back(":"+text);
888                 Utils->DoOneToMany(user->uuid,"WALLOPS",params);
889         }
890 }
891
892 void ModuleSpanningTree::OnUserNotice(userrec* user, void* dest, int target_type, const std::string &text, char status, const CUList &exempt_list)
893 {
894         if (target_type == TYPE_USER)
895         {
896                 userrec* d = (userrec*)dest;
897                 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
898                 {
899                         std::deque<std::string> params;
900                         params.clear();
901                         params.push_back(d->uuid);
902                         params.push_back(":"+text);
903                         Utils->DoOneToOne(user->uuid,"NOTICE",params,d->server);
904                 }
905         }
906         else if (target_type == TYPE_CHANNEL)
907         {
908                 if (IS_LOCAL(user))
909                 {
910                         chanrec *c = (chanrec*)dest;
911                         if (c)
912                         {
913                                 std::string cname = c->name;
914                                 if (status)
915                                         cname = status + cname;
916                                 TreeServerList list;
917                                 Utils->GetListOfServersForChannel(c,list,status,exempt_list);
918                                 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
919                                 {
920                                         TreeSocket* Sock = i->second->GetSocket();
921                                         if (Sock)
922                                                 Sock->WriteLine(":"+std::string(user->uuid)+" NOTICE "+cname+" :"+text);
923                                 }
924                         }
925                 }
926         }
927         else if (target_type == TYPE_SERVER)
928         {
929                 if (IS_LOCAL(user))
930                 {
931                         char* target = (char*)dest;
932                         std::deque<std::string> par;
933                         par.push_back(target);
934                         par.push_back(":"+text);
935                         Utils->DoOneToMany(user->uuid,"NOTICE",par);
936                 }
937         }
938 }
939
940 void ModuleSpanningTree::OnUserMessage(userrec* user, void* dest, int target_type, const std::string &text, char status, const CUList &exempt_list)
941 {
942         if (target_type == TYPE_USER)
943         {
944                 // route private messages which are targetted at clients only to the server
945                 // which needs to receive them
946                 userrec* d = (userrec*)dest;
947                 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
948                 {
949                         std::deque<std::string> params;
950                         params.clear();
951                         params.push_back(d->uuid);
952                         params.push_back(":"+text);
953                         Utils->DoOneToOne(user->uuid,"PRIVMSG",params,d->server);
954                 }
955         }
956         else if (target_type == TYPE_CHANNEL)
957         {
958                 if (IS_LOCAL(user))
959                 {
960                         chanrec *c = (chanrec*)dest;
961                         if (c)
962                         {
963                                 std::string cname = c->name;
964                                 if (status)
965                                         cname = status + cname;
966                                 TreeServerList list;
967                                 Utils->GetListOfServersForChannel(c,list,status,exempt_list);
968                                 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
969                                 {
970                                         TreeSocket* Sock = i->second->GetSocket();
971                                         if (Sock)
972                                                 Sock->WriteLine(":"+std::string(user->uuid)+" PRIVMSG "+cname+" :"+text);
973                                 }
974                         }
975                 }
976         }
977         else if (target_type == TYPE_SERVER)
978         {
979                 if (IS_LOCAL(user))
980                 {
981                         char* target = (char*)dest;
982                         std::deque<std::string> par;
983                         par.push_back(target);
984                         par.push_back(":"+text);
985                         Utils->DoOneToMany(user->uuid,"PRIVMSG",par);
986                 }
987         }
988 }
989
990 void ModuleSpanningTree::OnBackgroundTimer(time_t curtime)
991 {
992         AutoConnectServers(curtime);
993         DoPingChecks(curtime);
994 }
995
996 void ModuleSpanningTree::OnUserJoin(userrec* user, chanrec* channel, bool &silent)
997 {
998         // Only do this for local users
999         if (IS_LOCAL(user))
1000         {
1001                 if (channel->GetUserCounter() == 1)
1002                 {
1003                         std::deque<std::string> params;
1004                         // set up their permissions and the channel TS with FJOIN.
1005                         // All users are FJOINed now, because a module may specify
1006                         // new joining permissions for the user.
1007                         params.push_back(channel->name);
1008                         params.push_back(ConvToStr(channel->age));
1009                         params.push_back(std::string(channel->GetAllPrefixChars(user))+","+std::string(user->uuid));
1010                         Utils->DoOneToMany(ServerInstance->Config->GetSID(),"FJOIN",params);
1011                         /* First user in, sync the modes for the channel */
1012                         params.pop_back();
1013                         params.push_back(channel->ChanModes(true));
1014                         Utils->DoOneToMany(ServerInstance->Config->GetSID(),"FMODE",params);
1015                 }
1016                 else
1017                 {
1018                         std::deque<std::string> params;
1019                         params.push_back(channel->name);
1020                         params.push_back(ConvToStr(channel->age));
1021                         Utils->DoOneToMany(user->uuid,"JOIN",params);
1022                 }
1023         }
1024 }
1025
1026 void ModuleSpanningTree::OnChangeHost(userrec* user, const std::string &newhost)
1027 {
1028         // only occurs for local clients
1029         if (user->registered != REG_ALL)
1030                 return;
1031         std::deque<std::string> params;
1032         params.push_back(newhost);
1033         Utils->DoOneToMany(user->uuid,"FHOST",params);
1034 }
1035
1036 void ModuleSpanningTree::OnChangeName(userrec* user, const std::string &gecos)
1037 {
1038         // only occurs for local clients
1039         if (user->registered != REG_ALL)
1040                 return;
1041         std::deque<std::string> params;
1042         params.push_back(gecos);
1043         Utils->DoOneToMany(user->uuid,"FNAME",params);
1044 }
1045
1046 void ModuleSpanningTree::OnUserPart(userrec* user, chanrec* channel, const std::string &partmessage, bool &silent)
1047 {
1048         if (IS_LOCAL(user))
1049         {
1050                 std::deque<std::string> params;
1051                 params.push_back(channel->name);
1052                 if (!partmessage.empty())
1053                         params.push_back(":"+partmessage);
1054                 Utils->DoOneToMany(user->uuid,"PART",params);
1055         }
1056 }
1057
1058 void ModuleSpanningTree::OnUserConnect(userrec* user)
1059 {
1060         if (IS_LOCAL(user))
1061         {
1062                 std::deque<std::string> params;
1063                 params.push_back(user->uuid);
1064                 params.push_back(ConvToStr(user->age));
1065                 params.push_back(user->nick);
1066                 params.push_back(user->host);
1067                 params.push_back(user->dhost);
1068                 params.push_back(user->ident);
1069                 params.push_back("+"+std::string(user->FormatModes()));
1070                 params.push_back(user->GetIPString());
1071                 params.push_back(ConvToStr(user->signon));
1072                 params.push_back(":"+std::string(user->fullname));
1073                 Utils->DoOneToMany(ServerInstance->Config->GetSID(), "UID", params);
1074                 // User is Local, change needs to be reflected!
1075                 TreeServer* SourceServer = Utils->FindServer(user->server);
1076                 if (SourceServer)
1077                 {
1078                         SourceServer->AddUserCount();
1079                 }
1080         }
1081 }
1082
1083 void ModuleSpanningTree::OnUserQuit(userrec* user, const std::string &reason, const std::string &oper_message)
1084 {
1085         if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
1086         {
1087                 std::deque<std::string> params;
1088
1089                 if (oper_message != reason)
1090                 {
1091                         params.push_back(":"+oper_message);
1092                         Utils->DoOneToMany(user->uuid,"OPERQUIT",params);
1093                 }
1094                 params.clear();
1095                 params.push_back(":"+reason);
1096                 Utils->DoOneToMany(user->uuid,"QUIT",params);
1097         }
1098         // Regardless, We need to modify the user Counts..
1099         TreeServer* SourceServer = Utils->FindServer(user->server);
1100         if (SourceServer)
1101         {
1102                 SourceServer->DelUserCount();
1103         }
1104 }
1105
1106 void ModuleSpanningTree::OnUserPostNick(userrec* user, const std::string &oldnick)
1107 {
1108         if (IS_LOCAL(user))
1109         {
1110                 std::deque<std::string> params;
1111                 params.push_back(user->nick);
1112
1113                 /** IMPORTANT: We don't update the TS if the oldnick is just a case change of the newnick!
1114                  */
1115                 if (irc::string(user->nick) != assign(oldnick))
1116                         user->age = ServerInstance->Time(true);
1117
1118                 params.push_back(ConvToStr(user->age));
1119                 Utils->DoOneToMany(user->uuid,"NICK",params);
1120         }
1121 }
1122
1123 void ModuleSpanningTree::OnUserKick(userrec* source, userrec* user, chanrec* chan, const std::string &reason, bool &silent)
1124 {
1125         if ((source) && (IS_LOCAL(source)))
1126         {
1127                 std::deque<std::string> params;
1128                 params.push_back(chan->name);
1129                 params.push_back(user->uuid);
1130                 params.push_back(":"+reason);
1131                 Utils->DoOneToMany(source->uuid,"KICK",params);
1132         }
1133         else if (!source)
1134         {
1135                 std::deque<std::string> params;
1136                 params.push_back(chan->name);
1137                 params.push_back(user->uuid);
1138                 params.push_back(":"+reason);
1139                 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"KICK",params);
1140         }
1141 }
1142
1143 void ModuleSpanningTree::OnRemoteKill(userrec* source, userrec* dest, const std::string &reason, const std::string &operreason)
1144 {
1145         std::deque<std::string> params;
1146         params.push_back(":"+reason);
1147         Utils->DoOneToMany(dest->uuid,"OPERQUIT",params);
1148         params.clear();
1149         params.push_back(dest->uuid);
1150         params.push_back(":"+reason);
1151         dest->SetOperQuit(operreason);
1152         Utils->DoOneToMany(source->uuid,"KILL",params);
1153 }
1154
1155 void ModuleSpanningTree::OnRehash(userrec* user, const std::string &parameter)
1156 {
1157         if (!parameter.empty())
1158         {
1159                 std::deque<std::string> params;
1160                 params.push_back(parameter);
1161                 Utils->DoOneToMany(user ? user->nick : ServerInstance->Config->GetSID(), "REHASH", params);
1162                 // check for self
1163                 if (ServerInstance->MatchText(ServerInstance->Config->ServerName,parameter))
1164                 {
1165                         ServerInstance->WriteOpers("*** Remote rehash initiated locally by \002%s\002", user ? user->nick : ServerInstance->Config->ServerName);
1166                         ServerInstance->RehashServer();
1167                 }
1168         }
1169         Utils->ReadConfiguration(false);
1170         InitializeDisabledCommands(ServerInstance->Config->DisabledCommands, ServerInstance);
1171 }
1172
1173 // note: the protocol does not allow direct umode +o except
1174 // via NICK with 8 params. sending OPERTYPE infers +o modechange
1175 // locally.
1176 void ModuleSpanningTree::OnOper(userrec* user, const std::string &opertype)
1177 {
1178         if (IS_LOCAL(user))
1179         {
1180                 std::deque<std::string> params;
1181                 params.push_back(opertype);
1182                 Utils->DoOneToMany(user->uuid,"OPERTYPE",params);
1183         }
1184 }
1185
1186 void ModuleSpanningTree::OnLine(userrec* source, const std::string &host, bool adding, char linetype, long duration, const std::string &reason)
1187 {
1188         if (!source)
1189         {
1190                 /* Server-set lines */
1191                 char data[MAXBUF];
1192                 snprintf(data,MAXBUF,"%c %s %s %lu %lu :%s", linetype, host.c_str(), ServerInstance->Config->ServerName, (unsigned long)ServerInstance->Time(false),
1193                                 (unsigned long)duration, reason.c_str());
1194                 std::deque<std::string> params;
1195                 params.push_back(data);
1196                 Utils->DoOneToMany(ServerInstance->Config->GetSID(), "ADDLINE", params);
1197         }
1198         else
1199         {
1200                 if (IS_LOCAL(source))
1201                 {
1202                         char type[8];
1203                         snprintf(type,8,"%cLINE",linetype);
1204                         std::string stype = type;
1205                         if (adding)
1206                         {
1207                                 char sduration[MAXBUF];
1208                                 snprintf(sduration,MAXBUF,"%ld",duration);
1209                                 std::deque<std::string> params;
1210                                 params.push_back(host);
1211                                 params.push_back(sduration);
1212                                 params.push_back(":"+reason);
1213                                 Utils->DoOneToMany(source->uuid,stype,params);
1214                         }
1215                         else
1216                         {
1217                                 std::deque<std::string> params;
1218                                 params.push_back(host);
1219                                 Utils->DoOneToMany(source->uuid,stype,params);
1220                         }
1221                 }
1222         }
1223 }
1224
1225 void ModuleSpanningTree::OnAddGLine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
1226 {
1227         OnLine(source,hostmask,true,'G',duration,reason);
1228 }
1229         
1230 void ModuleSpanningTree::OnAddZLine(long duration, userrec* source, const std::string &reason, const std::string &ipmask)
1231 {
1232         OnLine(source,ipmask,true,'Z',duration,reason);
1233 }
1234
1235 void ModuleSpanningTree::OnAddQLine(long duration, userrec* source, const std::string &reason, const std::string &nickmask)
1236 {
1237         OnLine(source,nickmask,true,'Q',duration,reason);
1238 }
1239
1240 void ModuleSpanningTree::OnAddELine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
1241 {
1242         OnLine(source,hostmask,true,'E',duration,reason);
1243 }
1244
1245 void ModuleSpanningTree::OnDelGLine(userrec* source, const std::string &hostmask)
1246 {
1247         OnLine(source,hostmask,false,'G',0,"");
1248 }
1249
1250 void ModuleSpanningTree::OnDelZLine(userrec* source, const std::string &ipmask)
1251 {
1252         OnLine(source,ipmask,false,'Z',0,"");
1253 }
1254
1255 void ModuleSpanningTree::OnDelQLine(userrec* source, const std::string &nickmask)
1256 {
1257         OnLine(source,nickmask,false,'Q',0,"");
1258 }
1259
1260 void ModuleSpanningTree::OnDelELine(userrec* source, const std::string &hostmask)
1261 {
1262         OnLine(source,hostmask,false,'E',0,"");
1263 }
1264
1265 void ModuleSpanningTree::OnMode(userrec* user, void* dest, int target_type, const std::string &text)
1266 {
1267         if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
1268         {
1269                 std::deque<std::string> params;
1270                 std::string command;
1271                 std::string output_text;
1272
1273                 ServerInstance->Parser->TranslateUIDs(TR_SPACENICKLIST, text, output_text);
1274
1275                 if (target_type == TYPE_USER)
1276                 {
1277                         userrec* u = (userrec*)dest;
1278                         params.push_back(u->uuid);
1279                         params.push_back(output_text);
1280                         command = "MODE";
1281                 }
1282                 else
1283                 {
1284                         chanrec* c = (chanrec*)dest;
1285                         params.push_back(c->name);
1286                         params.push_back(ConvToStr(c->age));
1287                         params.push_back(output_text);
1288                         command = "FMODE";
1289                 }
1290
1291                 Utils->DoOneToMany(user->uuid, command, params);
1292         }
1293 }
1294
1295 void ModuleSpanningTree::OnSetAway(userrec* user)
1296 {
1297         if (IS_LOCAL(user))
1298         {
1299                 std::deque<std::string> params;
1300                 params.push_back(":"+std::string(user->awaymsg));
1301                 Utils->DoOneToMany(user->uuid,"AWAY",params);
1302         }
1303 }
1304
1305 void ModuleSpanningTree::OnCancelAway(userrec* user)
1306 {
1307         if (IS_LOCAL(user))
1308         {
1309                 std::deque<std::string> params;
1310                 params.clear();
1311                 Utils->DoOneToMany(user->uuid,"AWAY",params);
1312         }
1313 }
1314
1315 void ModuleSpanningTree::ProtoSendMode(void* opaque, int target_type, void* target, const std::string &modeline)
1316 {
1317         TreeSocket* s = (TreeSocket*)opaque;
1318         std::string output_text;
1319
1320         ServerInstance->Parser->TranslateUIDs(TR_SPACENICKLIST, modeline, output_text);
1321
1322         if (target)
1323         {
1324                 if (target_type == TYPE_USER)
1325                 {
1326                         userrec* u = (userrec*)target;
1327                         s->WriteLine(std::string(":")+ServerInstance->Config->GetSID()+" FMODE "+u->uuid+" "+ConvToStr(u->age)+" "+output_text);
1328                 }
1329                 else
1330                 {
1331                         chanrec* c = (chanrec*)target;
1332                         s->WriteLine(std::string(":")+ServerInstance->Config->GetSID()+" FMODE "+c->name+" "+ConvToStr(c->age)+" "+output_text);
1333                 }
1334         }
1335 }
1336
1337 void ModuleSpanningTree::ProtoSendMetaData(void* opaque, int target_type, void* target, const std::string &extname, const std::string &extdata)
1338 {
1339         TreeSocket* s = (TreeSocket*)opaque;
1340         if (target)
1341         {
1342                 if (target_type == TYPE_USER)
1343                 {
1344                         userrec* u = (userrec*)target;
1345                         s->WriteLine(std::string(":")+ServerInstance->Config->GetSID()+" METADATA "+u->uuid+" "+extname+" :"+extdata);
1346                 }
1347                 else if (target_type == TYPE_CHANNEL)
1348                 {
1349                         chanrec* c = (chanrec*)target;
1350                         s->WriteLine(std::string(":")+ServerInstance->Config->GetSID()+" METADATA "+c->name+" "+extname+" :"+extdata);
1351                 }
1352         }
1353         if (target_type == TYPE_OTHER)
1354         {
1355                 s->WriteLine(std::string(":")+ServerInstance->Config->GetSID()+" METADATA * "+extname+" :"+extdata);
1356         }
1357 }
1358
1359 void ModuleSpanningTree::OnEvent(Event* event)
1360 {
1361         std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
1362         if (event->GetEventID() == "send_metadata")
1363         {
1364                 if (params->size() < 3)
1365                         return;
1366                 (*params)[2] = ":" + (*params)[2];
1367                 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"METADATA",*params);
1368         }
1369         else if (event->GetEventID() == "send_topic")
1370         {
1371                 if (params->size() < 2)
1372                         return;
1373                 (*params)[1] = ":" + (*params)[1];
1374                 params->insert(params->begin() + 1,ServerInstance->Config->ServerName);
1375                 params->insert(params->begin() + 1,ConvToStr(ServerInstance->Time(true)));
1376                 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"FTOPIC",*params);
1377         }
1378         else if (event->GetEventID() == "send_mode")
1379         {
1380                 if (params->size() < 2)
1381                         return;
1382                 // Insert the TS value of the object, either userrec or chanrec
1383                 time_t ourTS = 0;
1384                 std::string output_text;
1385
1386                 /* Warning: in-place translation is only safe for type TR_NICK */
1387                 for (size_t n = 0; n < params->size(); n++)
1388                         ServerInstance->Parser->TranslateUIDs(TR_NICK, (*params)[n], (*params)[n]);
1389
1390                 userrec* a = ServerInstance->FindNick((*params)[0]);
1391                 if (a)
1392                 {
1393                         ourTS = a->age;
1394                         Utils->DoOneToMany(ServerInstance->Config->GetSID(),"MODE",*params);
1395                         return;
1396                 }
1397                 else
1398                 {
1399                         chanrec* a = ServerInstance->FindChan((*params)[0]);
1400                         if (a)
1401                         {
1402                                 ourTS = a->age;
1403                                 params->insert(params->begin() + 1,ConvToStr(ourTS));
1404                                 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"FMODE",*params);
1405                         }
1406                 }
1407         }
1408         else if (event->GetEventID() == "send_mode_explicit")
1409         {
1410                 if (params->size() < 2)
1411                         return;
1412                 std::string output_text;
1413
1414                 /* Warning: in-place translation is only safe for type TR_NICK */
1415                 for (size_t n = 0; n < params->size(); n++)
1416                         ServerInstance->Parser->TranslateUIDs(TR_NICK, (*params)[n], (*params)[n]);
1417
1418                 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"MODE",*params);
1419         }
1420         else if (event->GetEventID() == "send_opers")
1421         {
1422                 if (params->size() < 1)
1423                         return;
1424                 (*params)[0] = ":" + (*params)[0];
1425                 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"OPERNOTICE",*params);
1426         }
1427         else if (event->GetEventID() == "send_modeset")
1428         {
1429                 if (params->size() < 2)
1430                         return;
1431                 (*params)[1] = ":" + (*params)[1];
1432                 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"MODENOTICE",*params);
1433         }
1434         else if (event->GetEventID() == "send_snoset")
1435         {
1436                 if (params->size() < 2)
1437                         return;
1438                 (*params)[1] = ":" + (*params)[1];
1439                 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"SNONOTICE",*params);
1440         }
1441         else if (event->GetEventID() == "send_push")
1442         {
1443                 if (params->size() < 2)
1444                         return;
1445                         
1446                 userrec *a = ServerInstance->FindNick((*params)[0]);
1447                         
1448                 if (!a)
1449                         return;
1450
1451                 (*params)[0] = a->uuid;
1452                 (*params)[1] = ":" + (*params)[1];
1453                 Utils->DoOneToOne(ServerInstance->Config->GetSID(), "PUSH", *params, a->server);
1454         }
1455 }
1456
1457 ModuleSpanningTree::~ModuleSpanningTree()
1458 {
1459         /* This will also free the listeners */
1460         delete Utils;
1461         if (SyncTimer)
1462                 ServerInstance->Timers->DelTimer(SyncTimer);
1463
1464         ServerInstance->Timers->DelTimer(RefreshTimer);
1465
1466         ServerInstance->Modules->DoneWithInterface("InspSocketHook");
1467 }
1468
1469 Version ModuleSpanningTree::GetVersion()
1470 {
1471         return Version(1,1,0,2,VF_VENDOR,API_VERSION);
1472 }
1473
1474 void ModuleSpanningTree::Implements(char* List)
1475 {
1476         List[I_OnPreCommand] = List[I_OnGetServerDescription] = List[I_OnUserInvite] = List[I_OnPostLocalTopicChange] = 1;
1477         List[I_OnWallops] = List[I_OnUserNotice] = List[I_OnUserMessage] = List[I_OnBackgroundTimer] = 1;
1478         List[I_OnUserJoin] = List[I_OnChangeHost] = List[I_OnChangeName] = List[I_OnUserPart] = List[I_OnUserConnect] = 1;
1479         List[I_OnUserQuit] = List[I_OnUserPostNick] = List[I_OnUserKick] = List[I_OnRemoteKill] = List[I_OnRehash] = 1;
1480         List[I_OnOper] = List[I_OnAddGLine] = List[I_OnAddZLine] = List[I_OnAddQLine] = List[I_OnAddELine] = 1;
1481         List[I_OnDelGLine] = List[I_OnDelZLine] = List[I_OnDelQLine] = List[I_OnDelELine] = List[I_ProtoSendMode] = List[I_OnMode] = 1;
1482         List[I_OnStats] = List[I_ProtoSendMetaData] = List[I_OnEvent] = List[I_OnSetAway] = List[I_OnCancelAway] = List[I_OnPostCommand] = 1;
1483 }
1484
1485 /* It is IMPORTANT that m_spanningtree is the last module in the chain
1486  * so that any activity it sees is FINAL, e.g. we arent going to send out
1487  * a NICK message before m_cloaking has finished putting the +x on the user,
1488  * etc etc.
1489  * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
1490  * the module call queue.
1491  */
1492 Priority ModuleSpanningTree::Prioritize()
1493 {
1494         return PRIORITY_LAST;
1495 }
1496
1497 MODULE_INIT(ModuleSpanningTree)