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