]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/treeserver.cpp
Merge insp20
[user/henk/code/inspircd.git] / src / modules / m_spanningtree / treeserver.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org>
5  *   Copyright (C) 2007-2008 Craig Edwards <craigedwards@brainbox.cc>
6  *   Copyright (C) 2008 Robin Burchell <robin+git@viroteck.net>
7  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
8  *
9  * This file is part of InspIRCd.  InspIRCd is free software: you can
10  * redistribute it and/or modify it under the terms of the GNU General Public
11  * License as published by the Free Software Foundation, version 2.
12  *
13  * This program is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
16  * details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
20  */
21
22
23 #include "inspircd.h"
24 #include "xline.h"
25 #include "main.h"
26 #include "modules/spanningtree.h"
27
28 #include "utils.h"
29 #include "treeserver.h"
30
31 /** We use this constructor only to create the 'root' item, Utils->TreeRoot, which
32  * represents our own server. Therefore, it has no route, no parent, and
33  * no socket associated with it. Its version string is our own local version.
34  */
35 TreeServer::TreeServer()
36         : Server(ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc)
37         , Parent(NULL), Route(NULL)
38         , VersionString(ServerInstance->GetVersionString())
39         , fullversion(ServerInstance->GetVersionString(true))
40         , Socket(NULL), sid(ServerInstance->Config->GetSID()), behind_bursting(0), isdead(false)
41         , pingtimer(this)
42         , ServerUser(ServerInstance->FakeClient)
43         , age(ServerInstance->Time()), UserCount(ServerInstance->Users.LocalUserCount())
44         , OperCount(0), rtt(0), StartBurst(0), Hidden(false)
45 {
46         AddHashEntry();
47 }
48
49 /** When we create a new server, we call this constructor to initialize it.
50  * This constructor initializes the server's Route and Parent, and sets up
51  * its ping counters so that it will be pinged one minute from now.
52  */
53 TreeServer::TreeServer(const std::string& Name, const std::string& Desc, const std::string& id, TreeServer* Above, TreeSocket* Sock, bool Hide)
54         : Server(Name, Desc)
55         , Parent(Above), Socket(Sock), sid(id), behind_bursting(Parent->behind_bursting), isdead(false)
56         , pingtimer(this)
57         , ServerUser(new FakeUser(id, this))
58         , age(ServerInstance->Time()), UserCount(0), OperCount(0), rtt(0), StartBurst(0), Hidden(Hide)
59 {
60         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "New server %s behind_bursting %u", GetName().c_str(), behind_bursting);
61         CheckULine();
62
63         ServerInstance->Timers.AddTimer(&pingtimer);
64
65         /* find the 'route' for this server (e.g. the one directly connected
66          * to the local server, which we can use to reach it)
67          *
68          * In the following example, consider we have just added a TreeServer
69          * class for server G on our network, of which we are server A.
70          * To route traffic to G (marked with a *) we must send the data to
71          * B (marked with a +) so this algorithm initializes the 'Route'
72          * value to point at whichever server traffic must be routed through
73          * to get here. If we were to try this algorithm with server B,
74          * the Route pointer would point at its own object ('this').
75          *
76          *            A
77          *           / \
78          *        + B   C
79          *         / \   \
80          *        D   E   F
81          *       /         \
82          *    * G           H
83          *
84          * We only run this algorithm when a server is created, as
85          * the routes remain constant while ever the server exists, and
86          * do not need to be re-calculated.
87          */
88
89         Route = Above;
90         if (Route == Utils->TreeRoot)
91         {
92                 Route = this;
93         }
94         else
95         {
96                 while (this->Route->GetParent() != Utils->TreeRoot)
97                 {
98                         this->Route = Route->GetParent();
99                 }
100         }
101
102         /* Because recursive code is slow and takes a lot of resources,
103          * we store two representations of the server tree. The first
104          * is a recursive structure where each server references its
105          * children and its parent, which is used for netbursts and
106          * netsplits to dump the whole dataset to the other server,
107          * and the second is used for very fast lookups when routing
108          * messages and is instead a hash_map, where each item can
109          * be referenced by its server name. The AddHashEntry()
110          * call below automatically inserts each TreeServer class
111          * into the hash_map as it is created. There is a similar
112          * maintainance call in the destructor to tidy up deleted
113          * servers.
114          */
115
116         this->AddHashEntry();
117         Parent->Children.push_back(this);
118 }
119
120 void TreeServer::BeginBurst(unsigned long startms)
121 {
122         behind_bursting++;
123
124         unsigned long now = ServerInstance->Time() * 1000 + (ServerInstance->Time_ns() / 1000000);
125         // If the start time is in the future (clocks are not synced) then use current time
126         if ((!startms) || (startms > now))
127                 startms = now;
128         this->StartBurst = startms;
129         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Server %s started bursting at time %lu behind_bursting %u", sid.c_str(), startms, behind_bursting);
130 }
131
132 void TreeServer::FinishBurstInternal()
133 {
134         // Check is needed because 1202 protocol servers don't send the bursting state of a server, so servers
135         // introduced during a netburst may later send ENDBURST which would normally decrease this counter
136         if (behind_bursting > 0)
137                 behind_bursting--;
138         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "FinishBurstInternal() %s behind_bursting %u", GetName().c_str(), behind_bursting);
139
140         for (ChildServers::const_iterator i = Children.begin(); i != Children.end(); ++i)
141         {
142                 TreeServer* child = *i;
143                 child->FinishBurstInternal();
144         }
145 }
146
147 void TreeServer::FinishBurst()
148 {
149         ServerInstance->XLines->ApplyLines();
150         long ts = ServerInstance->Time() * 1000 + (ServerInstance->Time_ns() / 1000000);
151         unsigned long bursttime = ts - this->StartBurst;
152         ServerInstance->SNO->WriteToSnoMask(Parent == Utils->TreeRoot ? 'l' : 'L', "Received end of netburst from \2%s\2 (burst time: %lu %s)",
153                 GetName().c_str(), (bursttime > 10000 ? bursttime / 1000 : bursttime), (bursttime > 10000 ? "secs" : "msecs"));
154         FOREACH_MOD_CUSTOM(Utils->Creator->GetEventProvider(), SpanningTreeEventListener, OnServerLink, (this));
155
156         StartBurst = 0;
157         FinishBurstInternal();
158 }
159
160 void TreeServer::SQuitChild(TreeServer* server, const std::string& reason)
161 {
162         FOREACH_MOD_CUSTOM(Utils->Creator->GetEventProvider(), SpanningTreeEventListener, OnServerSplit, (server));
163         stdalgo::erase(Children, server);
164
165         if (IsRoot())
166         {
167                 // Server split from us, generate a SQUIT message and broadcast it
168                 ServerInstance->SNO->WriteGlobalSno('l', "Server \002" + server->GetName() + "\002 split: " + reason);
169                 CmdBuilder("SQUIT").push(server->GetID()).push_last(reason).Broadcast();
170         }
171         else
172         {
173                 ServerInstance->SNO->WriteToSnoMask('L', "Server \002" + server->GetName() + "\002 split from server \002" + GetName() + "\002 with reason: " + reason);
174         }
175
176         unsigned int num_lost_servers = 0;
177         server->SQuitInternal(num_lost_servers);
178
179         const std::string quitreason = GetName() + " " + server->GetName();
180         unsigned int num_lost_users = QuitUsers(quitreason);
181
182         ServerInstance->SNO->WriteToSnoMask(IsRoot() ? 'l' : 'L', "Netsplit complete, lost \002%u\002 user%s on \002%u\002 server%s.",
183                 num_lost_users, num_lost_users != 1 ? "s" : "", num_lost_servers, num_lost_servers != 1 ? "s" : "");
184
185         // No-op if the socket is already closed (i.e. it called us)
186         if (server->IsLocal())
187                 server->GetSocket()->Close();
188
189         // Add the server to the cull list, the servers behind it are handled by cull() and the destructor
190         ServerInstance->GlobalCulls.AddItem(server);
191 }
192
193 void TreeServer::SQuitInternal(unsigned int& num_lost_servers)
194 {
195         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Server %s lost in split", GetName().c_str());
196
197         for (ChildServers::const_iterator i = Children.begin(); i != Children.end(); ++i)
198         {
199                 TreeServer* server = *i;
200                 server->SQuitInternal(num_lost_servers);
201         }
202
203         // Mark server as dead
204         isdead = true;
205         num_lost_servers++;
206         RemoveHash();
207 }
208
209 unsigned int TreeServer::QuitUsers(const std::string& reason)
210 {
211         std::string publicreason = ServerInstance->Config->HideSplits ? "*.net *.split" : reason;
212
213         const user_hash& users = ServerInstance->Users->GetUsers();
214         unsigned int original_size = users.size();
215         for (user_hash::const_iterator i = users.begin(); i != users.end(); )
216         {
217                 User* user = i->second;
218                 // Increment the iterator now because QuitUser() removes the user from the container
219                 ++i;
220                 TreeServer* server = TreeServer::Get(user);
221                 if (server->IsDead())
222                         ServerInstance->Users->QuitUser(user, publicreason, &reason);
223         }
224         return original_size - users.size();
225 }
226
227 void TreeServer::CheckULine()
228 {
229         uline = silentuline = false;
230
231         ConfigTagList tags = ServerInstance->Config->ConfTags("uline");
232         for (ConfigIter i = tags.first; i != tags.second; ++i)
233         {
234                 ConfigTag* tag = i->second;
235                 std::string server = tag->getString("server");
236                 if (!strcasecmp(server.c_str(), GetName().c_str()))
237                 {
238                         if (this->IsRoot())
239                         {
240                                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Servers should not uline themselves (at " + tag->getTagLocation() + ")");
241                                 return;
242                         }
243
244                         uline = true;
245                         silentuline = tag->getBool("silent");
246                         break;
247                 }
248         }
249 }
250
251 /** This method is used to add the structure to the
252  * hash_map for linear searches. It is only called
253  * by the constructors.
254  */
255 void TreeServer::AddHashEntry()
256 {
257         Utils->serverlist[GetName()] = this;
258         Utils->sidlist[sid] = this;
259 }
260
261 CullResult TreeServer::cull()
262 {
263         // Recursively cull all servers that are under us in the tree
264         for (ChildServers::const_iterator i = Children.begin(); i != Children.end(); ++i)
265         {
266                 TreeServer* server = *i;
267                 server->cull();
268         }
269
270         if (!IsRoot())
271                 ServerUser->cull();
272         return classbase::cull();
273 }
274
275 TreeServer::~TreeServer()
276 {
277         // Recursively delete all servers that are under us in the tree first
278         for (ChildServers::const_iterator i = Children.begin(); i != Children.end(); ++i)
279                 delete *i;
280
281         // Delete server user unless it's us
282         if (!IsRoot())
283                 delete ServerUser;
284 }
285
286 void TreeServer::RemoveHash()
287 {
288         // XXX: Erase server from UserManager::uuidlist now, to allow sid reuse in the current main loop
289         // iteration, before the cull list is applied
290         ServerInstance->Users->uuidlist.erase(sid);
291
292         Utils->sidlist.erase(sid);
293         Utils->serverlist.erase(GetName());
294 }