]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/main.cpp
b0829cc1d9cc8521c91b8a675bf8e4616a736c2b
[user/henk/code/inspircd.git] / src / modules / m_spanningtree / main.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2009 InspIRCd Development Team
6  * See: http://wiki.inspircd.org/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 "socket.h"
18 #include "xline.h"
19 #include "../transport.h"
20
21 #include "cachetimer.h"
22 #include "resolvers.h"
23 #include "main.h"
24 #include "utils.h"
25 #include "treeserver.h"
26 #include "link.h"
27 #include "treesocket.h"
28 #include "rconnect.h"
29 #include "rsquit.h"
30 #include "protocolinterface.h"
31
32 /* $ModDep: m_spanningtree/cachetimer.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 m_spanningtree/protocolinterface.h */
33
34 ModuleSpanningTree::ModuleSpanningTree()
35         : max_local(0), max_global(0)
36 {
37         ServerInstance->Modules->UseInterface("BufferedSocketHook");
38         Utils = new SpanningTreeUtilities(this);
39         command_rconnect = new CommandRConnect(this, Utils);
40         ServerInstance->AddCommand(command_rconnect);
41         command_rsquit = new CommandRSQuit(this, Utils);
42         ServerInstance->AddCommand(command_rsquit);
43         RefreshTimer = new CacheRefreshTimer(Utils);
44         ServerInstance->Timers->AddTimer(RefreshTimer);
45
46         Implementation eventlist[] =
47         {
48                 I_OnPreCommand, I_OnGetServerDescription, I_OnUserInvite, I_OnPostTopicChange,
49                 I_OnWallops, I_OnUserNotice, I_OnUserMessage, I_OnBackgroundTimer, I_OnUserJoin,
50                 I_OnChangeLocalUserHost, I_OnChangeName, I_OnChangeIdent, I_OnUserPart, I_OnUnloadModule,
51                 I_OnUserQuit, I_OnUserPostNick, I_OnUserKick, I_OnRemoteKill, I_OnRehash, I_OnPreRehash,
52                 I_OnOper, I_OnAddLine, I_OnDelLine, I_OnMode, I_OnLoadModule, I_OnStats, I_OnEvent,
53                 I_OnSetAway, I_OnPostCommand, I_OnUserConnect
54         };
55         ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
56
57         delete ServerInstance->PI;
58         ServerInstance->PI = new SpanningTreeProtocolInterface(this, Utils);
59         loopCall = false;
60
61         // update our local user count
62         Utils->TreeRoot->SetUserCount(ServerInstance->Users->local_users.size());
63 }
64
65 void ModuleSpanningTree::ShowLinks(TreeServer* Current, User* user, int hops)
66 {
67         std::string Parent = Utils->TreeRoot->GetName();
68         if (Current->GetParent())
69         {
70                 Parent = Current->GetParent()->GetName();
71         }
72         for (unsigned int q = 0; q < Current->ChildCount(); q++)
73         {
74                 if ((Current->GetChild(q)->Hidden) || ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str()))))
75                 {
76                         if (IS_OPER(user))
77                         {
78                                  ShowLinks(Current->GetChild(q),user,hops+1);
79                         }
80                 }
81                 else
82                 {
83                         ShowLinks(Current->GetChild(q),user,hops+1);
84                 }
85         }
86         /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
87         if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetName().c_str())) && (!IS_OPER(user)))
88                 return;
89         /* Or if the server is hidden and they're not an oper */
90         else if ((Current->Hidden) && (!IS_OPER(user)))
91                 return;
92
93         user->WriteNumeric(364, "%s %s %s :%d %s",      user->nick.c_str(),Current->GetName().c_str(),
94                         (Utils->FlatLinks && (!IS_OPER(user))) ? ServerInstance->Config->ServerName : Parent.c_str(),
95                         (Utils->FlatLinks && (!IS_OPER(user))) ? 0 : hops,
96                         Current->GetDesc().c_str());
97 }
98
99 int ModuleSpanningTree::CountLocalServs()
100 {
101         return Utils->TreeRoot->ChildCount();
102 }
103
104 int ModuleSpanningTree::CountServs()
105 {
106         return Utils->serverlist.size();
107 }
108
109 void ModuleSpanningTree::HandleLinks(const std::vector<std::string>& parameters, User* user)
110 {
111         ShowLinks(Utils->TreeRoot,user,0);
112         user->WriteNumeric(365, "%s * :End of /LINKS list.",user->nick.c_str());
113         return;
114 }
115
116 void ModuleSpanningTree::HandleLusers(const std::vector<std::string>& parameters, User* user)
117 {
118         unsigned int n_users = ServerInstance->Users->UserCount();
119
120         /* Only update these when someone wants to see them, more efficient */
121         if ((unsigned int)ServerInstance->Users->LocalUserCount() > max_local)
122                 max_local = ServerInstance->Users->LocalUserCount();
123         if (n_users > max_global)
124                 max_global = n_users;
125
126         unsigned int ulined_count = 0;
127         unsigned int ulined_local_count = 0;
128
129         /* If ulined are hidden and we're not an oper, count the number of ulined servers hidden,
130          * locally and globally (locally means directly connected to us)
131          */
132         if ((Utils->HideULines) && (!IS_OPER(user)))
133         {
134                 for (server_hash::iterator q = Utils->serverlist.begin(); q != Utils->serverlist.end(); q++)
135                 {
136                         if (ServerInstance->ULine(q->second->GetName().c_str()))
137                         {
138                                 ulined_count++;
139                                 if (q->second->GetParent() == Utils->TreeRoot)
140                                         ulined_local_count++;
141                         }
142                 }
143         }
144         user->WriteNumeric(251, "%s :There are %d users and %d invisible on %d servers",user->nick.c_str(),
145                         n_users-ServerInstance->Users->ModeCount('i'),
146                         ServerInstance->Users->ModeCount('i'),
147                         ulined_count ? this->CountServs() - ulined_count : this->CountServs());
148
149         if (ServerInstance->Users->OperCount())
150                 user->WriteNumeric(252, "%s %d :operator(s) online",user->nick.c_str(),ServerInstance->Users->OperCount());
151
152         if (ServerInstance->Users->UnregisteredUserCount())
153                 user->WriteNumeric(253, "%s %d :unknown connections",user->nick.c_str(),ServerInstance->Users->UnregisteredUserCount());
154
155         if (ServerInstance->ChannelCount())
156                 user->WriteNumeric(254, "%s %ld :channels formed",user->nick.c_str(),ServerInstance->ChannelCount());
157
158         user->WriteNumeric(255, "%s :I have %d clients and %d servers",user->nick.c_str(),ServerInstance->Users->LocalUserCount(),ulined_local_count ? this->CountLocalServs() - ulined_local_count : this->CountLocalServs());
159         user->WriteNumeric(265, "%s :Current Local Users: %d  Max: %d",user->nick.c_str(),ServerInstance->Users->LocalUserCount(),max_local);
160         user->WriteNumeric(266, "%s :Current Global Users: %d  Max: %d",user->nick.c_str(),n_users,max_global);
161         return;
162 }
163
164 std::string ModuleSpanningTree::TimeToStr(time_t secs)
165 {
166         time_t mins_up = secs / 60;
167         time_t hours_up = mins_up / 60;
168         time_t days_up = hours_up / 24;
169         secs = secs % 60;
170         mins_up = mins_up % 60;
171         hours_up = hours_up % 24;
172         return ((days_up ? (ConvToStr(days_up) + "d") : std::string(""))
173                         + (hours_up ? (ConvToStr(hours_up) + "h") : std::string(""))
174                         + (mins_up ? (ConvToStr(mins_up) + "m") : std::string(""))
175                         + ConvToStr(secs) + "s");
176 }
177
178 void ModuleSpanningTree::DoPingChecks(time_t curtime)
179 {
180         /*
181          * Cancel remote burst mode on any servers which still have it enabled due to latency/lack of data.
182          * This prevents lost REMOTECONNECT notices
183          */
184         timeval t;
185         gettimeofday(&t, NULL);
186         long ts = (t.tv_sec * 1000) + (t.tv_usec / 1000);
187
188         for (server_hash::iterator i = Utils->serverlist.begin(); i != Utils->serverlist.end(); i++)
189         {
190                 TreeServer *s = i->second;
191
192                 // Fix for bug #792, do not ping servers that are not connected yet!
193                 // Remote servers have Socket == NULL and local connected servers have
194                 // Socket->LinkState == CONNECTED
195                 if (s->GetSocket() && s->GetSocket()->GetLinkState() != CONNECTED)
196                         continue;
197
198                 // Now do PING checks on all servers
199                 TreeServer *mts = Utils->BestRouteTo(s->GetID());
200
201                 if (mts)
202                 {
203                         // Only ping if this server needs one
204                         if (curtime >= s->NextPingTime())
205                         {
206                                 // And if they answered the last
207                                 if (s->AnsweredLastPing())
208                                 {
209                                         // They did, send a ping to them
210                                         s->SetNextPingTime(curtime + Utils->PingFreq);
211                                         TreeSocket *tsock = mts->GetSocket();
212
213                                         // ... if we can find a proper route to them
214                                         if (tsock)
215                                         {
216                                                 tsock->WriteLine(std::string(":") + ServerInstance->Config->GetSID() + " PING " +
217                                                                 ServerInstance->Config->GetSID() + " " + s->GetID());
218                                                 s->LastPingMsec = ts;
219                                         }
220                                 }
221                                 else
222                                 {
223                                         // They didn't answer the last ping, if they are locally connected, get rid of them.
224                                         TreeSocket *sock = s->GetSocket();
225                                         if (sock)
226                                         {
227                                                 sock->SendError("Ping timeout");
228                                                 sock->Squit(s,"Ping timeout");
229                                                 ServerInstance->SE->DelFd(sock);
230                                                 sock->Close();
231                                                 return;
232                                         }
233                                 }
234                         }
235
236                         // If warn on ping enabled and not warned and the difference is sufficient and they didn't answer the last ping...
237                         if ((Utils->PingWarnTime) && (!s->Warned) && (curtime >= s->NextPingTime() - (Utils->PingFreq - Utils->PingWarnTime)) && (!s->AnsweredLastPing()))
238                         {
239                                 /* The server hasnt responded, send a warning to opers */
240                                 ServerInstance->SNO->WriteToSnoMask('l',"Server \002%s\002 has not responded to PING for %d seconds, high latency.", s->GetName().c_str(), Utils->PingWarnTime);
241                                 s->Warned = true;
242                         }
243                 }
244         }
245 }
246
247 void ModuleSpanningTree::ConnectServer(Autoconnect* y)
248 {
249         if (!y)
250                 return;
251         y->position++;
252         while (y->position < (int)y->servers.size())
253         {
254                 Link* x = Utils->FindLink(y->servers[y->position]);
255                 if (x)
256                 {
257                         ServerInstance->SNO->WriteToSnoMask('l', "AUTOCONNECT: Auto-connecting server \002%s\002", x->Name.c_str());
258                         ConnectServer(x, y);
259                         return;
260                 }
261                 y->position++;
262         }
263         // Autoconnect chain has been fully iterated; start at the beginning on the
264         // next AutoConnectServers run
265         y->position = -1;
266 }
267
268 void ModuleSpanningTree::ConnectServer(Link* x, Autoconnect* y)
269 {
270         bool ipvalid = true;
271
272         if (InspIRCd::Match(ServerInstance->Config->ServerName, assign(x->Name)))
273         {
274                 ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Not connecting to myself.");
275                 return;
276         }
277
278         QueryType start_type = DNS_QUERY_A;
279         start_type = DNS_QUERY_AAAA;
280         if (strchr(x->IPAddr.c_str(),':'))
281         {
282                 in6_addr n;
283                 if (inet_pton(AF_INET6, x->IPAddr.c_str(), &n) < 1)
284                         ipvalid = false;
285         }
286         else
287         {
288                 in_addr n;
289                 if (inet_aton(x->IPAddr.c_str(),&n) < 1)
290                         ipvalid = false;
291         }
292
293         /* Do we already have an IP? If so, no need to resolve it. */
294         if (ipvalid)
295         {
296                 /* Gave a hook, but it wasnt one we know */
297                 if ((!x->Hook.empty()) && (Utils->hooks.find(x->Hook.c_str()) == Utils->hooks.end()))
298                         return;
299                 TreeSocket* newsocket = new TreeSocket(Utils, x->IPAddr,x->Port, x->Timeout ? x->Timeout : 10,x->Name.c_str(), x->Bind, y, x->Hook.empty() ? NULL : Utils->hooks[x->Hook.c_str()]);
300                 if (newsocket->GetFd() > -1)
301                 {
302                         /* Handled automatically on success */
303                 }
304                 else
305                 {
306                         ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
307                         ServerInstance->GlobalCulls.AddItem(newsocket);
308                         ConnectServer(y);
309                 }
310         }
311         else
312         {
313                 try
314                 {
315                         bool cached;
316                         ServernameResolver* snr = new ServernameResolver((Module*)this, Utils, x->IPAddr, x, cached, start_type, y);
317                         ServerInstance->AddResolver(snr, cached);
318                 }
319                 catch (ModuleException& e)
320                 {
321                         ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(), e.GetReason());
322                         ConnectServer(y);
323                 }
324         }
325 }
326
327 void ModuleSpanningTree::AutoConnectServers(time_t curtime)
328 {
329         for (std::vector<reference<Autoconnect> >::iterator i = Utils->AutoconnectBlocks.begin(); i < Utils->AutoconnectBlocks.end(); ++i)
330         {
331                 Autoconnect* x = *i;
332                 if (curtime >= x->NextConnectTime)
333                 {
334                         x->NextConnectTime = curtime + x->Period;
335                         for(unsigned int j=0; j < x->servers.size(); j++)
336                         {
337                                 if (Utils->FindServer(x->servers[j]))
338                                 {
339                                         // found something in this block. Should the server fail,
340                                         // we want to start at the start of the list, not in the
341                                         // middle where we left off
342                                         x->position = -1;
343                                         goto dupe_found; // next autoconnect block
344                                 }
345                         }
346                         // only start a new chain if we aren't running
347                         if (x->position == -1)
348                                 ConnectServer(x);
349                 }
350 dupe_found:;
351         }
352 }
353
354 void ModuleSpanningTree::DoConnectTimeout(time_t curtime)
355 {
356         std::vector<Autoconnect*> failovers;
357         std::map<TreeSocket*, std::pair<std::string, int> >::iterator i = Utils->timeoutlist.begin();
358         while (i != Utils->timeoutlist.end())
359         {
360                 TreeSocket* s = i->first;
361                 std::pair<std::string, int> p = i->second;
362                 std::map<TreeSocket*, std::pair<std::string, int> >::iterator me = i;
363                 i++;
364                 if (curtime > s->age + p.second)
365                 {
366                         ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002 (timeout of %d seconds)",p.first.c_str(),p.second);
367                         if (s->myautoconnect)
368                                 failovers.push_back(s->myautoconnect);
369                         Utils->timeoutlist.erase(me);
370                         s->Close();
371                 }
372         }
373         for(unsigned int j=0; j < failovers.size(); j++)
374         {
375                 if (failovers[j]->position >= 0)
376                         ConnectServer(failovers[j]);
377         }
378 }
379
380 ModResult ModuleSpanningTree::HandleVersion(const std::vector<std::string>& parameters, User* user)
381 {
382         // we've already checked if pcnt > 0, so this is safe
383         TreeServer* found = Utils->FindServerMask(parameters[0]);
384         if (found)
385         {
386                 std::string Version = found->GetVersion();
387                 user->WriteNumeric(351, "%s :%s",user->nick.c_str(),Version.c_str());
388                 if (found == Utils->TreeRoot)
389                 {
390                         ServerInstance->Config->Send005(user);
391                 }
392         }
393         else
394         {
395                 user->WriteNumeric(402, "%s %s :No such server",user->nick.c_str(),parameters[0].c_str());
396         }
397         return MOD_RES_DENY;
398 }
399
400 /* This method will attempt to get a message to a remote user.
401  */
402 void ModuleSpanningTree::RemoteMessage(User* user, const char* format, ...)
403 {
404         char text[MAXBUF];
405         va_list argsPtr;
406
407         va_start(argsPtr, format);
408         vsnprintf(text, MAXBUF, format, argsPtr);
409         va_end(argsPtr);
410
411         if (IS_LOCAL(user))
412                 user->WriteServ("NOTICE %s :%s", user->nick.c_str(), text);
413         else
414                 ServerInstance->PI->SendUserNotice(user, text);
415 }
416
417 ModResult ModuleSpanningTree::HandleConnect(const std::vector<std::string>& parameters, User* user)
418 {
419         for (std::vector<reference<Link> >::iterator i = Utils->LinkBlocks.begin(); i < Utils->LinkBlocks.end(); i++)
420         {
421                 Link* x = *i;
422                 if (InspIRCd::Match(x->Name.c_str(),parameters[0]))
423                 {
424                         if (InspIRCd::Match(ServerInstance->Config->ServerName, assign(x->Name)))
425                         {
426                                 RemoteMessage(user, "*** CONNECT: Server \002%s\002 is ME, not connecting.",x->Name.c_str());
427                                 return MOD_RES_DENY;
428                         }
429
430                         TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
431                         if (!CheckDupe)
432                         {
433                                 RemoteMessage(user, "*** CONNECT: Connecting to server: \002%s\002 (%s:%d)",x->Name.c_str(),(x->HiddenFromStats ? "<hidden>" : x->IPAddr.c_str()),x->Port);
434                                 ConnectServer(x);
435                                 return MOD_RES_DENY;
436                         }
437                         else
438                         {
439                                 RemoteMessage(user, "*** CONNECT: Server \002%s\002 already exists on the network and is connected via \002%s\002",x->Name.c_str(),CheckDupe->GetParent()->GetName().c_str());
440                                 return MOD_RES_DENY;
441                         }
442                 }
443         }
444         RemoteMessage(user, "*** CONNECT: No server matching \002%s\002 could be found in the config file.",parameters[0].c_str());
445         return MOD_RES_DENY;
446 }
447
448 void ModuleSpanningTree::OnGetServerDescription(const std::string &servername,std::string &description)
449 {
450         TreeServer* s = Utils->FindServer(servername);
451         if (s)
452         {
453                 description = s->GetDesc();
454         }
455 }
456
457 void ModuleSpanningTree::OnUserInvite(User* source,User* dest,Channel* channel, time_t expiry)
458 {
459         if (IS_LOCAL(source))
460         {
461                 parameterlist params;
462                 params.push_back(dest->uuid);
463                 params.push_back(channel->name);
464                 params.push_back(ConvToStr(expiry));
465                 Utils->DoOneToMany(source->uuid,"INVITE",params);
466         }
467 }
468
469 void ModuleSpanningTree::OnPostTopicChange(User* user, Channel* chan, const std::string &topic)
470 {
471         // Drop remote events on the floor.
472         if (!IS_LOCAL(user))
473                 return;
474
475         parameterlist params;
476         params.push_back(chan->name);
477         params.push_back(":"+topic);
478         Utils->DoOneToMany(user->uuid,"TOPIC",params);
479 }
480
481 void ModuleSpanningTree::OnWallops(User* user, const std::string &text)
482 {
483         if (IS_LOCAL(user))
484         {
485                 parameterlist params;
486                 params.push_back(":"+text);
487                 Utils->DoOneToMany(user->uuid,"WALLOPS",params);
488         }
489 }
490
491 void ModuleSpanningTree::OnUserNotice(User* user, void* dest, int target_type, const std::string &text, char status, const CUList &exempt_list)
492 {
493         /* Server origin */
494         if (user == NULL)
495                 return;
496
497         if (target_type == TYPE_USER)
498         {
499                 User* d = (User*)dest;
500                 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
501                 {
502                         parameterlist params;
503                         params.push_back(d->uuid);
504                         params.push_back(":"+text);
505                         Utils->DoOneToOne(user->uuid,"NOTICE",params,d->server);
506                 }
507         }
508         else if (target_type == TYPE_CHANNEL)
509         {
510                 if (IS_LOCAL(user))
511                 {
512                         Channel *c = (Channel*)dest;
513                         if (c)
514                         {
515                                 std::string cname = c->name;
516                                 if (status)
517                                         cname = status + cname;
518                                 TreeServerList list;
519                                 Utils->GetListOfServersForChannel(c,list,status,exempt_list);
520                                 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
521                                 {
522                                         TreeSocket* Sock = i->second->GetSocket();
523                                         if (Sock)
524                                                 Sock->WriteLine(":"+std::string(user->uuid)+" NOTICE "+cname+" :"+text);
525                                 }
526                         }
527                 }
528         }
529         else if (target_type == TYPE_SERVER)
530         {
531                 if (IS_LOCAL(user))
532                 {
533                         char* target = (char*)dest;
534                         parameterlist par;
535                         par.push_back(target);
536                         par.push_back(":"+text);
537                         Utils->DoOneToMany(user->uuid,"NOTICE",par);
538                 }
539         }
540 }
541
542 void ModuleSpanningTree::OnUserMessage(User* user, void* dest, int target_type, const std::string &text, char status, const CUList &exempt_list)
543 {
544         /* Server origin */
545         if (user == NULL)
546                 return;
547
548         if (target_type == TYPE_USER)
549         {
550                 // route private messages which are targetted at clients only to the server
551                 // which needs to receive them
552                 User* d = (User*)dest;
553                 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
554                 {
555                         parameterlist params;
556                         params.push_back(d->uuid);
557                         params.push_back(":"+text);
558                         Utils->DoOneToOne(user->uuid,"PRIVMSG",params,d->server);
559                 }
560         }
561         else if (target_type == TYPE_CHANNEL)
562         {
563                 if (IS_LOCAL(user))
564                 {
565                         Channel *c = (Channel*)dest;
566                         if (c)
567                         {
568                                 std::string cname = c->name;
569                                 if (status)
570                                         cname = status + cname;
571                                 TreeServerList list;
572                                 Utils->GetListOfServersForChannel(c,list,status,exempt_list);
573                                 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
574                                 {
575                                         TreeSocket* Sock = i->second->GetSocket();
576                                         if (Sock)
577                                                 Sock->WriteLine(":"+std::string(user->uuid)+" PRIVMSG "+cname+" :"+text);
578                                 }
579                         }
580                 }
581         }
582         else if (target_type == TYPE_SERVER)
583         {
584                 if (IS_LOCAL(user))
585                 {
586                         char* target = (char*)dest;
587                         parameterlist par;
588                         par.push_back(target);
589                         par.push_back(":"+text);
590                         Utils->DoOneToMany(user->uuid,"PRIVMSG",par);
591                 }
592         }
593 }
594
595 void ModuleSpanningTree::OnBackgroundTimer(time_t curtime)
596 {
597         AutoConnectServers(curtime);
598         DoPingChecks(curtime);
599         DoConnectTimeout(curtime);
600 }
601
602 void ModuleSpanningTree::OnUserConnect(User* user)
603 {
604         if (user->quitting)
605                 return;
606
607         parameterlist params;
608         params.push_back(user->uuid);
609         params.push_back(ConvToStr(user->age));
610         params.push_back(user->nick);
611         params.push_back(user->host);
612         params.push_back(user->dhost);
613         params.push_back(user->ident);
614         params.push_back(user->GetIPString());
615         params.push_back(ConvToStr(user->signon));
616         params.push_back("+"+std::string(user->FormatModes(true)));
617         params.push_back(":"+std::string(user->fullname));
618         Utils->DoOneToMany(ServerInstance->Config->GetSID(), "UID", params);
619
620         Utils->TreeRoot->SetUserCount(1); // increment by 1
621 }
622
623 void ModuleSpanningTree::OnUserJoin(Membership* memb, bool sync, bool created, CUList& excepts)
624 {
625         // Only do this for local users
626         if (IS_LOCAL(memb->user))
627         {
628                 parameterlist params;
629                 // set up their permissions and the channel TS with FJOIN.
630                 // All users are FJOINed now, because a module may specify
631                 // new joining permissions for the user.
632                 params.push_back(memb->chan->name);
633                 params.push_back(ConvToStr(memb->chan->age));
634                 params.push_back(std::string("+") + memb->chan->ChanModes(true));
635                 params.push_back(memb->modes+","+std::string(memb->user->uuid));
636                 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"FJOIN",params);
637         }
638 }
639
640 ModResult ModuleSpanningTree::OnChangeLocalUserHost(User* user, const std::string &newhost)
641 {
642         if (user->registered != REG_ALL)
643                 return MOD_RES_PASSTHRU;
644
645         parameterlist params;
646         params.push_back(newhost);
647         Utils->DoOneToMany(user->uuid,"FHOST",params);
648         return MOD_RES_PASSTHRU;
649 }
650
651 void ModuleSpanningTree::OnChangeName(User* user, const std::string &gecos)
652 {
653         // only occurs for local clients
654         if (user->registered != REG_ALL)
655                 return;
656
657         parameterlist params;
658         params.push_back(gecos);
659         Utils->DoOneToMany(user->uuid,"FNAME",params);
660 }
661
662 void ModuleSpanningTree::OnChangeIdent(User* user, const std::string &ident)
663 {
664         // only occurs for local clients
665         if (user->registered != REG_ALL)
666                 return;
667
668         parameterlist params;
669         params.push_back(ident);
670         Utils->DoOneToMany(user->uuid,"FIDENT",params);
671 }
672
673 void ModuleSpanningTree::OnUserPart(Membership* memb, std::string &partmessage, CUList& excepts)
674 {
675         if (IS_LOCAL(memb->user))
676         {
677                 parameterlist params;
678                 params.push_back(memb->chan->name);
679                 if (!partmessage.empty())
680                         params.push_back(":"+partmessage);
681                 Utils->DoOneToMany(memb->user->uuid,"PART",params);
682         }
683 }
684
685 void ModuleSpanningTree::OnUserQuit(User* user, const std::string &reason, const std::string &oper_message)
686 {
687         if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
688         {
689                 parameterlist params;
690
691                 if (oper_message != reason)
692                 {
693                         params.push_back(":"+oper_message);
694                         Utils->DoOneToMany(user->uuid,"OPERQUIT",params);
695                 }
696                 params.clear();
697                 params.push_back(":"+reason);
698                 Utils->DoOneToMany(user->uuid,"QUIT",params);
699         }
700
701         // Regardless, We need to modify the user Counts..
702         TreeServer* SourceServer = Utils->FindServer(user->server);
703         if (SourceServer)
704         {
705                 SourceServer->SetUserCount(-1); // decrement by 1
706         }
707 }
708
709 void ModuleSpanningTree::OnUserPostNick(User* user, const std::string &oldnick)
710 {
711         if (IS_LOCAL(user))
712         {
713                 parameterlist params;
714                 params.push_back(user->nick);
715
716                 /** IMPORTANT: We don't update the TS if the oldnick is just a case change of the newnick!
717                  */
718                 if (irc::string(user->nick.c_str()) != assign(oldnick))
719                         user->age = ServerInstance->Time();
720
721                 params.push_back(ConvToStr(user->age));
722                 Utils->DoOneToMany(user->uuid,"NICK",params);
723         }
724         else if (!loopCall && user->nick == user->uuid)
725         {
726                 parameterlist params;
727                 params.push_back(user->uuid);
728                 params.push_back(ConvToStr(user->age));
729                 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"SAVE",params);
730         }
731 }
732
733 void ModuleSpanningTree::OnUserKick(User* source, Membership* memb, const std::string &reason, CUList& excepts)
734 {
735         parameterlist params;
736         params.push_back(memb->chan->name);
737         params.push_back(memb->user->uuid);
738         params.push_back(":"+reason);
739         if (IS_LOCAL(source))
740         {
741                 Utils->DoOneToMany(source->uuid,"KICK",params);
742         }
743         else if (IS_SERVER(source) && source != Utils->ServerUser)
744         {
745                 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"KICK",params);
746         }
747 }
748
749 void ModuleSpanningTree::OnRemoteKill(User* source, User* dest, const std::string &reason, const std::string &operreason)
750 {
751         if (!IS_LOCAL(source))
752                 return; // Only start routing if we're origin.
753
754         User::OperQuit.set(dest, operreason);
755         parameterlist params;
756         params.push_back(":"+operreason);
757         Utils->DoOneToMany(dest->uuid,"OPERQUIT",params);
758         params.clear();
759         params.push_back(dest->uuid);
760         params.push_back(":"+reason);
761         Utils->DoOneToMany(source->uuid,"KILL",params);
762 }
763
764 void ModuleSpanningTree::OnPreRehash(User* user, const std::string &parameter)
765 {
766         ServerInstance->Logs->Log("remoterehash", DEBUG, "called with param %s", parameter.c_str());
767
768         // Send out to other servers
769         if (!parameter.empty() && parameter[0] != '-')
770         {
771                 parameterlist params;
772                 params.push_back(parameter);
773                 Utils->DoOneToAllButSender(user ? user->uuid : ServerInstance->Config->GetSID(), "REHASH", params, user ? user->server : ServerInstance->Config->ServerName);
774         }
775 }
776
777 void ModuleSpanningTree::OnRehash(User* user)
778 {
779         // Re-read config stuff
780         Utils->ReadConfiguration(true);
781 }
782
783 void ModuleSpanningTree::OnLoadModule(Module* mod, const std::string &name)
784 {
785         this->RedoConfig(mod, name);
786 }
787
788 void ModuleSpanningTree::OnUnloadModule(Module* mod, const std::string &name)
789 {
790         this->RedoConfig(mod, name);
791 }
792
793 void ModuleSpanningTree::RedoConfig(Module* mod, const std::string &name)
794 {
795         /* If m_sha256.so is loaded (we use this for HMAC) or any module implementing a BufferedSocket interface is loaded,
796          * then we need to re-read our config again taking this into account.
797          */
798         modulelist* ml = ServerInstance->Modules->FindInterface("BufferedSocketHook");
799         bool IsBufferSocketModule = false;
800
801         /* Did we find any modules? */
802         if (ml && std::find(ml->begin(), ml->end(), mod) != ml->end())
803                 IsBufferSocketModule = true;
804
805         if (name == "m_sha256.so" || IsBufferSocketModule)
806         {
807                 Utils->ReadConfiguration(true);
808         }
809 }
810
811 // note: the protocol does not allow direct umode +o except
812 // via NICK with 8 params. sending OPERTYPE infers +o modechange
813 // locally.
814 void ModuleSpanningTree::OnOper(User* user, const std::string &opertype)
815 {
816         if (IS_LOCAL(user))
817         {
818                 parameterlist params;
819                 params.push_back(opertype);
820                 Utils->DoOneToMany(user->uuid,"OPERTYPE",params);
821         }
822 }
823
824 void ModuleSpanningTree::OnAddLine(User* user, XLine *x)
825 {
826         if (!x->IsBurstable() || loopCall)
827                 return;
828
829         char data[MAXBUF];
830         snprintf(data,MAXBUF,"%s %s %s %lu %lu :%s", x->type.c_str(), x->Displayable(),
831         ServerInstance->Config->ServerName, (unsigned long)x->set_time, (unsigned long)x->duration, x->reason.c_str());
832         parameterlist params;
833         params.push_back(data);
834
835         if (!user)
836         {
837                 /* Server-set lines */
838                 Utils->DoOneToMany(ServerInstance->Config->GetSID(), "ADDLINE", params);
839         }
840         else if (IS_LOCAL(user))
841         {
842                 /* User-set lines */
843                 Utils->DoOneToMany(user->uuid, "ADDLINE", params);
844         }
845 }
846
847 void ModuleSpanningTree::OnDelLine(User* user, XLine *x)
848 {
849         if (x->type == "K")
850                 return;
851
852         char data[MAXBUF];
853         snprintf(data,MAXBUF,"%s %s", x->type.c_str(), x->Displayable());
854         parameterlist params;
855         params.push_back(data);
856
857         if (!user)
858         {
859                 /* Server-unset lines */
860                 Utils->DoOneToMany(ServerInstance->Config->GetSID(), "DELLINE", params);
861         }
862         else if (IS_LOCAL(user))
863         {
864                 /* User-unset lines */
865                 Utils->DoOneToMany(user->uuid, "DELLINE", params);
866         }
867 }
868
869 void ModuleSpanningTree::OnMode(User* user, void* dest, int target_type, const parameterlist &text, const std::vector<TranslateType> &translate)
870 {
871         if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
872         {
873                 parameterlist params;
874                 std::string command;
875                 std::string output_text;
876
877                 ServerInstance->Parser->TranslateUIDs(translate, text, output_text);
878
879                 if (target_type == TYPE_USER)
880                 {
881                         User* u = (User*)dest;
882                         params.push_back(u->uuid);
883                         params.push_back(output_text);
884                         command = "MODE";
885                 }
886                 else
887                 {
888                         Channel* c = (Channel*)dest;
889                         params.push_back(c->name);
890                         params.push_back(ConvToStr(c->age));
891                         params.push_back(output_text);
892                         command = "FMODE";
893                 }
894
895                 Utils->DoOneToMany(user->uuid, command, params);
896         }
897 }
898
899 ModResult ModuleSpanningTree::OnSetAway(User* user, const std::string &awaymsg)
900 {
901         if (IS_LOCAL(user))
902         {
903                 if (awaymsg.empty())
904                 {
905                         parameterlist params;
906                         Utils->DoOneToMany(user->uuid,"AWAY",params);
907                 }
908                 else
909                 {
910                         parameterlist params;
911                         params.push_back(ConvToStr(user->awaytime));
912                         params.push_back(":" + awaymsg);
913                         Utils->DoOneToMany(user->uuid,"AWAY",params);
914                 }
915         }
916
917         return MOD_RES_PASSTHRU;
918 }
919
920 void ModuleSpanningTree::ProtoSendMode(void* opaque, TargetTypeFlags target_type, void* target, const parameterlist &modeline, const std::vector<TranslateType> &translate)
921 {
922         TreeSocket* s = (TreeSocket*)opaque;
923         std::string output_text;
924
925         ServerInstance->Parser->TranslateUIDs(translate, modeline, output_text);
926
927         if (target)
928         {
929                 if (target_type == TYPE_USER)
930                 {
931                         User* u = (User*)target;
932                         s->WriteLine(std::string(":")+ServerInstance->Config->GetSID()+" MODE "+u->uuid+" "+output_text);
933                 }
934                 else if (target_type == TYPE_CHANNEL)
935                 {
936                         Channel* c = (Channel*)target;
937                         s->WriteLine(std::string(":")+ServerInstance->Config->GetSID()+" FMODE "+c->name+" "+ConvToStr(c->age)+" "+output_text);
938                 }
939         }
940 }
941
942 void ModuleSpanningTree::ProtoSendMetaData(void* opaque, Extensible* target, const std::string &extname, const std::string &extdata)
943 {
944         TreeSocket* s = static_cast<TreeSocket*>(opaque);
945         User* u = dynamic_cast<User*>(target);
946         Channel* c = dynamic_cast<Channel*>(target);
947         if (u)
948                 s->WriteLine(std::string(":")+ServerInstance->Config->GetSID()+" METADATA "+u->uuid+" "+extname+" :"+extdata);
949         else if (c)
950                 s->WriteLine(std::string(":")+ServerInstance->Config->GetSID()+" METADATA "+c->name+" "+extname+" :"+extdata);
951         else if (!target)
952                 s->WriteLine(std::string(":")+ServerInstance->Config->GetSID()+" METADATA * "+extname+" :"+extdata);
953 }
954
955 void ModuleSpanningTree::OnEvent(Event* event)
956 {
957         if ((event->GetEventID() == "send_encap") || (event->GetEventID() == "send_metadata") || (event->GetEventID() == "send_topic") || (event->GetEventID() == "send_mode") || (event->GetEventID() == "send_mode_explicit") || (event->GetEventID() == "send_opers")
958                 || (event->GetEventID() == "send_modeset") || (event->GetEventID() == "send_snoset") || (event->GetEventID() == "send_push"))
959         {
960                 ServerInstance->Logs->Log("m_spanningtree", DEBUG, "WARNING: Deprecated use of old 1.1 style m_spanningtree event ignored, type '"+event->GetEventID()+"'!");
961         }
962 }
963
964 bool ModuleSpanningTree::cull()
965 {
966         return Utils->cull();
967 }
968
969 ModuleSpanningTree::~ModuleSpanningTree()
970 {
971         delete ServerInstance->PI;
972         ServerInstance->PI = new ProtocolInterface;
973
974         /* This will also free the listeners */
975         delete Utils;
976
977         delete command_rconnect;
978         delete command_rsquit;
979
980         ServerInstance->Timers->DelTimer(RefreshTimer);
981
982         ServerInstance->Modules->DoneWithInterface("BufferedSocketHook");
983 }
984
985 Version ModuleSpanningTree::GetVersion()
986 {
987         return Version("Allows servers to be linked", VF_VENDOR);
988 }
989
990 /* It is IMPORTANT that m_spanningtree is the last module in the chain
991  * so that any activity it sees is FINAL, e.g. we arent going to send out
992  * a NICK message before m_cloaking has finished putting the +x on the user,
993  * etc etc.
994  * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
995  * the module call queue.
996  */
997 void ModuleSpanningTree::Prioritize()
998 {
999         ServerInstance->Modules->SetPriority(this, PRIORITY_LAST);
1000 }
1001
1002 MODULE_INIT(ModuleSpanningTree)