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