]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/main.cpp
We really should SEND it too, if we're looking for it... :p
[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         std::deque<std::string> params;
633         char text[MAXBUF];
634         va_list argsPtr;
635
636         va_start(argsPtr, format);
637         vsnprintf(text, MAXBUF, format, argsPtr);
638         va_end(argsPtr);
639
640         if (!user)
641         {
642                 /* No user, target it generically at everyone */
643                 ServerInstance->SNO->WriteToSnoMask('l', "%s", text);
644                 params.push_back("l");
645                 params.push_back(std::string(":") + text);
646                 Utils->DoOneToMany(ServerInstance->Config->GetSID(), "SNONOTICE", params);
647         }
648         else
649         {
650                 if (IS_LOCAL(user))
651                         user->WriteServ("NOTICE %s :%s", user->nick, text);
652                 else
653                 {
654                         params.push_back(user->uuid);
655                         params.push_back(std::string("::") + ServerInstance->Config->ServerName + " NOTICE " + user->nick + " :*** From " +
656                                         ServerInstance->Config->ServerName+ ": " + text);
657                         Utils->DoOneToMany(ServerInstance->Config->GetSID(), "PUSH", params);
658                 }
659         }
660 }
661         
662 int ModuleSpanningTree::HandleConnect(const char** parameters, int pcnt, userrec* user)
663 {
664         for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
665         {
666                 if (ServerInstance->MatchText(x->Name.c_str(),parameters[0]))
667                 {
668                         TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
669                         if (!CheckDupe)
670                         {
671                                 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);
672                                 ConnectServer(&(*x));
673                                 return 1;
674                         }
675                         else
676                         {
677                                 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());
678                                 return 1;
679                         }
680                 }
681         }
682         RemoteMessage(user, "NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
683         return 1;
684 }
685
686 void ModuleSpanningTree::BroadcastTimeSync()
687 {
688         if (Utils->MasterTime)
689         {
690                 std::deque<std::string> params;
691                 params.push_back(ConvToStr(ServerInstance->Time(false)));
692                 params.push_back("FORCE");
693                 Utils->DoOneToMany(ServerInstance->Config->GetSID(), "TIMESET", params);
694         }
695 }
696
697 int ModuleSpanningTree::OnStats(char statschar, userrec* user, string_list &results)
698 {
699         if ((statschar == 'c') || (statschar == 'n'))
700         {
701                 for (unsigned int i = 0; i < Utils->LinkBlocks.size(); i++)
702                 {
703                         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');
704                         if (statschar == 'c')
705                                 results.push_back(std::string(ServerInstance->Config->ServerName)+" 244 "+user->nick+" H * * "+Utils->LinkBlocks[i].Name.c_str());
706                 }
707                 results.push_back(std::string(ServerInstance->Config->ServerName)+" 219 "+user->nick+" "+statschar+" :End of /STATS report");
708                 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);
709                 return 1;
710         }
711
712         if (statschar == 'p')
713         {
714                 /* show all server ports, after showing client ports. -- w00t */
715
716                 for (unsigned int i = 0; i < Utils->Bindings.size(); i++)
717                 {
718                         std::string ip = Utils->Bindings[i]->IP;
719                         if (ip.empty())
720                                 ip = "*";
721
722                         std::string transport("plaintext");
723                         if (Utils->Bindings[i]->GetHook())
724                                 transport = InspSocketNameRequest(this, Utils->Bindings[i]->GetHook()).Send();
725
726                         results.push_back(ConvToStr(ServerInstance->Config->ServerName) + " 249 "+user->nick+" :" + ip + ":" + ConvToStr(Utils->Bindings[i]->port)+
727                                 " (server, " + transport + ")");
728                 }
729         }
730         return 0;
731 }
732
733 int ModuleSpanningTree::OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated, const std::string &original_line)
734 {
735         /* If the command doesnt appear to be valid, we dont want to mess with it. */
736         if (!validated)
737                 return 0;
738
739         if (command == "CONNECT")
740         {
741                 return this->HandleConnect(parameters,pcnt,user);
742         }
743         else if (command == "STATS")
744         {
745                 return this->HandleStats(parameters,pcnt,user);
746         }
747         else if (command == "MOTD")
748         {
749                 return this->HandleMotd(parameters,pcnt,user);
750         }
751         else if (command == "ADMIN")
752         {
753                 return this->HandleAdmin(parameters,pcnt,user);
754         }
755         else if (command == "SQUIT")
756         {
757                 return this->HandleSquit(parameters,pcnt,user);
758         }
759         else if (command == "MAP")
760         {
761                 this->HandleMap(parameters,pcnt,user);
762                 return 1;
763         }
764         else if ((command == "TIME") && (pcnt > 0))
765         {
766                 return this->HandleTime(parameters,pcnt,user);
767         }
768         else if (command == "LUSERS")
769         {
770                 this->HandleLusers(parameters,pcnt,user);
771                 return 1;
772         }
773         else if (command == "LINKS")
774         {
775                 this->HandleLinks(parameters,pcnt,user);
776                 return 1;
777         }
778         else if (command == "WHOIS")
779         {
780                 if (pcnt > 1)
781                 {
782                         // remote whois
783                         return this->HandleRemoteWhois(parameters,pcnt,user);
784                 }
785         }
786         else if ((command == "VERSION") && (pcnt > 0))
787         {
788                 this->HandleVersion(parameters,pcnt,user);
789                 return 1;
790         }
791         else if ((command == "MODULES") && (pcnt > 0))
792         {
793                 return this->HandleModules(parameters,pcnt,user);
794         }
795         return 0;
796 }
797
798 void ModuleSpanningTree::OnPostCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, CmdResult result, const std::string &original_line)
799 {
800         if ((result == CMD_SUCCESS) && (ServerInstance->IsValidModuleCommand(command, pcnt, user)))
801         {
802                 /* Safe, we know its non-null because IsValidModuleCommand returned true */
803                 command_t* thiscmd = ServerInstance->Parser->GetHandler(command);
804                 // this bit of code cleverly routes all module commands
805                 // to all remote severs *automatically* so that modules
806                 // can just handle commands locally, without having
807                 // to have any special provision in place for remote
808                 // commands and linking protocols.
809                 std::deque<std::string> params;
810                 params.clear();
811                 int n_translate = thiscmd->translation.size();
812                 TranslateType translate_to;
813
814                 for (int j = 0; j < pcnt; j++)
815                 {
816                         std::string target;
817
818                         /* Map all items to UUIDs where neccessary */
819                         if (j < n_translate)
820                         {
821                                 /* We have a translation mapping for this index */
822                                 translate_to = thiscmd->translation[j] != TR_END ? thiscmd->translation[j] : TR_TEXT;
823                         }
824                         else
825                                 translate_to = TR_TEXT;
826
827                         ServerInstance->Log(DEBUG,"TRANSLATION: %s - type is %d", parameters[j], translate_to);
828                         ServerInstance->Parser->TranslateUIDs(translate_to, parameters[j], target);
829
830                         if (strchr(parameters[j],' '))
831                                 params.push_back(":" + target);
832                         else
833                                 params.push_back(target);
834                 }
835                 Utils->DoOneToMany(user->uuid, command, params);
836         }
837 }
838
839 void ModuleSpanningTree::OnGetServerDescription(const std::string &servername,std::string &description)
840 {
841         TreeServer* s = Utils->FindServer(servername);
842         if (s)
843         {
844                 description = s->GetDesc();
845         }
846 }
847
848 void ModuleSpanningTree::OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
849 {
850         if (IS_LOCAL(source))
851         {
852                 std::deque<std::string> params;
853                 params.push_back(dest->uuid);
854                 params.push_back(channel->name);
855                 Utils->DoOneToMany(source->uuid,"INVITE",params);
856         }
857 }
858
859 void ModuleSpanningTree::OnPostLocalTopicChange(userrec* user, chanrec* chan, const std::string &topic)
860 {
861         std::deque<std::string> params;
862         params.push_back(chan->name);
863         params.push_back(":"+topic);
864         Utils->DoOneToMany(user->uuid,"TOPIC",params);
865 }
866
867 void ModuleSpanningTree::OnWallops(userrec* user, const std::string &text)
868 {
869         if (IS_LOCAL(user))
870         {
871                 std::deque<std::string> params;
872                 params.push_back(":"+text);
873                 Utils->DoOneToMany(user->uuid,"WALLOPS",params);
874         }
875 }
876
877 void ModuleSpanningTree::OnUserNotice(userrec* user, void* dest, int target_type, const std::string &text, char status, const CUList &exempt_list)
878 {
879         if (target_type == TYPE_USER)
880         {
881                 userrec* d = (userrec*)dest;
882                 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
883                 {
884                         std::deque<std::string> params;
885                         params.clear();
886                         params.push_back(d->uuid);
887                         params.push_back(":"+text);
888                         Utils->DoOneToOne(user->uuid,"NOTICE",params,d->server);
889                 }
890         }
891         else if (target_type == TYPE_CHANNEL)
892         {
893                 if (IS_LOCAL(user))
894                 {
895                         chanrec *c = (chanrec*)dest;
896                         if (c)
897                         {
898                                 std::string cname = c->name;
899                                 if (status)
900                                         cname = status + cname;
901                                 TreeServerList list;
902                                 Utils->GetListOfServersForChannel(c,list,status,exempt_list);
903                                 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
904                                 {
905                                         TreeSocket* Sock = i->second->GetSocket();
906                                         if (Sock)
907                                                 Sock->WriteLine(":"+std::string(user->uuid)+" NOTICE "+cname+" :"+text);
908                                 }
909                         }
910                 }
911         }
912         else if (target_type == TYPE_SERVER)
913         {
914                 if (IS_LOCAL(user))
915                 {
916                         char* target = (char*)dest;
917                         std::deque<std::string> par;
918                         par.push_back(target);
919                         par.push_back(":"+text);
920                         Utils->DoOneToMany(user->uuid,"NOTICE",par);
921                 }
922         }
923 }
924
925 void ModuleSpanningTree::OnUserMessage(userrec* user, void* dest, int target_type, const std::string &text, char status, const CUList &exempt_list)
926 {
927         if (target_type == TYPE_USER)
928         {
929                 // route private messages which are targetted at clients only to the server
930                 // which needs to receive them
931                 userrec* d = (userrec*)dest;
932                 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
933                 {
934                         std::deque<std::string> params;
935                         params.clear();
936                         params.push_back(d->uuid);
937                         params.push_back(":"+text);
938                         Utils->DoOneToOne(user->uuid,"PRIVMSG",params,d->server);
939                 }
940         }
941         else if (target_type == TYPE_CHANNEL)
942         {
943                 if (IS_LOCAL(user))
944                 {
945                         chanrec *c = (chanrec*)dest;
946                         if (c)
947                         {
948                                 std::string cname = c->name;
949                                 if (status)
950                                         cname = status + cname;
951                                 TreeServerList list;
952                                 Utils->GetListOfServersForChannel(c,list,status,exempt_list);
953                                 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
954                                 {
955                                         TreeSocket* Sock = i->second->GetSocket();
956                                         if (Sock)
957                                                 Sock->WriteLine(":"+std::string(user->uuid)+" PRIVMSG "+cname+" :"+text);
958                                 }
959                         }
960                 }
961         }
962         else if (target_type == TYPE_SERVER)
963         {
964                 if (IS_LOCAL(user))
965                 {
966                         char* target = (char*)dest;
967                         std::deque<std::string> par;
968                         par.push_back(target);
969                         par.push_back(":"+text);
970                         Utils->DoOneToMany(user->uuid,"PRIVMSG",par);
971                 }
972         }
973 }
974
975 void ModuleSpanningTree::OnBackgroundTimer(time_t curtime)
976 {
977         AutoConnectServers(curtime);
978         DoPingChecks(curtime);
979 }
980
981 void ModuleSpanningTree::OnUserJoin(userrec* user, chanrec* channel, bool &silent)
982 {
983         // Only do this for local users
984         if (IS_LOCAL(user))
985         {
986                 if (channel->GetUserCounter() == 1)
987                 {
988                         std::deque<std::string> params;
989                         // set up their permissions and the channel TS with FJOIN.
990                         // All users are FJOINed now, because a module may specify
991                         // new joining permissions for the user.
992                         params.push_back(channel->name);
993                         params.push_back(ConvToStr(channel->age));
994                         params.push_back(std::string(channel->GetAllPrefixChars(user))+","+std::string(user->uuid));
995                         Utils->DoOneToMany(ServerInstance->Config->GetSID(),"FJOIN",params);
996                         /* First user in, sync the modes for the channel */
997                         params.pop_back();
998                         params.push_back(channel->ChanModes(true));
999                         Utils->DoOneToMany(ServerInstance->Config->GetSID(),"FMODE",params);
1000                 }
1001                 else
1002                 {
1003                         std::deque<std::string> params;
1004                         params.push_back(channel->name);
1005                         params.push_back(ConvToStr(channel->age));
1006                         Utils->DoOneToMany(user->uuid,"JOIN",params);
1007                 }
1008         }
1009 }
1010
1011 void ModuleSpanningTree::OnChangeHost(userrec* user, const std::string &newhost)
1012 {
1013         // only occurs for local clients
1014         if (user->registered != REG_ALL)
1015                 return;
1016         std::deque<std::string> params;
1017         params.push_back(newhost);
1018         Utils->DoOneToMany(user->uuid,"FHOST",params);
1019 }
1020
1021 void ModuleSpanningTree::OnChangeName(userrec* user, const std::string &gecos)
1022 {
1023         // only occurs for local clients
1024         if (user->registered != REG_ALL)
1025                 return;
1026         std::deque<std::string> params;
1027         params.push_back(gecos);
1028         Utils->DoOneToMany(user->uuid,"FNAME",params);
1029 }
1030
1031 void ModuleSpanningTree::OnUserPart(userrec* user, chanrec* channel, const std::string &partmessage, bool &silent)
1032 {
1033         if (IS_LOCAL(user))
1034         {
1035                 std::deque<std::string> params;
1036                 params.push_back(channel->name);
1037                 if (!partmessage.empty())
1038                         params.push_back(":"+partmessage);
1039                 Utils->DoOneToMany(user->uuid,"PART",params);
1040         }
1041 }
1042
1043 void ModuleSpanningTree::OnUserConnect(userrec* user)
1044 {
1045         if (IS_LOCAL(user))
1046         {
1047                 std::deque<std::string> params;
1048                 params.push_back(user->uuid);
1049                 params.push_back(ConvToStr(user->age));
1050                 params.push_back(user->nick);
1051                 params.push_back(user->host);
1052                 params.push_back(user->dhost);
1053                 params.push_back(user->ident);
1054                 params.push_back("+"+std::string(user->FormatModes()));
1055                 params.push_back(user->GetIPString());
1056                 params.push_back(ConvToStr(user->signon));
1057                 params.push_back(":"+std::string(user->fullname));
1058                 Utils->DoOneToMany(ServerInstance->Config->GetSID(), "UID", params);
1059                 // User is Local, change needs to be reflected!
1060                 TreeServer* SourceServer = Utils->FindServer(user->server);
1061                 if (SourceServer)
1062                 {
1063                         SourceServer->AddUserCount();
1064                 }
1065         }
1066 }
1067
1068 void ModuleSpanningTree::OnUserQuit(userrec* user, const std::string &reason, const std::string &oper_message)
1069 {
1070         if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
1071         {
1072                 std::deque<std::string> params;
1073
1074                 if (oper_message != reason)
1075                 {
1076                         params.push_back(":"+oper_message);
1077                         Utils->DoOneToMany(user->uuid,"OPERQUIT",params);
1078                 }
1079                 params.clear();
1080                 params.push_back(":"+reason);
1081                 Utils->DoOneToMany(user->uuid,"QUIT",params);
1082         }
1083         // Regardless, We need to modify the user Counts..
1084         TreeServer* SourceServer = Utils->FindServer(user->server);
1085         if (SourceServer)
1086         {
1087                 SourceServer->DelUserCount();
1088         }
1089 }
1090
1091 void ModuleSpanningTree::OnUserPostNick(userrec* user, const std::string &oldnick)
1092 {
1093         if (IS_LOCAL(user))
1094         {
1095                 std::deque<std::string> params;
1096                 params.push_back(user->nick);
1097
1098                 /** IMPORTANT: We don't update the TS if the oldnick is just a case change of the newnick!
1099                  */
1100                 if (irc::string(user->nick) != assign(oldnick))
1101                         user->age = ServerInstance->Time(true);
1102
1103                 params.push_back(ConvToStr(user->age));
1104                 Utils->DoOneToMany(user->uuid,"NICK",params);
1105         }
1106 }
1107
1108 void ModuleSpanningTree::OnUserKick(userrec* source, userrec* user, chanrec* chan, const std::string &reason, bool &silent)
1109 {
1110         if ((source) && (IS_LOCAL(source)))
1111         {
1112                 std::deque<std::string> params;
1113                 params.push_back(chan->name);
1114                 params.push_back(user->uuid);
1115                 params.push_back(":"+reason);
1116                 Utils->DoOneToMany(source->uuid,"KICK",params);
1117         }
1118         else if (!source)
1119         {
1120                 std::deque<std::string> params;
1121                 params.push_back(chan->name);
1122                 params.push_back(user->uuid);
1123                 params.push_back(":"+reason);
1124                 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"KICK",params);
1125         }
1126 }
1127
1128 void ModuleSpanningTree::OnRemoteKill(userrec* source, userrec* dest, const std::string &reason, const std::string &operreason)
1129 {
1130         std::deque<std::string> params;
1131         params.push_back(":"+reason);
1132         Utils->DoOneToMany(dest->uuid,"OPERQUIT",params);
1133         params.clear();
1134         params.push_back(dest->uuid);
1135         params.push_back(":"+reason);
1136         dest->SetOperQuit(operreason);
1137         Utils->DoOneToMany(source->uuid,"KILL",params);
1138 }
1139
1140 void ModuleSpanningTree::OnRehash(userrec* user, const std::string &parameter)
1141 {
1142         if (!parameter.empty())
1143         {
1144                 std::deque<std::string> params;
1145                 params.push_back(parameter);
1146                 Utils->DoOneToMany(user ? user->nick : ServerInstance->Config->GetSID(), "REHASH", params);
1147                 // check for self
1148                 if (ServerInstance->MatchText(ServerInstance->Config->ServerName,parameter))
1149                 {
1150                         ServerInstance->WriteOpers("*** Remote rehash initiated locally by \002%s\002", user ? user->nick : ServerInstance->Config->ServerName);
1151                         ServerInstance->RehashServer();
1152                 }
1153         }
1154         Utils->ReadConfiguration(false);
1155         InitializeDisabledCommands(ServerInstance->Config->DisabledCommands, ServerInstance);
1156 }
1157
1158 // note: the protocol does not allow direct umode +o except
1159 // via NICK with 8 params. sending OPERTYPE infers +o modechange
1160 // locally.
1161 void ModuleSpanningTree::OnOper(userrec* user, const std::string &opertype)
1162 {
1163         if (IS_LOCAL(user))
1164         {
1165                 std::deque<std::string> params;
1166                 params.push_back(opertype);
1167                 Utils->DoOneToMany(user->uuid,"OPERTYPE",params);
1168         }
1169 }
1170
1171 void ModuleSpanningTree::OnLine(userrec* source, const std::string &host, bool adding, char linetype, long duration, const std::string &reason)
1172 {
1173         if (!source)
1174         {
1175                 /* Server-set lines */
1176                 char data[MAXBUF];
1177                 snprintf(data,MAXBUF,"%c %s %s %lu %lu :%s", linetype, host.c_str(), ServerInstance->Config->ServerName, (unsigned long)ServerInstance->Time(false),
1178                                 (unsigned long)duration, reason.c_str());
1179                 std::deque<std::string> params;
1180                 params.push_back(data);
1181                 Utils->DoOneToMany(ServerInstance->Config->GetSID(), "ADDLINE", params);
1182         }
1183         else
1184         {
1185                 if (IS_LOCAL(source))
1186                 {
1187                         char type[8];
1188                         snprintf(type,8,"%cLINE",linetype);
1189                         std::string stype = type;
1190                         if (adding)
1191                         {
1192                                 char sduration[MAXBUF];
1193                                 snprintf(sduration,MAXBUF,"%ld",duration);
1194                                 std::deque<std::string> params;
1195                                 params.push_back(host);
1196                                 params.push_back(sduration);
1197                                 params.push_back(":"+reason);
1198                                 Utils->DoOneToMany(source->uuid,stype,params);
1199                         }
1200                         else
1201                         {
1202                                 std::deque<std::string> params;
1203                                 params.push_back(host);
1204                                 Utils->DoOneToMany(source->uuid,stype,params);
1205                         }
1206                 }
1207         }
1208 }
1209
1210 void ModuleSpanningTree::OnAddGLine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
1211 {
1212         OnLine(source,hostmask,true,'G',duration,reason);
1213 }
1214         
1215 void ModuleSpanningTree::OnAddZLine(long duration, userrec* source, const std::string &reason, const std::string &ipmask)
1216 {
1217         OnLine(source,ipmask,true,'Z',duration,reason);
1218 }
1219
1220 void ModuleSpanningTree::OnAddQLine(long duration, userrec* source, const std::string &reason, const std::string &nickmask)
1221 {
1222         OnLine(source,nickmask,true,'Q',duration,reason);
1223 }
1224
1225 void ModuleSpanningTree::OnAddELine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
1226 {
1227         OnLine(source,hostmask,true,'E',duration,reason);
1228 }
1229
1230 void ModuleSpanningTree::OnDelGLine(userrec* source, const std::string &hostmask)
1231 {
1232         OnLine(source,hostmask,false,'G',0,"");
1233 }
1234
1235 void ModuleSpanningTree::OnDelZLine(userrec* source, const std::string &ipmask)
1236 {
1237         OnLine(source,ipmask,false,'Z',0,"");
1238 }
1239
1240 void ModuleSpanningTree::OnDelQLine(userrec* source, const std::string &nickmask)
1241 {
1242         OnLine(source,nickmask,false,'Q',0,"");
1243 }
1244
1245 void ModuleSpanningTree::OnDelELine(userrec* source, const std::string &hostmask)
1246 {
1247         OnLine(source,hostmask,false,'E',0,"");
1248 }
1249
1250 void ModuleSpanningTree::OnMode(userrec* user, void* dest, int target_type, const std::string &text)
1251 {
1252         if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
1253         {
1254                 std::deque<std::string> params;
1255                 std::string command;
1256                 std::string output_text;
1257
1258                 ServerInstance->Parser->TranslateUIDs(TR_SPACENICKLIST, text, output_text);
1259
1260                 if (target_type == TYPE_USER)
1261                 {
1262                         userrec* u = (userrec*)dest;
1263                         params.push_back(u->uuid);
1264                         params.push_back(output_text);
1265                         command = "MODE";
1266                 }
1267                 else
1268                 {
1269                         chanrec* c = (chanrec*)dest;
1270                         params.push_back(c->name);
1271                         params.push_back(ConvToStr(c->age));
1272                         params.push_back(output_text);
1273                         command = "FMODE";
1274                 }
1275
1276                 Utils->DoOneToMany(user->uuid, command, params);
1277         }
1278 }
1279
1280 void ModuleSpanningTree::OnSetAway(userrec* user)
1281 {
1282         if (IS_LOCAL(user))
1283         {
1284                 std::deque<std::string> params;
1285                 params.push_back(":"+std::string(user->awaymsg));
1286                 Utils->DoOneToMany(user->uuid,"AWAY",params);
1287         }
1288 }
1289
1290 void ModuleSpanningTree::OnCancelAway(userrec* user)
1291 {
1292         if (IS_LOCAL(user))
1293         {
1294                 std::deque<std::string> params;
1295                 params.clear();
1296                 Utils->DoOneToMany(user->uuid,"AWAY",params);
1297         }
1298 }
1299
1300 void ModuleSpanningTree::ProtoSendMode(void* opaque, int target_type, void* target, const std::string &modeline)
1301 {
1302         TreeSocket* s = (TreeSocket*)opaque;
1303         std::string output_text;
1304
1305         ServerInstance->Parser->TranslateUIDs(TR_SPACENICKLIST, modeline, output_text);
1306
1307         if (target)
1308         {
1309                 if (target_type == TYPE_USER)
1310                 {
1311                         userrec* u = (userrec*)target;
1312                         s->WriteLine(std::string(":")+ServerInstance->Config->GetSID()+" FMODE "+u->uuid+" "+ConvToStr(u->age)+" "+output_text);
1313                 }
1314                 else
1315                 {
1316                         chanrec* c = (chanrec*)target;
1317                         s->WriteLine(std::string(":")+ServerInstance->Config->GetSID()+" FMODE "+c->name+" "+ConvToStr(c->age)+" "+output_text);
1318                 }
1319         }
1320 }
1321
1322 void ModuleSpanningTree::ProtoSendMetaData(void* opaque, int target_type, void* target, const std::string &extname, const std::string &extdata)
1323 {
1324         TreeSocket* s = (TreeSocket*)opaque;
1325         if (target)
1326         {
1327                 if (target_type == TYPE_USER)
1328                 {
1329                         userrec* u = (userrec*)target;
1330                         s->WriteLine(std::string(":")+ServerInstance->Config->GetSID()+" METADATA "+u->uuid+" "+extname+" :"+extdata);
1331                 }
1332                 else if (target_type == TYPE_CHANNEL)
1333                 {
1334                         chanrec* c = (chanrec*)target;
1335                         s->WriteLine(std::string(":")+ServerInstance->Config->GetSID()+" METADATA "+c->name+" "+extname+" :"+extdata);
1336                 }
1337         }
1338         if (target_type == TYPE_OTHER)
1339         {
1340                 s->WriteLine(std::string(":")+ServerInstance->Config->GetSID()+" METADATA * "+extname+" :"+extdata);
1341         }
1342 }
1343
1344 void ModuleSpanningTree::OnEvent(Event* event)
1345 {
1346         std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
1347         if (event->GetEventID() == "send_metadata")
1348         {
1349                 if (params->size() < 3)
1350                         return;
1351                 (*params)[2] = ":" + (*params)[2];
1352                 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"METADATA",*params);
1353         }
1354         else if (event->GetEventID() == "send_topic")
1355         {
1356                 if (params->size() < 2)
1357                         return;
1358                 (*params)[1] = ":" + (*params)[1];
1359                 params->insert(params->begin() + 1,ServerInstance->Config->ServerName);
1360                 params->insert(params->begin() + 1,ConvToStr(ServerInstance->Time(true)));
1361                 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"FTOPIC",*params);
1362         }
1363         else if (event->GetEventID() == "send_mode")
1364         {
1365                 if (params->size() < 2)
1366                         return;
1367                 // Insert the TS value of the object, either userrec or chanrec
1368                 time_t ourTS = 0;
1369                 std::string output_text;
1370
1371                 /* Warning: in-place translation is only safe for type TR_NICK */
1372                 for (size_t n = 0; n < params->size(); n++)
1373                         ServerInstance->Parser->TranslateUIDs(TR_NICK, (*params)[n], (*params)[n]);
1374
1375                 userrec* a = ServerInstance->FindNick((*params)[0]);
1376                 if (a)
1377                 {
1378                         ourTS = a->age;
1379                         Utils->DoOneToMany(ServerInstance->Config->GetSID(),"MODE",*params);
1380                         return;
1381                 }
1382                 else
1383                 {
1384                         chanrec* a = ServerInstance->FindChan((*params)[0]);
1385                         if (a)
1386                         {
1387                                 ourTS = a->age;
1388                                 params->insert(params->begin() + 1,ConvToStr(ourTS));
1389                                 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"FMODE",*params);
1390                         }
1391                 }
1392         }
1393         else if (event->GetEventID() == "send_mode_explicit")
1394         {
1395                 if (params->size() < 2)
1396                         return;
1397                 std::string output_text;
1398
1399                 /* Warning: in-place translation is only safe for type TR_NICK */
1400                 for (size_t n = 0; n < params->size(); n++)
1401                         ServerInstance->Parser->TranslateUIDs(TR_NICK, (*params)[n], (*params)[n]);
1402
1403                 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"MODE",*params);
1404         }
1405         else if (event->GetEventID() == "send_opers")
1406         {
1407                 if (params->size() < 1)
1408                         return;
1409                 (*params)[0] = ":" + (*params)[0];
1410                 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"OPERNOTICE",*params);
1411         }
1412         else if (event->GetEventID() == "send_modeset")
1413         {
1414                 if (params->size() < 2)
1415                         return;
1416                 (*params)[1] = ":" + (*params)[1];
1417                 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"MODENOTICE",*params);
1418         }
1419         else if (event->GetEventID() == "send_snoset")
1420         {
1421                 if (params->size() < 2)
1422                         return;
1423                 (*params)[1] = ":" + (*params)[1];
1424                 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"SNONOTICE",*params);
1425         }
1426         else if (event->GetEventID() == "send_push")
1427         {
1428                 if (params->size() < 2)
1429                         return;
1430                         
1431                 userrec *a = ServerInstance->FindNick((*params)[0]);
1432                         
1433                 if (!a)
1434                         return;
1435
1436                 (*params)[0] = a->uuid;
1437                 (*params)[1] = ":" + (*params)[1];
1438                 Utils->DoOneToOne(ServerInstance->Config->GetSID(), "PUSH", *params, a->server);
1439         }
1440 }
1441
1442 ModuleSpanningTree::~ModuleSpanningTree()
1443 {
1444         /* This will also free the listeners */
1445         delete Utils;
1446         if (SyncTimer)
1447                 ServerInstance->Timers->DelTimer(SyncTimer);
1448
1449         ServerInstance->Timers->DelTimer(RefreshTimer);
1450
1451         ServerInstance->Modules->DoneWithInterface("InspSocketHook");
1452 }
1453
1454 Version ModuleSpanningTree::GetVersion()
1455 {
1456         return Version(1,1,0,2,VF_VENDOR,API_VERSION);
1457 }
1458
1459 void ModuleSpanningTree::Implements(char* List)
1460 {
1461         List[I_OnPreCommand] = List[I_OnGetServerDescription] = List[I_OnUserInvite] = List[I_OnPostLocalTopicChange] = 1;
1462         List[I_OnWallops] = List[I_OnUserNotice] = List[I_OnUserMessage] = List[I_OnBackgroundTimer] = 1;
1463         List[I_OnUserJoin] = List[I_OnChangeHost] = List[I_OnChangeName] = List[I_OnUserPart] = List[I_OnUserConnect] = 1;
1464         List[I_OnUserQuit] = List[I_OnUserPostNick] = List[I_OnUserKick] = List[I_OnRemoteKill] = List[I_OnRehash] = 1;
1465         List[I_OnOper] = List[I_OnAddGLine] = List[I_OnAddZLine] = List[I_OnAddQLine] = List[I_OnAddELine] = 1;
1466         List[I_OnDelGLine] = List[I_OnDelZLine] = List[I_OnDelQLine] = List[I_OnDelELine] = List[I_ProtoSendMode] = List[I_OnMode] = 1;
1467         List[I_OnStats] = List[I_ProtoSendMetaData] = List[I_OnEvent] = List[I_OnSetAway] = List[I_OnCancelAway] = List[I_OnPostCommand] = 1;
1468 }
1469
1470 /* It is IMPORTANT that m_spanningtree is the last module in the chain
1471  * so that any activity it sees is FINAL, e.g. we arent going to send out
1472  * a NICK message before m_cloaking has finished putting the +x on the user,
1473  * etc etc.
1474  * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
1475  * the module call queue.
1476  */
1477 Priority ModuleSpanningTree::Prioritize()
1478 {
1479         return PRIORITY_LAST;
1480 }
1481
1482 MODULE_INIT(ModuleSpanningTree)