1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
14 /* $ModDesc: Provides a spanning tree server link protocol */
17 #include "commands/cmd_whois.h"
18 #include "commands/cmd_stats.h"
22 #include "transport.h"
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"
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 */
36 ModuleSpanningTree::ModuleSpanningTree(InspIRCd* Me)
37 : Module(Me), max_local(0), max_global(0)
39 ServerInstance->UseInterface("InspSocketHook");
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)
47 SyncTimer = new TimeSyncTimer(ServerInstance, this);
48 ServerInstance->Timers->AddTimer(SyncTimer);
53 RefreshTimer = new CacheRefreshTimer(ServerInstance, Utils);
54 ServerInstance->Timers->AddTimer(RefreshTimer);
57 void ModuleSpanningTree::ShowLinks(TreeServer* Current, userrec* user, int hops)
59 std::string Parent = Utils->TreeRoot->GetName();
60 if (Current->GetParent())
62 Parent = Current->GetParent()->GetName();
64 for (unsigned int q = 0; q < Current->ChildCount(); q++)
66 if ((Current->GetChild(q)->Hidden) || ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str()))))
70 ShowLinks(Current->GetChild(q),user,hops+1);
75 ShowLinks(Current->GetChild(q),user,hops+1);
78 /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
79 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetName().c_str())) && (!IS_OPER(user)))
81 /* Or if the server is hidden and they're not an oper */
82 else if ((Current->Hidden) && (!IS_OPER(user)))
85 user->WriteServ("364 %s %s %s :%d %s", user->nick,Current->GetName().c_str(),
86 (Utils->FlatLinks && (!IS_OPER(user))) ? ServerInstance->Config->ServerName : Parent.c_str(),
87 (Utils->FlatLinks && (!IS_OPER(user))) ? 0 : hops,
88 Current->GetDesc().c_str());
91 int ModuleSpanningTree::CountLocalServs()
93 return Utils->TreeRoot->ChildCount();
96 int ModuleSpanningTree::CountServs()
98 return Utils->serverlist.size();
101 void ModuleSpanningTree::HandleLinks(const char** parameters, int pcnt, userrec* user)
103 ShowLinks(Utils->TreeRoot,user,0);
104 user->WriteServ("365 %s * :End of /LINKS list.",user->nick);
108 void ModuleSpanningTree::HandleLusers(const char** parameters, int pcnt, userrec* user)
110 unsigned int n_users = ServerInstance->UserCount();
112 /* Only update these when someone wants to see them, more efficient */
113 if ((unsigned int)ServerInstance->LocalUserCount() > max_local)
114 max_local = ServerInstance->LocalUserCount();
115 if (n_users > max_global)
116 max_global = n_users;
118 unsigned int ulined_count = 0;
119 unsigned int ulined_local_count = 0;
121 /* If ulined are hidden and we're not an oper, count the number of ulined servers hidden,
122 * locally and globally (locally means directly connected to us)
124 if ((Utils->HideULines) && (!*user->oper))
126 for (server_hash::iterator q = Utils->serverlist.begin(); q != Utils->serverlist.end(); q++)
128 if (ServerInstance->ULine(q->second->GetName().c_str()))
131 if (q->second->GetParent() == Utils->TreeRoot)
132 ulined_local_count++;
136 user->WriteServ("251 %s :There are %d users and %d invisible on %d servers",user->nick,
137 n_users-ServerInstance->InvisibleUserCount(),
138 ServerInstance->InvisibleUserCount(),
139 ulined_count ? this->CountServs() - ulined_count : this->CountServs());
141 if (ServerInstance->OperCount())
142 user->WriteServ("252 %s %d :operator(s) online",user->nick,ServerInstance->OperCount());
144 if (ServerInstance->UnregisteredUserCount())
145 user->WriteServ("253 %s %d :unknown connections",user->nick,ServerInstance->UnregisteredUserCount());
147 if (ServerInstance->ChannelCount())
148 user->WriteServ("254 %s %d :channels formed",user->nick,ServerInstance->ChannelCount());
150 user->WriteServ("255 %s :I have %d clients and %d servers",user->nick,ServerInstance->LocalUserCount(),ulined_local_count ? this->CountLocalServs() - ulined_local_count : this->CountLocalServs());
151 user->WriteServ("265 %s :Current Local Users: %d Max: %d",user->nick,ServerInstance->LocalUserCount(),max_local);
152 user->WriteServ("266 %s :Current Global Users: %d Max: %d",user->nick,n_users,max_global);
156 std::string ModuleSpanningTree::TimeToStr(time_t secs)
158 time_t mins_up = secs / 60;
159 time_t hours_up = mins_up / 60;
160 time_t days_up = hours_up / 24;
162 mins_up = mins_up % 60;
163 hours_up = hours_up % 24;
164 return ((days_up ? (ConvToStr(days_up) + "d") : std::string(""))
165 + (hours_up ? (ConvToStr(hours_up) + "h") : std::string(""))
166 + (mins_up ? (ConvToStr(mins_up) + "m") : std::string(""))
167 + ConvToStr(secs) + "s");
170 const std::string ModuleSpanningTree::MapOperInfo(TreeServer* Current)
172 time_t secs_up = ServerInstance->Time() - Current->age;
173 return (" [Up: " + TimeToStr(secs_up) + " Lag: "+ConvToStr(Current->rtt)+"ms]");
176 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
177 void ModuleSpanningTree::ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][128], float &totusers, float &totservers)
181 for (int t = 0; t < depth; t++)
183 matrix[line][t] = ' ';
185 // For Aligning, we need to work out exactly how deep this thing is, and produce
186 // a 'Spacer' String to compensate.
188 memset(spacer,' ',40);
189 if ((40 - Current->GetName().length() - depth) > 1) {
190 spacer[40 - Current->GetName().length() - depth] = '\0';
198 /* Neat and tidy default values, as we're dealing with a matrix not a simple string */
199 memset(text, 0, 128);
201 if (ServerInstance->clientlist->size() == 0) {
202 // If there are no users, WHO THE HELL DID THE /MAP?!?!?!
207 percent = ((float)Current->GetUserCount() / (float)ServerInstance->clientlist->size()) * 100;
209 const std::string operdata = IS_OPER(user) ? MapOperInfo(Current) : "";
210 snprintf(text, 126, "%s %s%5d [%5.2f%%]%s", Current->GetName().c_str(), spacer, Current->GetUserCount(), percent, operdata.c_str());
211 totusers += Current->GetUserCount();
213 strlcpy(&matrix[line][depth],text,126);
215 for (unsigned int q = 0; q < Current->ChildCount(); q++)
217 if ((Current->GetChild(q)->Hidden) || ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str()))))
221 ShowMap(Current->GetChild(q),user,(Utils->FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
226 ShowMap(Current->GetChild(q),user,(Utils->FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
232 int ModuleSpanningTree::HandleMotd(const char** parameters, int pcnt, userrec* user)
236 if (match(ServerInstance->Config->ServerName, parameters[0]))
239 /* Remote MOTD, the server is within the 1st parameter */
240 std::deque<std::string> params;
241 params.push_back(parameters[0]);
242 /* Send it out remotely, generate no reply yet */
243 TreeServer* s = Utils->FindServerMask(parameters[0]);
246 params[0] = s->GetName();
247 Utils->DoOneToOne(user->uuid, "MOTD", params, s->GetName());
250 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
256 int ModuleSpanningTree::HandleAdmin(const char** parameters, int pcnt, userrec* user)
260 if (match(ServerInstance->Config->ServerName, parameters[0]))
263 /* Remote ADMIN, the server is within the 1st parameter */
264 std::deque<std::string> params;
265 params.push_back(parameters[0]);
266 /* Send it out remotely, generate no reply yet */
267 TreeServer* s = Utils->FindServerMask(parameters[0]);
270 params[0] = s->GetName();
271 Utils->DoOneToOne(user->uuid, "ADMIN", params, s->GetName());
274 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
280 int ModuleSpanningTree::HandleModules(const char** parameters, int pcnt, userrec* user)
284 if (match(ServerInstance->Config->ServerName, parameters[0]))
287 std::deque<std::string> params;
288 params.push_back(parameters[0]);
289 TreeServer* s = Utils->FindServerMask(parameters[0]);
292 params[0] = s->GetName();
293 Utils->DoOneToOne(user->uuid, "MODULES", params, s->GetName());
296 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
302 int ModuleSpanningTree::HandleStats(const char** parameters, int pcnt, userrec* user)
306 if (match(ServerInstance->Config->ServerName, parameters[1]))
309 /* Remote STATS, the server is within the 2nd parameter */
310 std::deque<std::string> params;
311 params.push_back(parameters[0]);
312 params.push_back(parameters[1]);
313 /* Send it out remotely, generate no reply yet */
315 TreeServer* s = Utils->FindServerMask(parameters[1]);
318 params[1] = s->GetName();
319 Utils->DoOneToOne(user->uuid, "STATS", params, s->GetName());
323 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[1]);
330 // Ok, prepare to be confused.
331 // After much mulling over how to approach this, it struck me that
332 // the 'usual' way of doing a /MAP isnt the best way. Instead of
333 // keeping track of a ton of ascii characters, and line by line
334 // under recursion working out where to place them using multiplications
335 // and divisons, we instead render the map onto a backplane of characters
336 // (a character matrix), then draw the branches as a series of "L" shapes
337 // from the nodes. This is not only friendlier on CPU it uses less stack.
338 void ModuleSpanningTree::HandleMap(const char** parameters, int pcnt, userrec* user)
340 // This array represents a virtual screen which we will
341 // "scratch" draw to, as the console device of an irc
342 // client does not provide for a proper terminal.
344 float totservers = 0;
345 char matrix[128][128];
346 for (unsigned int t = 0; t < 128; t++)
351 // The only recursive bit is called here.
352 ShowMap(Utils->TreeRoot,user,0,matrix,totusers,totservers);
353 // Process each line one by one. The algorithm has a limit of
354 // 128 servers (which is far more than a spanning tree should have
355 // anyway, so we're ok). This limit can be raised simply by making
356 // the character matrix deeper, 128 rows taking 10k of memory.
357 for (int l = 1; l < line; l++)
359 // scan across the line looking for the start of the
360 // servername (the recursive part of the algorithm has placed
361 // the servers at indented positions depending on what they
363 int first_nonspace = 0;
364 while (matrix[l][first_nonspace] == ' ')
369 // Draw the `- (corner) section: this may be overwritten by
370 // another L shape passing along the same vertical pane, becoming
371 // a |- (branch) section instead.
372 matrix[l][first_nonspace] = '-';
373 matrix[l][first_nonspace-1] = '`';
375 // Draw upwards until we hit the parent server, causing possibly
376 // other corners (`-) to become branches (|-)
377 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
379 matrix[l2][first_nonspace-1] = '|';
383 // dump the whole lot to the user. This is the easy bit, honest.
384 for (int t = 0; t < line; t++)
386 user->WriteServ("006 %s :%s",user->nick,&matrix[t][0]);
388 float avg_users = totusers / totservers;
389 user->WriteServ("270 %s :%.0f server%s and %.0f user%s, average %.2f users per server",user->nick,totservers,(totservers > 1 ? "s" : ""),totusers,(totusers > 1 ? "s" : ""),avg_users);
390 user->WriteServ("007 %s :End of /MAP",user->nick);
394 int ModuleSpanningTree::HandleSquit(const char** parameters, int pcnt, userrec* user)
396 TreeServer* s = Utils->FindServerMask(parameters[0]);
399 if (s == Utils->TreeRoot)
401 user->WriteServ("NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
404 TreeSocket* sock = s->GetSocket();
407 ServerInstance->SNO->WriteToSnoMask('l',"SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
408 sock->Squit(s,std::string("Server quit by ") + user->GetFullRealHost());
409 ServerInstance->SE->DelFd(sock);
415 user->WriteServ("NOTICE %s :*** WARNING: Using SQUIT to split remote servers is deprecated. Please use RSQUIT instead.",user->nick);
420 user->WriteServ("NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
425 int ModuleSpanningTree::HandleTime(const char** parameters, int pcnt, userrec* user)
427 if ((IS_LOCAL(user)) && (pcnt))
429 TreeServer* found = Utils->FindServerMask(parameters[0]);
432 // we dont' override for local server
433 if (found == Utils->TreeRoot)
436 std::deque<std::string> params;
437 params.push_back(found->GetName());
438 params.push_back(user->uuid);
439 Utils->DoOneToOne(ServerInstance->Config->GetSID(),"TIME",params,found->GetName());
443 user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
449 int ModuleSpanningTree::HandleRemoteWhois(const char** parameters, int pcnt, userrec* user)
451 if ((IS_LOCAL(user)) && (pcnt > 1))
453 userrec* remote = ServerInstance->FindNick(parameters[1]);
454 if ((remote) && (remote->GetFd() < 0))
456 std::deque<std::string> params;
457 params.push_back(parameters[1]);
458 Utils->DoOneToOne(user->uuid,"IDLE",params,remote->server);
463 user->WriteServ("401 %s %s :No such nick/channel",user->nick, parameters[1]);
464 user->WriteServ("318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
471 void ModuleSpanningTree::DoPingChecks(time_t curtime)
473 for (unsigned int j = 0; j < Utils->TreeRoot->ChildCount(); j++)
475 TreeServer* serv = Utils->TreeRoot->GetChild(j);
476 TreeSocket* sock = serv->GetSocket();
479 if (curtime >= serv->NextPingTime())
481 if (serv->AnsweredLastPing())
483 sock->WriteLine(std::string(":")+ServerInstance->Config->GetSID()+" PING "+serv->GetName());
484 serv->SetNextPingTime(curtime + Utils->PingFreq);
485 serv->LastPing = curtime;
487 gettimeofday(&t, NULL);
488 long ts = (t.tv_sec * 1000) + (t.tv_usec / 1000);
489 serv->LastPingMsec = ts;
490 serv->Warned = false;
494 /* they didnt answer, boot them */
495 sock->SendError("Ping timeout");
496 sock->Squit(serv,"Ping timeout");
497 ServerInstance->SE->DelFd(sock);
502 else if ((Utils->PingWarnTime) && (!serv->Warned) && (curtime >= serv->NextPingTime() - (Utils->PingFreq - Utils->PingWarnTime)) && (!serv->AnsweredLastPing()))
504 /* The server hasnt responded, send a warning to opers */
505 ServerInstance->SNO->WriteToSnoMask('l',"Server \002%s\002 has not responded to PING for %d seconds, high latency.", serv->GetName().c_str(), Utils->PingWarnTime);
511 /* Cancel remote burst mode on any servers which still have it enabled due to latency/lack of data.
512 * This prevents lost REMOTECONNECT notices
514 for (server_hash::iterator i = Utils->serverlist.begin(); i != Utils->serverlist.end(); i++)
515 Utils->SetRemoteBursting(i->second, false);
518 void ModuleSpanningTree::ConnectServer(Link* x)
521 QueryType start_type = DNS_QUERY_A;
523 start_type = DNS_QUERY_AAAA;
524 if (strchr(x->IPAddr.c_str(),':'))
527 if (inet_pton(AF_INET6, x->IPAddr.c_str(), &n) < 1)
534 if (inet_aton(x->IPAddr.c_str(),&n) < 1)
538 /* Do we already have an IP? If so, no need to resolve it. */
541 /* Gave a hook, but it wasnt one we know */
542 if ((!x->Hook.empty()) && (Utils->hooks.find(x->Hook.c_str()) == Utils->hooks.end()))
544 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()]);
545 if (newsocket->GetFd() > -1)
547 /* Handled automatically on success */
551 RemoteMessage(NULL, "CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
552 if (ServerInstance->SocketCull.find(newsocket) == ServerInstance->SocketCull.end())
553 ServerInstance->SocketCull[newsocket] = newsocket;
554 Utils->DoFailOver(x);
562 ServernameResolver* snr = new ServernameResolver((Module*)this, Utils, ServerInstance,x->IPAddr, *x, cached, start_type);
563 ServerInstance->AddResolver(snr, cached);
565 catch (ModuleException& e)
567 RemoteMessage(NULL, "CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(), e.GetReason());
568 Utils->DoFailOver(x);
573 void ModuleSpanningTree::AutoConnectServers(time_t curtime)
575 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
577 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
579 x->NextConnectTime = curtime + x->AutoConnect;
580 TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
581 if (x->FailOver.length())
583 TreeServer* CheckFailOver = Utils->FindServer(x->FailOver.c_str());
586 /* The failover for this server is currently a member of the network.
587 * The failover probably succeeded, where the main link did not.
588 * Don't try the main link until the failover is gone again.
595 // an autoconnected server is not connected. Check if its time to connect it
596 ServerInstance->SNO->WriteToSnoMask('l',"AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
597 this->ConnectServer(&(*x));
603 int ModuleSpanningTree::HandleVersion(const char** parameters, int pcnt, userrec* user)
605 // we've already checked if pcnt > 0, so this is safe
606 TreeServer* found = Utils->FindServerMask(parameters[0]);
609 std::string Version = found->GetVersion();
610 user->WriteServ("351 %s :%s",user->nick,Version.c_str());
611 if (found == Utils->TreeRoot)
613 ServerInstance->Config->Send005(user);
618 user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
623 /* This method will attempt to get a link message out to as many people as is required.
624 * If a user is provided, and that user is local, then the user is sent the message using
625 * WriteServ (they are the local initiator of that message). If the user is remote, they are
626 * sent that message remotely via PUSH.
627 * If the user is NULL, then the notice is sent locally via WriteToSnoMask with snomask 'l',
628 * and remotely via SNONOTICE with mask 'l'.
630 void ModuleSpanningTree::RemoteMessage(userrec* user, const char* format, ...)
632 std::deque<std::string> params;
636 va_start(argsPtr, format);
637 vsnprintf(text, MAXBUF, format, argsPtr);
642 /* No user, target it generically at everyone */
643 ServerInstance->SNO->WriteToSnoMask('l', "%s", text);
644 params.push_back("l");
645 params.push_back(std::string(":") + text);
646 Utils->DoOneToMany(ServerInstance->Config->GetSID(), "SNONOTICE", params);
651 user->WriteServ("NOTICE %s :%s", user->nick, text);
654 params.push_back(user->uuid);
655 params.push_back(std::string("::") + ServerInstance->Config->ServerName + " NOTICE " + user->nick + " :*** From " +
656 ServerInstance->Config->ServerName+ ": " + text);
657 Utils->DoOneToMany(ServerInstance->Config->GetSID(), "PUSH", params);
662 int ModuleSpanningTree::HandleConnect(const char** parameters, int pcnt, userrec* user)
664 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
666 if (ServerInstance->MatchText(x->Name.c_str(),parameters[0]))
668 TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
671 RemoteMessage(user, "*** CONNECT: Connecting to server: \002%s\002 (%s:%d)",user->nick,x->Name.c_str(),(x->HiddenFromStats ? "<hidden>" : x->IPAddr.c_str()),x->Port);
672 ConnectServer(&(*x));
677 RemoteMessage(user, "*** CONNECT: Server \002%s\002 already exists on the network and is connected via \002%s\002",user->nick,x->Name.c_str(),CheckDupe->GetParent()->GetName().c_str());
682 RemoteMessage(user, "NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
686 void ModuleSpanningTree::BroadcastTimeSync()
688 if (Utils->MasterTime)
690 std::deque<std::string> params;
691 params.push_back(ConvToStr(ServerInstance->Time(false)));
692 params.push_back("FORCE");
693 Utils->DoOneToMany(Instance->Config->GetSID(), "TIMESET", params);
697 int ModuleSpanningTree::OnStats(char statschar, userrec* user, string_list &results)
699 if ((statschar == 'c') || (statschar == 'n'))
701 for (unsigned int i = 0; i < Utils->LinkBlocks.size(); i++)
703 results.push_back(std::string(ServerInstance->Config->ServerName)+" 213 "+user->nick+" "+statschar+" *@"+(Utils->LinkBlocks[i].HiddenFromStats ? "<hidden>" : Utils->LinkBlocks[i].IPAddr)+" * "+Utils->LinkBlocks[i].Name.c_str()+" "+ConvToStr(Utils->LinkBlocks[i].Port)+" "+(Utils->LinkBlocks[i].Hook.empty() ? "plaintext" : Utils->LinkBlocks[i].Hook)+" "+(Utils->LinkBlocks[i].AutoConnect ? 'a' : '-')+'s');
704 if (statschar == 'c')
705 results.push_back(std::string(ServerInstance->Config->ServerName)+" 244 "+user->nick+" H * * "+Utils->LinkBlocks[i].Name.c_str());
707 results.push_back(std::string(ServerInstance->Config->ServerName)+" 219 "+user->nick+" "+statschar+" :End of /STATS report");
708 ServerInstance->SNO->WriteToSnoMask('t',"%s '%c' requested by %s (%s@%s)",(!strcmp(user->server,ServerInstance->Config->ServerName) ? "Stats" : "Remote stats"),statschar,user->nick,user->ident,user->host);
712 if (statschar == 'p')
714 /* show all server ports, after showing client ports. -- w00t */
716 for (unsigned int i = 0; i < Utils->Bindings.size(); i++)
718 std::string ip = Utils->Bindings[i]->IP;
722 std::string transport("plaintext");
723 if (Utils->Bindings[i]->GetHook())
724 transport = InspSocketNameRequest(this, Utils->Bindings[i]->GetHook()).Send();
726 results.push_back(ConvToStr(ServerInstance->Config->ServerName) + " 249 "+user->nick+" :" + ip + ":" + ConvToStr(Utils->Bindings[i]->port)+
727 " (server, " + transport + ")");
733 int ModuleSpanningTree::OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated, const std::string &original_line)
735 /* If the command doesnt appear to be valid, we dont want to mess with it. */
739 if (command == "CONNECT")
741 return this->HandleConnect(parameters,pcnt,user);
743 else if (command == "STATS")
745 return this->HandleStats(parameters,pcnt,user);
747 else if (command == "MOTD")
749 return this->HandleMotd(parameters,pcnt,user);
751 else if (command == "ADMIN")
753 return this->HandleAdmin(parameters,pcnt,user);
755 else if (command == "SQUIT")
757 return this->HandleSquit(parameters,pcnt,user);
759 else if (command == "MAP")
761 this->HandleMap(parameters,pcnt,user);
764 else if ((command == "TIME") && (pcnt > 0))
766 return this->HandleTime(parameters,pcnt,user);
768 else if (command == "LUSERS")
770 this->HandleLusers(parameters,pcnt,user);
773 else if (command == "LINKS")
775 this->HandleLinks(parameters,pcnt,user);
778 else if (command == "WHOIS")
783 return this->HandleRemoteWhois(parameters,pcnt,user);
786 else if ((command == "VERSION") && (pcnt > 0))
788 this->HandleVersion(parameters,pcnt,user);
791 else if ((command == "MODULES") && (pcnt > 0))
793 return this->HandleModules(parameters,pcnt,user);
798 void ModuleSpanningTree::OnPostCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, CmdResult result, const std::string &original_line)
800 if ((result == CMD_SUCCESS) && (ServerInstance->IsValidModuleCommand(command, pcnt, user)))
802 /* Safe, we know its non-null because IsValidModuleCommand returned true */
803 command_t* thiscmd = ServerInstance->Parser->GetHandler(command);
804 // this bit of code cleverly routes all module commands
805 // to all remote severs *automatically* so that modules
806 // can just handle commands locally, without having
807 // to have any special provision in place for remote
808 // commands and linking protocols.
809 std::deque<std::string> params;
811 int n_translate = thiscmd->translation.size();
812 TranslateType translate_to;
814 for (int j = 0; j < pcnt; j++)
818 /* Map all items to UUIDs where neccessary */
821 /* We have a translation mapping for this index */
822 translate_to = thiscmd->translation[j] != TR_END ? thiscmd->translation[j] : TR_TEXT;
825 translate_to = TR_TEXT;
827 ServerInstance->Log(DEBUG,"TRANSLATION: %s - type is %d", parameters[j], translate_to);
828 ServerInstance->Parser->TranslateUIDs(translate_to, parameters[j], target);
830 if (strchr(parameters[j],' '))
831 params.push_back(":" + target);
833 params.push_back(target);
835 Utils->DoOneToMany(user->uuid, command, params);
839 void ModuleSpanningTree::OnGetServerDescription(const std::string &servername,std::string &description)
841 TreeServer* s = Utils->FindServer(servername);
844 description = s->GetDesc();
848 void ModuleSpanningTree::OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
850 if (IS_LOCAL(source))
852 std::deque<std::string> params;
853 params.push_back(dest->uuid);
854 params.push_back(channel->name);
855 Utils->DoOneToMany(source->uuid,"INVITE",params);
859 void ModuleSpanningTree::OnPostLocalTopicChange(userrec* user, chanrec* chan, const std::string &topic)
861 std::deque<std::string> params;
862 params.push_back(chan->name);
863 params.push_back(":"+topic);
864 Utils->DoOneToMany(user->uuid,"TOPIC",params);
867 void ModuleSpanningTree::OnWallops(userrec* user, const std::string &text)
871 std::deque<std::string> params;
872 params.push_back(":"+text);
873 Utils->DoOneToMany(user->uuid,"WALLOPS",params);
877 void ModuleSpanningTree::OnUserNotice(userrec* user, void* dest, int target_type, const std::string &text, char status, const CUList &exempt_list)
879 if (target_type == TYPE_USER)
881 userrec* d = (userrec*)dest;
882 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
884 std::deque<std::string> params;
886 params.push_back(d->uuid);
887 params.push_back(":"+text);
888 Utils->DoOneToOne(user->uuid,"NOTICE",params,d->server);
891 else if (target_type == TYPE_CHANNEL)
895 chanrec *c = (chanrec*)dest;
898 std::string cname = c->name;
900 cname = status + cname;
902 Utils->GetListOfServersForChannel(c,list,status,exempt_list);
903 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
905 TreeSocket* Sock = i->second->GetSocket();
907 Sock->WriteLine(":"+std::string(user->uuid)+" NOTICE "+cname+" :"+text);
912 else if (target_type == TYPE_SERVER)
916 char* target = (char*)dest;
917 std::deque<std::string> par;
918 par.push_back(target);
919 par.push_back(":"+text);
920 Utils->DoOneToMany(user->uuid,"NOTICE",par);
925 void ModuleSpanningTree::OnUserMessage(userrec* user, void* dest, int target_type, const std::string &text, char status, const CUList &exempt_list)
927 if (target_type == TYPE_USER)
929 // route private messages which are targetted at clients only to the server
930 // which needs to receive them
931 userrec* d = (userrec*)dest;
932 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
934 std::deque<std::string> params;
936 params.push_back(d->uuid);
937 params.push_back(":"+text);
938 Utils->DoOneToOne(user->uuid,"PRIVMSG",params,d->server);
941 else if (target_type == TYPE_CHANNEL)
945 chanrec *c = (chanrec*)dest;
948 std::string cname = c->name;
950 cname = status + cname;
952 Utils->GetListOfServersForChannel(c,list,status,exempt_list);
953 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
955 TreeSocket* Sock = i->second->GetSocket();
957 Sock->WriteLine(":"+std::string(user->uuid)+" PRIVMSG "+cname+" :"+text);
962 else if (target_type == TYPE_SERVER)
966 char* target = (char*)dest;
967 std::deque<std::string> par;
968 par.push_back(target);
969 par.push_back(":"+text);
970 Utils->DoOneToMany(user->uuid,"PRIVMSG",par);
975 void ModuleSpanningTree::OnBackgroundTimer(time_t curtime)
977 AutoConnectServers(curtime);
978 DoPingChecks(curtime);
981 void ModuleSpanningTree::OnUserJoin(userrec* user, chanrec* channel, bool &silent)
983 // Only do this for local users
986 if (channel->GetUserCounter() == 1)
988 std::deque<std::string> params;
989 // set up their permissions and the channel TS with FJOIN.
990 // All users are FJOINed now, because a module may specify
991 // new joining permissions for the user.
992 params.push_back(channel->name);
993 params.push_back(ConvToStr(channel->age));
994 params.push_back(std::string(channel->GetAllPrefixChars(user))+","+std::string(user->uuid));
995 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"FJOIN",params);
996 /* First user in, sync the modes for the channel */
998 params.push_back(channel->ChanModes(true));
999 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"FMODE",params);
1003 std::deque<std::string> params;
1004 params.push_back(channel->name);
1005 params.push_back(ConvToStr(channel->age));
1006 Utils->DoOneToMany(user->uuid,"JOIN",params);
1011 void ModuleSpanningTree::OnChangeHost(userrec* user, const std::string &newhost)
1013 // only occurs for local clients
1014 if (user->registered != REG_ALL)
1016 std::deque<std::string> params;
1017 params.push_back(newhost);
1018 Utils->DoOneToMany(user->uuid,"FHOST",params);
1021 void ModuleSpanningTree::OnChangeName(userrec* user, const std::string &gecos)
1023 // only occurs for local clients
1024 if (user->registered != REG_ALL)
1026 std::deque<std::string> params;
1027 params.push_back(gecos);
1028 Utils->DoOneToMany(user->uuid,"FNAME",params);
1031 void ModuleSpanningTree::OnUserPart(userrec* user, chanrec* channel, const std::string &partmessage, bool &silent)
1035 std::deque<std::string> params;
1036 params.push_back(channel->name);
1037 if (!partmessage.empty())
1038 params.push_back(":"+partmessage);
1039 Utils->DoOneToMany(user->uuid,"PART",params);
1043 void ModuleSpanningTree::OnUserConnect(userrec* user)
1045 char agestr[MAXBUF];
1048 std::deque<std::string> params;
1049 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
1050 params.push_back(user->uuid);
1051 params.push_back(agestr);
1052 params.push_back(user->nick);
1053 params.push_back(user->host);
1054 params.push_back(user->dhost);
1055 params.push_back(user->ident);
1056 params.push_back("+"+std::string(user->FormatModes()));
1057 params.push_back(user->GetIPString());
1058 params.push_back(":"+std::string(user->fullname));
1059 Utils->DoOneToMany(ServerInstance->Config->GetSID(), "UID", params);
1060 // User is Local, change needs to be reflected!
1061 TreeServer* SourceServer = Utils->FindServer(user->server);
1064 SourceServer->AddUserCount();
1069 void ModuleSpanningTree::OnUserQuit(userrec* user, const std::string &reason, const std::string &oper_message)
1071 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
1073 std::deque<std::string> params;
1075 if (oper_message != reason)
1077 params.push_back(":"+oper_message);
1078 Utils->DoOneToMany(user->uuid,"OPERQUIT",params);
1081 params.push_back(":"+reason);
1082 Utils->DoOneToMany(user->uuid,"QUIT",params);
1084 // Regardless, We need to modify the user Counts..
1085 TreeServer* SourceServer = Utils->FindServer(user->server);
1088 SourceServer->DelUserCount();
1092 void ModuleSpanningTree::OnUserPostNick(userrec* user, const std::string &oldnick)
1096 std::deque<std::string> params;
1097 params.push_back(user->nick);
1098 Utils->DoOneToMany(user->uuid,"NICK",params);
1102 void ModuleSpanningTree::OnUserKick(userrec* source, userrec* user, chanrec* chan, const std::string &reason, bool &silent)
1104 if ((source) && (IS_LOCAL(source)))
1106 std::deque<std::string> params;
1107 params.push_back(chan->name);
1108 params.push_back(user->uuid);
1109 params.push_back(":"+reason);
1110 Utils->DoOneToMany(source->uuid,"KICK",params);
1114 std::deque<std::string> params;
1115 params.push_back(chan->name);
1116 params.push_back(user->uuid);
1117 params.push_back(":"+reason);
1118 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"KICK",params);
1122 void ModuleSpanningTree::OnRemoteKill(userrec* source, userrec* dest, const std::string &reason, const std::string &operreason)
1124 std::deque<std::string> params;
1125 params.push_back(":"+reason);
1126 Utils->DoOneToMany(dest->uuid,"OPERQUIT",params);
1128 params.push_back(dest->uuid);
1129 params.push_back(":"+reason);
1130 dest->SetOperQuit(operreason);
1131 Utils->DoOneToMany(source->uuid,"KILL",params);
1134 void ModuleSpanningTree::OnRehash(userrec* user, const std::string ¶meter)
1136 if (!parameter.empty())
1138 std::deque<std::string> params;
1139 params.push_back(parameter);
1140 Utils->DoOneToMany(user ? user->nick : ServerInstance->Config->GetSID(), "REHASH", params);
1142 if (ServerInstance->MatchText(ServerInstance->Config->ServerName,parameter))
1144 ServerInstance->WriteOpers("*** Remote rehash initiated locally by \002%s\002", user ? user->nick : ServerInstance->Config->ServerName);
1145 ServerInstance->RehashServer();
1148 Utils->ReadConfiguration(false);
1149 InitializeDisabledCommands(ServerInstance->Config->DisabledCommands, ServerInstance);
1152 // note: the protocol does not allow direct umode +o except
1153 // via NICK with 8 params. sending OPERTYPE infers +o modechange
1155 void ModuleSpanningTree::OnOper(userrec* user, const std::string &opertype)
1159 std::deque<std::string> params;
1160 params.push_back(opertype);
1161 Utils->DoOneToMany(user->uuid,"OPERTYPE",params);
1165 void ModuleSpanningTree::OnLine(userrec* source, const std::string &host, bool adding, char linetype, long duration, const std::string &reason)
1169 /* Server-set lines */
1171 snprintf(data,MAXBUF,"%c %s %s %lu %lu :%s", linetype, host.c_str(), ServerInstance->Config->ServerName, (unsigned long)ServerInstance->Time(false),
1172 (unsigned long)duration, reason.c_str());
1173 std::deque<std::string> params;
1174 params.push_back(data);
1175 Utils->DoOneToMany(ServerInstance->Config->GetSID(), "ADDLINE", params);
1179 if (IS_LOCAL(source))
1182 snprintf(type,8,"%cLINE",linetype);
1183 std::string stype = type;
1186 char sduration[MAXBUF];
1187 snprintf(sduration,MAXBUF,"%ld",duration);
1188 std::deque<std::string> params;
1189 params.push_back(host);
1190 params.push_back(sduration);
1191 params.push_back(":"+reason);
1192 Utils->DoOneToMany(source->uuid,stype,params);
1196 std::deque<std::string> params;
1197 params.push_back(host);
1198 Utils->DoOneToMany(source->uuid,stype,params);
1204 void ModuleSpanningTree::OnAddGLine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
1206 OnLine(source,hostmask,true,'G',duration,reason);
1209 void ModuleSpanningTree::OnAddZLine(long duration, userrec* source, const std::string &reason, const std::string &ipmask)
1211 OnLine(source,ipmask,true,'Z',duration,reason);
1214 void ModuleSpanningTree::OnAddQLine(long duration, userrec* source, const std::string &reason, const std::string &nickmask)
1216 OnLine(source,nickmask,true,'Q',duration,reason);
1219 void ModuleSpanningTree::OnAddELine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
1221 OnLine(source,hostmask,true,'E',duration,reason);
1224 void ModuleSpanningTree::OnDelGLine(userrec* source, const std::string &hostmask)
1226 OnLine(source,hostmask,false,'G',0,"");
1229 void ModuleSpanningTree::OnDelZLine(userrec* source, const std::string &ipmask)
1231 OnLine(source,ipmask,false,'Z',0,"");
1234 void ModuleSpanningTree::OnDelQLine(userrec* source, const std::string &nickmask)
1236 OnLine(source,nickmask,false,'Q',0,"");
1239 void ModuleSpanningTree::OnDelELine(userrec* source, const std::string &hostmask)
1241 OnLine(source,hostmask,false,'E',0,"");
1244 void ModuleSpanningTree::OnMode(userrec* user, void* dest, int target_type, const std::string &text)
1246 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
1248 std::deque<std::string> params;
1249 std::string command;
1250 std::string output_text;
1252 ServerInstance->Parser->TranslateUIDs(TR_SPACENICKLIST, text, output_text);
1254 if (target_type == TYPE_USER)
1256 userrec* u = (userrec*)dest;
1257 params.push_back(u->uuid);
1258 params.push_back(output_text);
1263 chanrec* c = (chanrec*)dest;
1264 params.push_back(c->name);
1265 params.push_back(ConvToStr(c->age));
1266 params.push_back(output_text);
1270 Utils->DoOneToMany(user->uuid, command, params);
1274 void ModuleSpanningTree::OnSetAway(userrec* user)
1278 std::deque<std::string> params;
1279 params.push_back(":"+std::string(user->awaymsg));
1280 Utils->DoOneToMany(user->uuid,"AWAY",params);
1284 void ModuleSpanningTree::OnCancelAway(userrec* user)
1288 std::deque<std::string> params;
1290 Utils->DoOneToMany(user->uuid,"AWAY",params);
1294 void ModuleSpanningTree::ProtoSendMode(void* opaque, int target_type, void* target, const std::string &modeline)
1296 TreeSocket* s = (TreeSocket*)opaque;
1297 std::string output_text;
1299 ServerInstance->Parser->TranslateUIDs(TR_SPACENICKLIST, modeline, output_text);
1303 if (target_type == TYPE_USER)
1305 userrec* u = (userrec*)target;
1306 s->WriteLine(std::string(":")+ServerInstance->Config->GetSID()+" FMODE "+u->uuid+" "+ConvToStr(u->age)+" "+output_text);
1310 chanrec* c = (chanrec*)target;
1311 s->WriteLine(std::string(":")+ServerInstance->Config->GetSID()+" FMODE "+c->name+" "+ConvToStr(c->age)+" "+output_text);
1316 void ModuleSpanningTree::ProtoSendMetaData(void* opaque, int target_type, void* target, const std::string &extname, const std::string &extdata)
1318 TreeSocket* s = (TreeSocket*)opaque;
1321 if (target_type == TYPE_USER)
1323 userrec* u = (userrec*)target;
1324 s->WriteLine(std::string(":")+ServerInstance->Config->GetSID()+" METADATA "+u->uuid+" "+extname+" :"+extdata);
1326 else if (target_type == TYPE_CHANNEL)
1328 chanrec* c = (chanrec*)target;
1329 s->WriteLine(std::string(":")+ServerInstance->Config->GetSID()+" METADATA "+c->name+" "+extname+" :"+extdata);
1332 if (target_type == TYPE_OTHER)
1334 s->WriteLine(std::string(":")+ServerInstance->Config->GetSID()+" METADATA * "+extname+" :"+extdata);
1338 void ModuleSpanningTree::OnEvent(Event* event)
1340 std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
1341 if (event->GetEventID() == "send_metadata")
1343 if (params->size() < 3)
1345 (*params)[2] = ":" + (*params)[2];
1346 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"METADATA",*params);
1348 else if (event->GetEventID() == "send_topic")
1350 if (params->size() < 2)
1352 (*params)[1] = ":" + (*params)[1];
1353 params->insert(params->begin() + 1,ServerInstance->Config->ServerName);
1354 params->insert(params->begin() + 1,ConvToStr(ServerInstance->Time(true)));
1355 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"FTOPIC",*params);
1357 else if (event->GetEventID() == "send_mode")
1359 if (params->size() < 2)
1361 // Insert the TS value of the object, either userrec or chanrec
1363 std::string output_text;
1365 /* Warning: in-place translation is only safe for type TR_NICK */
1366 for (size_t n = 0; n < params->size(); n++)
1367 ServerInstance->Parser->TranslateUIDs(TR_NICK, (*params)[n], (*params)[n]);
1369 userrec* a = ServerInstance->FindNick((*params)[0]);
1373 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"MODE",*params);
1378 chanrec* a = ServerInstance->FindChan((*params)[0]);
1382 params->insert(params->begin() + 1,ConvToStr(ourTS));
1383 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"FMODE",*params);
1387 else if (event->GetEventID() == "send_mode_explicit")
1389 if (params->size() < 2)
1391 std::string output_text;
1393 /* Warning: in-place translation is only safe for type TR_NICK */
1394 for (size_t n = 0; n < params->size(); n++)
1395 ServerInstance->Parser->TranslateUIDs(TR_NICK, (*params)[n], (*params)[n]);
1397 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"MODE",*params);
1399 else if (event->GetEventID() == "send_opers")
1401 if (params->size() < 1)
1403 (*params)[0] = ":" + (*params)[0];
1404 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"OPERNOTICE",*params);
1406 else if (event->GetEventID() == "send_modeset")
1408 if (params->size() < 2)
1410 (*params)[1] = ":" + (*params)[1];
1411 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"MODENOTICE",*params);
1413 else if (event->GetEventID() == "send_snoset")
1415 if (params->size() < 2)
1417 (*params)[1] = ":" + (*params)[1];
1418 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"SNONOTICE",*params);
1420 else if (event->GetEventID() == "send_push")
1422 if (params->size() < 2)
1425 userrec *a = ServerInstance->FindNick((*params)[0]);
1430 (*params)[0] = a->uuid;
1431 (*params)[1] = ":" + (*params)[1];
1432 Utils->DoOneToOne(ServerInstance->Config->GetSID(), "PUSH", *params, a->server);
1436 ModuleSpanningTree::~ModuleSpanningTree()
1438 /* This will also free the listeners */
1441 ServerInstance->Timers->DelTimer(SyncTimer);
1443 ServerInstance->Timers->DelTimer(RefreshTimer);
1445 ServerInstance->DoneWithInterface("InspSocketHook");
1448 Version ModuleSpanningTree::GetVersion()
1450 return Version(1,1,0,2,VF_VENDOR,API_VERSION);
1453 void ModuleSpanningTree::Implements(char* List)
1455 List[I_OnPreCommand] = List[I_OnGetServerDescription] = List[I_OnUserInvite] = List[I_OnPostLocalTopicChange] = 1;
1456 List[I_OnWallops] = List[I_OnUserNotice] = List[I_OnUserMessage] = List[I_OnBackgroundTimer] = 1;
1457 List[I_OnUserJoin] = List[I_OnChangeHost] = List[I_OnChangeName] = List[I_OnUserPart] = List[I_OnUserConnect] = 1;
1458 List[I_OnUserQuit] = List[I_OnUserPostNick] = List[I_OnUserKick] = List[I_OnRemoteKill] = List[I_OnRehash] = 1;
1459 List[I_OnOper] = List[I_OnAddGLine] = List[I_OnAddZLine] = List[I_OnAddQLine] = List[I_OnAddELine] = 1;
1460 List[I_OnDelGLine] = List[I_OnDelZLine] = List[I_OnDelQLine] = List[I_OnDelELine] = List[I_ProtoSendMode] = List[I_OnMode] = 1;
1461 List[I_OnStats] = List[I_ProtoSendMetaData] = List[I_OnEvent] = List[I_OnSetAway] = List[I_OnCancelAway] = List[I_OnPostCommand] = 1;
1464 /* It is IMPORTANT that m_spanningtree is the last module in the chain
1465 * so that any activity it sees is FINAL, e.g. we arent going to send out
1466 * a NICK message before m_cloaking has finished putting the +x on the user,
1468 * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
1469 * the module call queue.
1471 Priority ModuleSpanningTree::Prioritize()
1473 return PRIORITY_LAST;
1476 MODULE_INIT(ModuleSpanningTree)