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