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