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