]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/treeserver.cpp
ef0fe4472ffdda0378b9956fde9f83e24e8d66aa
[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), ServerUser(ServerInstance->FakeClient)
41         , age(ServerInstance->Time()), Warned(false), UserCount(ServerInstance->Users.GetLocalUsers().size())
42         , OperCount(0), rtt(0), StartBurst(0), Hidden(false)
43 {
44         AddHashEntry();
45 }
46
47 /** When we create a new server, we call this constructor to initialize it.
48  * This constructor initializes the server's Route and Parent, and sets up
49  * its ping counters so that it will be pinged one minute from now.
50  */
51 TreeServer::TreeServer(const std::string& Name, const std::string& Desc, const std::string& id, TreeServer* Above, TreeSocket* Sock, bool Hide)
52         : Server(Name, Desc)
53         , Parent(Above), Socket(Sock), sid(id), behind_bursting(Parent->behind_bursting), ServerUser(new FakeUser(id, this))
54         , age(ServerInstance->Time()), Warned(false), UserCount(0), OperCount(0), rtt(0), StartBurst(0), Hidden(Hide)
55 {
56         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "New server %s behind_bursting %u", GetName().c_str(), behind_bursting);
57         CheckULine();
58         SetNextPingTime(ServerInstance->Time() + Utils->PingFreq);
59         SetPingFlag();
60
61         /* find the 'route' for this server (e.g. the one directly connected
62          * to the local server, which we can use to reach it)
63          *
64          * In the following example, consider we have just added a TreeServer
65          * class for server G on our network, of which we are server A.
66          * To route traffic to G (marked with a *) we must send the data to
67          * B (marked with a +) so this algorithm initializes the 'Route'
68          * value to point at whichever server traffic must be routed through
69          * to get here. If we were to try this algorithm with server B,
70          * the Route pointer would point at its own object ('this').
71          *
72          *            A
73          *           / \
74          *        + B   C
75          *         / \   \
76          *        D   E   F
77          *       /         \
78          *    * G           H
79          *
80          * We only run this algorithm when a server is created, as
81          * the routes remain constant while ever the server exists, and
82          * do not need to be re-calculated.
83          */
84
85         Route = Above;
86         if (Route == Utils->TreeRoot)
87         {
88                 Route = this;
89         }
90         else
91         {
92                 while (this->Route->GetParent() != Utils->TreeRoot)
93                 {
94                         this->Route = Route->GetParent();
95                 }
96         }
97
98         /* Because recursive code is slow and takes a lot of resources,
99          * we store two representations of the server tree. The first
100          * is a recursive structure where each server references its
101          * children and its parent, which is used for netbursts and
102          * netsplits to dump the whole dataset to the other server,
103          * and the second is used for very fast lookups when routing
104          * messages and is instead a hash_map, where each item can
105          * be referenced by its server name. The AddHashEntry()
106          * call below automatically inserts each TreeServer class
107          * into the hash_map as it is created. There is a similar
108          * maintainance call in the destructor to tidy up deleted
109          * servers.
110          */
111
112         this->AddHashEntry();
113         Parent->AddChild(this);
114 }
115
116 void TreeServer::BeginBurst(unsigned long startms)
117 {
118         behind_bursting++;
119
120         unsigned long now = ServerInstance->Time() * 1000 + (ServerInstance->Time_ns() / 1000000);
121         // If the start time is in the future (clocks are not synced) then use current time
122         if ((!startms) || (startms > now))
123                 startms = now;
124         this->StartBurst = startms;
125         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Server %s started bursting at time %lu behind_bursting %u", sid.c_str(), startms, behind_bursting);
126 }
127
128 const std::string& TreeServer::GetID()
129 {
130         return sid;
131 }
132
133 void TreeServer::FinishBurstInternal()
134 {
135         // Check is needed because 1202 protocol servers don't send the bursting state of a server, so servers
136         // introduced during a netburst may later send ENDBURST which would normally decrease this counter
137         if (behind_bursting > 0)
138                 behind_bursting--;
139         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "FinishBurstInternal() %s behind_bursting %u", GetName().c_str(), behind_bursting);
140
141         if (!IsBehindBursting())
142         {
143                 SetNextPingTime(ServerInstance->Time() + Utils->PingFreq);
144                 SetPingFlag();
145         }
146         for (ChildServers::const_iterator i = Children.begin(); i != Children.end(); ++i)
147         {
148                 TreeServer* child = *i;
149                 child->FinishBurstInternal();
150         }
151 }
152
153 void TreeServer::FinishBurst()
154 {
155         ServerInstance->XLines->ApplyLines();
156         long ts = ServerInstance->Time() * 1000 + (ServerInstance->Time_ns() / 1000000);
157         unsigned long bursttime = ts - this->StartBurst;
158         ServerInstance->SNO->WriteToSnoMask(Parent == Utils->TreeRoot ? 'l' : 'L', "Received end of netburst from \2%s\2 (burst time: %lu %s)",
159                 GetName().c_str(), (bursttime > 10000 ? bursttime / 1000 : bursttime), (bursttime > 10000 ? "secs" : "msecs"));
160         AddServerEvent(Utils->Creator, GetName());
161
162         StartBurst = 0;
163         FinishBurstInternal();
164 }
165
166 void TreeServer::SQuitChild(TreeServer* server, const std::string& reason)
167 {
168         DelServerEvent(Utils->Creator, server->GetName());
169         DelChild(server);
170
171         if (IsRoot())
172         {
173                 // Server split from us, generate a SQUIT message and broadcast it
174                 ServerInstance->SNO->WriteGlobalSno('l', "Server \002" + server->GetName() + "\002 split: " + reason);
175                 CmdBuilder("SQUIT").push(server->GetID()).push_last(reason).Broadcast();
176         }
177         else
178         {
179                 ServerInstance->SNO->WriteToSnoMask('L', "Server \002" + server->GetName() + "\002 split from server \002" + GetName() + "\002 with reason: " + reason);
180         }
181
182         int num_lost_servers = 0;
183         int num_lost_users = 0;
184         const std::string quitreason = GetName() + " " + server->GetName();
185
186         ModuleSpanningTree* st = Utils->Creator;
187         st->SplitInProgress = true;
188         server->SQuitInternal(quitreason, num_lost_servers, num_lost_users);
189         st->SplitInProgress = false;
190
191         ServerInstance->SNO->WriteToSnoMask(IsRoot() ? 'l' : 'L', "Netsplit complete, lost \002%d\002 user%s on \002%d\002 server%s.",
192                 num_lost_users, num_lost_users != 1 ? "s" : "", num_lost_servers, num_lost_servers != 1 ? "s" : "");
193
194         // No-op if the socket is already closed (i.e. it called us)
195         if (server->IsLocal())
196                 server->GetSocket()->Close();
197
198         // Add the server to the cull list, the servers behind it are handled by cull() and the destructor
199         ServerInstance->GlobalCulls.AddItem(server);
200 }
201
202 void TreeServer::SQuitInternal(const std::string& reason, int& num_lost_servers, int& num_lost_users)
203 {
204         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Server %s lost in split", GetName().c_str());
205
206         for (ChildServers::const_iterator i = Children.begin(); i != Children.end(); ++i)
207         {
208                 TreeServer* server = *i;
209                 server->SQuitInternal(reason, num_lost_servers, num_lost_users);
210         }
211
212         num_lost_servers++;
213         num_lost_users += QuitUsers(reason);
214         RemoveHash();
215 }
216
217 int TreeServer::QuitUsers(const std::string &reason)
218 {
219         std::string publicreason = ServerInstance->Config->HideSplits ? "*.net *.split" : reason;
220
221         const user_hash& users = ServerInstance->Users->GetUsers();
222         unsigned int original_size = users.size();
223         for (user_hash::const_iterator i = users.begin(); i != users.end(); )
224         {
225                 User* user = i->second;
226                 // Increment the iterator now because QuitUser() removes the user from the container
227                 ++i;
228                 if (user->server == this)
229                         ServerInstance->Users->QuitUser(user, publicreason, &reason);
230         }
231         return original_size - users.size();
232 }
233
234 void TreeServer::CheckULine()
235 {
236         uline = silentuline = false;
237
238         ConfigTagList tags = ServerInstance->Config->ConfTags("uline");
239         for (ConfigIter i = tags.first; i != tags.second; ++i)
240         {
241                 ConfigTag* tag = i->second;
242                 std::string server = tag->getString("server");
243                 if (!strcasecmp(server.c_str(), GetName().c_str()))
244                 {
245                         if (this->IsRoot())
246                         {
247                                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Servers should not uline themselves (at " + tag->getTagLocation() + ")");
248                                 return;
249                         }
250
251                         uline = true;
252                         silentuline = tag->getBool("silent");
253                         break;
254                 }
255         }
256 }
257
258 /** This method is used to add the structure to the
259  * hash_map for linear searches. It is only called
260  * by the constructors.
261  */
262 void TreeServer::AddHashEntry()
263 {
264         Utils->serverlist[GetName()] = this;
265         Utils->sidlist[sid] = this;
266 }
267
268 /** These accessors etc should be pretty self-
269  * explanitory.
270  */
271 TreeServer* TreeServer::GetRoute()
272 {
273         return Route;
274 }
275
276 const std::string& TreeServer::GetVersion()
277 {
278         return VersionString;
279 }
280
281 void TreeServer::SetNextPingTime(time_t t)
282 {
283         this->NextPing = t;
284         LastPingWasGood = false;
285 }
286
287 time_t TreeServer::NextPingTime()
288 {
289         return NextPing;
290 }
291
292 bool TreeServer::AnsweredLastPing()
293 {
294         return LastPingWasGood;
295 }
296
297 void TreeServer::SetPingFlag()
298 {
299         LastPingWasGood = true;
300 }
301
302 TreeSocket* TreeServer::GetSocket()
303 {
304         return Socket;
305 }
306
307 TreeServer* TreeServer::GetParent()
308 {
309         return Parent;
310 }
311
312 void TreeServer::SetVersion(const std::string &Version)
313 {
314         VersionString = Version;
315 }
316
317 void TreeServer::AddChild(TreeServer* Child)
318 {
319         Children.push_back(Child);
320 }
321
322 bool TreeServer::DelChild(TreeServer* Child)
323 {
324         std::vector<TreeServer*>::iterator it = std::find(Children.begin(), Children.end(), Child);
325         if (it != Children.end())
326         {
327                 Children.erase(it);
328                 return true;
329         }
330         return false;
331 }
332
333 /** Removes child nodes of this node, and of that node, etc etc.
334  * This is used during netsplits to automatically tidy up the
335  * server tree. It is slow, we don't use it for much else.
336  */
337 void TreeServer::Tidy()
338 {
339         while (1)
340         {
341                 std::vector<TreeServer*>::iterator a = Children.begin();
342                 if (a == Children.end())
343                         return;
344                 TreeServer* s = *a;
345                 s->Tidy();
346                 s->cull();
347                 Children.erase(a);
348                 delete s;
349         }
350 }
351
352 CullResult TreeServer::cull()
353 {
354         // Recursively cull all servers that are under us in the tree
355         for (ChildServers::const_iterator i = Children.begin(); i != Children.end(); ++i)
356         {
357                 TreeServer* server = *i;
358                 server->cull();
359         }
360
361         if (!IsRoot())
362                 ServerUser->cull();
363         return classbase::cull();
364 }
365
366 TreeServer::~TreeServer()
367 {
368         // Recursively delete all servers that are under us in the tree first
369         for (ChildServers::const_iterator i = Children.begin(); i != Children.end(); ++i)
370                 delete *i;
371
372         // Delete server user unless it's us
373         if (!IsRoot())
374                 delete ServerUser;
375 }
376
377 void TreeServer::RemoveHash()
378 {
379         Utils->sidlist.erase(sid);
380         Utils->serverlist.erase(GetName());
381 }