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