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