]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/main.cpp
Make classbase and refcountbase uncopyable; expand comments on their indended uses
[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* a, bool on_timer)
247 {
248         if (!a)
249                 return;
250         for(unsigned int j=0; j < a->servers.size(); j++)
251         {
252                 if (Utils->FindServer(a->servers[j]))
253                 {
254                         // found something in this block. Should the server fail,
255                         // we want to start at the start of the list, not in the
256                         // middle where we left off
257                         a->position = -1;
258                         return;
259                 }
260         }
261         if (on_timer && a->position >= 0)
262                 return;
263         if (!on_timer && a->position < 0)
264                 return;
265
266         a->position++;
267         while (a->position < (int)a->servers.size())
268         {
269                 Link* x = Utils->FindLink(a->servers[a->position]);
270                 if (x)
271                 {
272                         ServerInstance->SNO->WriteToSnoMask('l', "AUTOCONNECT: Auto-connecting server \002%s\002", x->Name.c_str());
273                         ConnectServer(x, a);
274                         return;
275                 }
276                 a->position++;
277         }
278         // Autoconnect chain has been fully iterated; start at the beginning on the
279         // next AutoConnectServers run
280         a->position = -1;
281 }
282
283 void ModuleSpanningTree::ConnectServer(Link* x, Autoconnect* y)
284 {
285         bool ipvalid = true;
286
287         if (InspIRCd::Match(ServerInstance->Config->ServerName, assign(x->Name)))
288         {
289                 ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Not connecting to myself.");
290                 return;
291         }
292
293         QueryType start_type = DNS_QUERY_A;
294         start_type = DNS_QUERY_AAAA;
295         if (strchr(x->IPAddr.c_str(),':'))
296         {
297                 in6_addr n;
298                 if (inet_pton(AF_INET6, x->IPAddr.c_str(), &n) < 1)
299                         ipvalid = false;
300         }
301         else
302         {
303                 in_addr n;
304                 if (inet_aton(x->IPAddr.c_str(),&n) < 1)
305                         ipvalid = false;
306         }
307
308         /* Do we already have an IP? If so, no need to resolve it. */
309         if (ipvalid)
310         {
311                 /* Gave a hook, but it wasnt one we know */
312                 TreeSocket* newsocket = new TreeSocket(Utils, x->IPAddr, x->Port, x->Timeout ? x->Timeout : 10,
313                         x->Name.c_str(), x->Bind, y, x->Hook);
314                 if (newsocket->GetFd() > -1)
315                 {
316                         /* Handled automatically on success */
317                 }
318                 else
319                 {
320                         ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
321                         ServerInstance->GlobalCulls.AddItem(newsocket);
322                 }
323         }
324         else
325         {
326                 try
327                 {
328                         bool cached;
329                         ServernameResolver* snr = new ServernameResolver(Utils, x->IPAddr, x, cached, start_type, y);
330                         ServerInstance->AddResolver(snr, cached);
331                 }
332                 catch (ModuleException& e)
333                 {
334                         ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(), e.GetReason());
335                         ConnectServer(y, false);
336                 }
337         }
338 }
339
340 void ModuleSpanningTree::AutoConnectServers(time_t curtime)
341 {
342         for (std::vector<reference<Autoconnect> >::iterator i = Utils->AutoconnectBlocks.begin(); i < Utils->AutoconnectBlocks.end(); ++i)
343         {
344                 Autoconnect* x = *i;
345                 if (curtime >= x->NextConnectTime)
346                 {
347                         x->NextConnectTime = curtime + x->Period;
348                         ConnectServer(x, true);
349                 }
350         }
351 }
352
353 void ModuleSpanningTree::DoConnectTimeout(time_t curtime)
354 {
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                         Utils->timeoutlist.erase(me);
366                         s->Close();
367                         ServerInstance->GlobalCulls.AddItem(s);
368                 }
369         }
370 }
371
372 ModResult ModuleSpanningTree::HandleVersion(const std::vector<std::string>& parameters, User* user)
373 {
374         // we've already checked if pcnt > 0, so this is safe
375         TreeServer* found = Utils->FindServerMask(parameters[0]);
376         if (found)
377         {
378                 std::string Version = found->GetVersion();
379                 user->WriteNumeric(351, "%s :%s",user->nick.c_str(),Version.c_str());
380                 if (found == Utils->TreeRoot)
381                 {
382                         ServerInstance->Config->Send005(user);
383                 }
384         }
385         else
386         {
387                 user->WriteNumeric(402, "%s %s :No such server",user->nick.c_str(),parameters[0].c_str());
388         }
389         return MOD_RES_DENY;
390 }
391
392 /* This method will attempt to get a message to a remote user.
393  */
394 void ModuleSpanningTree::RemoteMessage(User* user, const char* format, ...)
395 {
396         char text[MAXBUF];
397         va_list argsPtr;
398
399         va_start(argsPtr, format);
400         vsnprintf(text, MAXBUF, format, argsPtr);
401         va_end(argsPtr);
402
403         if (IS_LOCAL(user))
404                 user->WriteServ("NOTICE %s :%s", user->nick.c_str(), text);
405         else
406                 ServerInstance->PI->SendUserNotice(user, text);
407 }
408
409 ModResult ModuleSpanningTree::HandleConnect(const std::vector<std::string>& parameters, User* user)
410 {
411         for (std::vector<reference<Link> >::iterator i = Utils->LinkBlocks.begin(); i < Utils->LinkBlocks.end(); i++)
412         {
413                 Link* x = *i;
414                 if (InspIRCd::Match(x->Name.c_str(),parameters[0]))
415                 {
416                         if (InspIRCd::Match(ServerInstance->Config->ServerName, assign(x->Name)))
417                         {
418                                 RemoteMessage(user, "*** CONNECT: Server \002%s\002 is ME, not connecting.",x->Name.c_str());
419                                 return MOD_RES_DENY;
420                         }
421
422                         TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
423                         if (!CheckDupe)
424                         {
425                                 RemoteMessage(user, "*** CONNECT: Connecting to server: \002%s\002 (%s:%d)",x->Name.c_str(),(x->HiddenFromStats ? "<hidden>" : x->IPAddr.c_str()),x->Port);
426                                 ConnectServer(x);
427                                 return MOD_RES_DENY;
428                         }
429                         else
430                         {
431                                 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());
432                                 return MOD_RES_DENY;
433                         }
434                 }
435         }
436         RemoteMessage(user, "*** CONNECT: No server matching \002%s\002 could be found in the config file.",parameters[0].c_str());
437         return MOD_RES_DENY;
438 }
439
440 void ModuleSpanningTree::OnGetServerDescription(const std::string &servername,std::string &description)
441 {
442         TreeServer* s = Utils->FindServer(servername);
443         if (s)
444         {
445                 description = s->GetDesc();
446         }
447 }
448
449 void ModuleSpanningTree::OnUserInvite(User* source,User* dest,Channel* channel, time_t expiry)
450 {
451         if (IS_LOCAL(source))
452         {
453                 parameterlist params;
454                 params.push_back(dest->uuid);
455                 params.push_back(channel->name);
456                 params.push_back(ConvToStr(expiry));
457                 Utils->DoOneToMany(source->uuid,"INVITE",params);
458         }
459 }
460
461 void ModuleSpanningTree::OnPostTopicChange(User* user, Channel* chan, const std::string &topic)
462 {
463         // Drop remote events on the floor.
464         if (!IS_LOCAL(user))
465                 return;
466
467         parameterlist params;
468         params.push_back(chan->name);
469         params.push_back(":"+topic);
470         Utils->DoOneToMany(user->uuid,"TOPIC",params);
471 }
472
473 void ModuleSpanningTree::OnWallops(User* user, const std::string &text)
474 {
475         if (IS_LOCAL(user))
476         {
477                 parameterlist params;
478                 params.push_back(":"+text);
479                 Utils->DoOneToMany(user->uuid,"WALLOPS",params);
480         }
481 }
482
483 void ModuleSpanningTree::OnUserNotice(User* user, void* dest, int target_type, const std::string &text, char status, const CUList &exempt_list)
484 {
485         /* Server origin */
486         if (user == NULL)
487                 return;
488
489         if (target_type == TYPE_USER)
490         {
491                 User* d = (User*)dest;
492                 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
493                 {
494                         parameterlist params;
495                         params.push_back(d->uuid);
496                         params.push_back(":"+text);
497                         Utils->DoOneToOne(user->uuid,"NOTICE",params,d->server);
498                 }
499         }
500         else if (target_type == TYPE_CHANNEL)
501         {
502                 if (IS_LOCAL(user))
503                 {
504                         Channel *c = (Channel*)dest;
505                         if (c)
506                         {
507                                 std::string cname = c->name;
508                                 if (status)
509                                         cname = status + cname;
510                                 TreeServerList list;
511                                 Utils->GetListOfServersForChannel(c,list,status,exempt_list);
512                                 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
513                                 {
514                                         TreeSocket* Sock = i->second->GetSocket();
515                                         if (Sock)
516                                                 Sock->WriteLine(":"+std::string(user->uuid)+" NOTICE "+cname+" :"+text);
517                                 }
518                         }
519                 }
520         }
521         else if (target_type == TYPE_SERVER)
522         {
523                 if (IS_LOCAL(user))
524                 {
525                         char* target = (char*)dest;
526                         parameterlist par;
527                         par.push_back(target);
528                         par.push_back(":"+text);
529                         Utils->DoOneToMany(user->uuid,"NOTICE",par);
530                 }
531         }
532 }
533
534 void ModuleSpanningTree::OnUserMessage(User* user, void* dest, int target_type, const std::string &text, char status, const CUList &exempt_list)
535 {
536         /* Server origin */
537         if (user == NULL)
538                 return;
539
540         if (target_type == TYPE_USER)
541         {
542                 // route private messages which are targetted at clients only to the server
543                 // which needs to receive them
544                 User* d = (User*)dest;
545                 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
546                 {
547                         parameterlist params;
548                         params.push_back(d->uuid);
549                         params.push_back(":"+text);
550                         Utils->DoOneToOne(user->uuid,"PRIVMSG",params,d->server);
551                 }
552         }
553         else if (target_type == TYPE_CHANNEL)
554         {
555                 if (IS_LOCAL(user))
556                 {
557                         Channel *c = (Channel*)dest;
558                         if (c)
559                         {
560                                 std::string cname = c->name;
561                                 if (status)
562                                         cname = status + cname;
563                                 TreeServerList list;
564                                 Utils->GetListOfServersForChannel(c,list,status,exempt_list);
565                                 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
566                                 {
567                                         TreeSocket* Sock = i->second->GetSocket();
568                                         if (Sock)
569                                                 Sock->WriteLine(":"+std::string(user->uuid)+" PRIVMSG "+cname+" :"+text);
570                                 }
571                         }
572                 }
573         }
574         else if (target_type == TYPE_SERVER)
575         {
576                 if (IS_LOCAL(user))
577                 {
578                         char* target = (char*)dest;
579                         parameterlist par;
580                         par.push_back(target);
581                         par.push_back(":"+text);
582                         Utils->DoOneToMany(user->uuid,"PRIVMSG",par);
583                 }
584         }
585 }
586
587 void ModuleSpanningTree::OnBackgroundTimer(time_t curtime)
588 {
589         AutoConnectServers(curtime);
590         DoPingChecks(curtime);
591         DoConnectTimeout(curtime);
592 }
593
594 void ModuleSpanningTree::OnUserConnect(User* user)
595 {
596         if (user->quitting)
597                 return;
598
599         parameterlist params;
600         params.push_back(user->uuid);
601         params.push_back(ConvToStr(user->age));
602         params.push_back(user->nick);
603         params.push_back(user->host);
604         params.push_back(user->dhost);
605         params.push_back(user->ident);
606         params.push_back(user->GetIPString());
607         params.push_back(ConvToStr(user->signon));
608         params.push_back("+"+std::string(user->FormatModes(true)));
609         params.push_back(":"+std::string(user->fullname));
610         Utils->DoOneToMany(ServerInstance->Config->GetSID(), "UID", params);
611
612         Utils->TreeRoot->SetUserCount(1); // increment by 1
613 }
614
615 void ModuleSpanningTree::OnUserJoin(Membership* memb, bool sync, bool created, CUList& excepts)
616 {
617         // Only do this for local users
618         if (IS_LOCAL(memb->user))
619         {
620                 parameterlist params;
621                 // set up their permissions and the channel TS with FJOIN.
622                 // All users are FJOINed now, because a module may specify
623                 // new joining permissions for the user.
624                 params.push_back(memb->chan->name);
625                 params.push_back(ConvToStr(memb->chan->age));
626                 params.push_back(std::string("+") + memb->chan->ChanModes(true));
627                 params.push_back(memb->modes+","+std::string(memb->user->uuid));
628                 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"FJOIN",params);
629         }
630 }
631
632 ModResult ModuleSpanningTree::OnChangeLocalUserHost(User* user, const std::string &newhost)
633 {
634         if (user->registered != REG_ALL)
635                 return MOD_RES_PASSTHRU;
636
637         parameterlist params;
638         params.push_back(newhost);
639         Utils->DoOneToMany(user->uuid,"FHOST",params);
640         return MOD_RES_PASSTHRU;
641 }
642
643 void ModuleSpanningTree::OnChangeName(User* user, const std::string &gecos)
644 {
645         // only occurs for local clients
646         if (user->registered != REG_ALL)
647                 return;
648
649         parameterlist params;
650         params.push_back(gecos);
651         Utils->DoOneToMany(user->uuid,"FNAME",params);
652 }
653
654 void ModuleSpanningTree::OnChangeIdent(User* user, const std::string &ident)
655 {
656         // only occurs for local clients
657         if (user->registered != REG_ALL)
658                 return;
659
660         parameterlist params;
661         params.push_back(ident);
662         Utils->DoOneToMany(user->uuid,"FIDENT",params);
663 }
664
665 void ModuleSpanningTree::OnUserPart(Membership* memb, std::string &partmessage, CUList& excepts)
666 {
667         if (IS_LOCAL(memb->user))
668         {
669                 parameterlist params;
670                 params.push_back(memb->chan->name);
671                 if (!partmessage.empty())
672                         params.push_back(":"+partmessage);
673                 Utils->DoOneToMany(memb->user->uuid,"PART",params);
674         }
675 }
676
677 void ModuleSpanningTree::OnUserQuit(User* user, const std::string &reason, const std::string &oper_message)
678 {
679         if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
680         {
681                 parameterlist params;
682
683                 if (oper_message != reason)
684                 {
685                         params.push_back(":"+oper_message);
686                         Utils->DoOneToMany(user->uuid,"OPERQUIT",params);
687                 }
688                 params.clear();
689                 params.push_back(":"+reason);
690                 Utils->DoOneToMany(user->uuid,"QUIT",params);
691         }
692
693         // Regardless, We need to modify the user Counts..
694         TreeServer* SourceServer = Utils->FindServer(user->server);
695         if (SourceServer)
696         {
697                 SourceServer->SetUserCount(-1); // decrement by 1
698         }
699 }
700
701 void ModuleSpanningTree::OnUserPostNick(User* user, const std::string &oldnick)
702 {
703         if (IS_LOCAL(user))
704         {
705                 parameterlist params;
706                 params.push_back(user->nick);
707
708                 /** IMPORTANT: We don't update the TS if the oldnick is just a case change of the newnick!
709                  */
710                 if (irc::string(user->nick.c_str()) != assign(oldnick))
711                         user->age = ServerInstance->Time();
712
713                 params.push_back(ConvToStr(user->age));
714                 Utils->DoOneToMany(user->uuid,"NICK",params);
715         }
716         else if (!loopCall && user->nick == user->uuid)
717         {
718                 parameterlist params;
719                 params.push_back(user->uuid);
720                 params.push_back(ConvToStr(user->age));
721                 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"SAVE",params);
722         }
723 }
724
725 void ModuleSpanningTree::OnUserKick(User* source, Membership* memb, const std::string &reason, CUList& excepts)
726 {
727         parameterlist params;
728         params.push_back(memb->chan->name);
729         params.push_back(memb->user->uuid);
730         params.push_back(":"+reason);
731         if (IS_LOCAL(source))
732         {
733                 Utils->DoOneToMany(source->uuid,"KICK",params);
734         }
735         else if (IS_SERVER(source) && source != Utils->ServerUser)
736         {
737                 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"KICK",params);
738         }
739 }
740
741 void ModuleSpanningTree::OnRemoteKill(User* source, User* dest, const std::string &reason, const std::string &operreason)
742 {
743         if (!IS_LOCAL(source))
744                 return; // Only start routing if we're origin.
745
746         ServerInstance->OperQuit.set(dest, operreason);
747         parameterlist params;
748         params.push_back(":"+operreason);
749         Utils->DoOneToMany(dest->uuid,"OPERQUIT",params);
750         params.clear();
751         params.push_back(dest->uuid);
752         params.push_back(":"+reason);
753         Utils->DoOneToMany(source->uuid,"KILL",params);
754 }
755
756 void ModuleSpanningTree::OnPreRehash(User* user, const std::string &parameter)
757 {
758         ServerInstance->Logs->Log("remoterehash", DEBUG, "called with param %s", parameter.c_str());
759
760         // Send out to other servers
761         if (!parameter.empty() && parameter[0] != '-')
762         {
763                 parameterlist params;
764                 params.push_back(parameter);
765                 Utils->DoOneToAllButSender(user ? user->uuid : ServerInstance->Config->GetSID(), "REHASH", params, user ? user->server : ServerInstance->Config->ServerName);
766         }
767 }
768
769 void ModuleSpanningTree::OnRehash(User* user)
770 {
771         // Re-read config stuff
772         Utils->ReadConfiguration(true);
773 }
774
775 void ModuleSpanningTree::OnLoadModule(Module* mod)
776 {
777         this->RedoConfig(mod);
778 }
779
780 void ModuleSpanningTree::OnUnloadModule(Module* mod)
781 {
782         this->RedoConfig(mod);
783 }
784
785 void ModuleSpanningTree::RedoConfig(Module* mod)
786 {
787         /* If m_sha256.so is loaded (we use this for HMAC) or any module implementing a BufferedSocket interface is loaded,
788          * then we need to re-read our config again taking this into account.
789          */
790         modulelist* ml = ServerInstance->Modules->FindInterface("BufferedSocketHook");
791         bool IsBufferSocketModule = false;
792
793         /* Did we find any modules? */
794         if (ml && std::find(ml->begin(), ml->end(), mod) != ml->end())
795                 IsBufferSocketModule = true;
796
797         if (mod->ModuleSourceFile == "m_sha256.so" || IsBufferSocketModule)
798         {
799                 Utils->ReadConfiguration(true);
800         }
801 }
802
803 // note: the protocol does not allow direct umode +o except
804 // via NICK with 8 params. sending OPERTYPE infers +o modechange
805 // locally.
806 void ModuleSpanningTree::OnOper(User* user, const std::string &opertype)
807 {
808         if (IS_LOCAL(user))
809         {
810                 parameterlist params;
811                 params.push_back(opertype);
812                 Utils->DoOneToMany(user->uuid,"OPERTYPE",params);
813         }
814 }
815
816 void ModuleSpanningTree::OnAddLine(User* user, XLine *x)
817 {
818         if (!x->IsBurstable() || loopCall)
819                 return;
820
821         char data[MAXBUF];
822         snprintf(data,MAXBUF,"%s %s %s %lu %lu :%s", x->type.c_str(), x->Displayable(),
823         ServerInstance->Config->ServerName.c_str(), (unsigned long)x->set_time, (unsigned long)x->duration, x->reason.c_str());
824         parameterlist params;
825         params.push_back(data);
826
827         if (!user)
828         {
829                 /* Server-set lines */
830                 Utils->DoOneToMany(ServerInstance->Config->GetSID(), "ADDLINE", params);
831         }
832         else if (IS_LOCAL(user))
833         {
834                 /* User-set lines */
835                 Utils->DoOneToMany(user->uuid, "ADDLINE", params);
836         }
837 }
838
839 void ModuleSpanningTree::OnDelLine(User* user, XLine *x)
840 {
841         if (x->type == "K")
842                 return;
843
844         char data[MAXBUF];
845         snprintf(data,MAXBUF,"%s %s", x->type.c_str(), x->Displayable());
846         parameterlist params;
847         params.push_back(data);
848
849         if (!user)
850         {
851                 /* Server-unset lines */
852                 Utils->DoOneToMany(ServerInstance->Config->GetSID(), "DELLINE", params);
853         }
854         else if (IS_LOCAL(user))
855         {
856                 /* User-unset lines */
857                 Utils->DoOneToMany(user->uuid, "DELLINE", params);
858         }
859 }
860
861 void ModuleSpanningTree::OnMode(User* user, void* dest, int target_type, const parameterlist &text, const std::vector<TranslateType> &translate)
862 {
863         if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
864         {
865                 parameterlist params;
866                 std::string command;
867                 std::string output_text;
868
869                 ServerInstance->Parser->TranslateUIDs(translate, text, output_text);
870
871                 if (target_type == TYPE_USER)
872                 {
873                         User* u = (User*)dest;
874                         params.push_back(u->uuid);
875                         params.push_back(output_text);
876                         command = "MODE";
877                 }
878                 else
879                 {
880                         Channel* c = (Channel*)dest;
881                         params.push_back(c->name);
882                         params.push_back(ConvToStr(c->age));
883                         params.push_back(output_text);
884                         command = "FMODE";
885                 }
886
887                 Utils->DoOneToMany(user->uuid, command, params);
888         }
889 }
890
891 ModResult ModuleSpanningTree::OnSetAway(User* user, const std::string &awaymsg)
892 {
893         if (IS_LOCAL(user))
894         {
895                 if (awaymsg.empty())
896                 {
897                         parameterlist params;
898                         Utils->DoOneToMany(user->uuid,"AWAY",params);
899                 }
900                 else
901                 {
902                         parameterlist params;
903                         params.push_back(ConvToStr(user->awaytime));
904                         params.push_back(":" + awaymsg);
905                         Utils->DoOneToMany(user->uuid,"AWAY",params);
906                 }
907         }
908
909         return MOD_RES_PASSTHRU;
910 }
911
912 void ModuleSpanningTree::ProtoSendMode(void* opaque, TargetTypeFlags target_type, void* target, const parameterlist &modeline, const std::vector<TranslateType> &translate)
913 {
914         TreeSocket* s = (TreeSocket*)opaque;
915         std::string output_text;
916
917         ServerInstance->Parser->TranslateUIDs(translate, modeline, output_text);
918
919         if (target)
920         {
921                 if (target_type == TYPE_USER)
922                 {
923                         User* u = (User*)target;
924                         s->WriteLine(std::string(":")+ServerInstance->Config->GetSID()+" MODE "+u->uuid+" "+output_text);
925                 }
926                 else if (target_type == TYPE_CHANNEL)
927                 {
928                         Channel* c = (Channel*)target;
929                         s->WriteLine(std::string(":")+ServerInstance->Config->GetSID()+" FMODE "+c->name+" "+ConvToStr(c->age)+" "+output_text);
930                 }
931         }
932 }
933
934 void ModuleSpanningTree::ProtoSendMetaData(void* opaque, Extensible* target, const std::string &extname, const std::string &extdata)
935 {
936         TreeSocket* s = static_cast<TreeSocket*>(opaque);
937         User* u = dynamic_cast<User*>(target);
938         Channel* c = dynamic_cast<Channel*>(target);
939         if (u)
940                 s->WriteLine(std::string(":")+ServerInstance->Config->GetSID()+" METADATA "+u->uuid+" "+extname+" :"+extdata);
941         else if (c)
942                 s->WriteLine(std::string(":")+ServerInstance->Config->GetSID()+" METADATA "+c->name+" "+extname+" :"+extdata);
943         else if (!target)
944                 s->WriteLine(std::string(":")+ServerInstance->Config->GetSID()+" METADATA * "+extname+" :"+extdata);
945 }
946
947 CullResult ModuleSpanningTree::cull()
948 {
949         Utils->cull();
950         ServerInstance->Timers->DelTimer(RefreshTimer);
951         ServerInstance->Modules->DoneWithInterface("BufferedSocketHook");
952         return this->Module::cull();
953 }
954
955 ModuleSpanningTree::~ModuleSpanningTree()
956 {
957         delete ServerInstance->PI;
958         ServerInstance->PI = new ProtocolInterface;
959
960         /* This will also free the listeners */
961         delete Utils;
962
963         delete command_rconnect;
964         delete command_rsquit;
965 }
966
967 Version ModuleSpanningTree::GetVersion()
968 {
969         return Version("Allows servers to be linked", VF_VENDOR);
970 }
971
972 /* It is IMPORTANT that m_spanningtree is the last module in the chain
973  * so that any activity it sees is FINAL, e.g. we arent going to send out
974  * a NICK message before m_cloaking has finished putting the +x on the user,
975  * etc etc.
976  * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
977  * the module call queue.
978  */
979 void ModuleSpanningTree::Prioritize()
980 {
981         ServerInstance->Modules->SetPriority(this, PRIORITY_LAST);
982 }
983
984 MODULE_INIT(ModuleSpanningTree)