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