1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2021 Valentin Lorentz <progval+git@progval.net>
5  *   Copyright (C) 2020 Matt Schatz <genius3000@g3k.solutions>
6  *   Copyright (C) 2018 Chris Novakovic <chrisnovakovic@users.noreply.github.com>
7  *   Copyright (C) 2013, 2017-2021 Sadie Powell <sadie@witchery.services>
8  *   Copyright (C) 2013 Adam <Adam@anope.org>
9  *   Copyright (C) 2012-2014, 2016, 2018 Attila Molnar <attilamolnar@hush.com>
10  *   Copyright (C) 2012-2013 ChrisTX <xpipe@hotmail.de>
11  *   Copyright (C) 2012 Robby <robby@chatbelgie.be>
12  *   Copyright (C) 2012 Ariadne Conill <ariadne@dereferenced.org>
13  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
14  *   Copyright (C) 2008-2009 Uli Schlachter <psychon@inspircd.org>
15  *   Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
16  *   Copyright (C) 2007-2008 Robin Burchell <robin+git@viroteck.net>
17  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
18  *   Copyright (C) 2006-2007 Oliver Lupton <om@inspircd.org>
19  *   Copyright (C) 2005-2010 Craig Edwards <brain@inspircd.org>
20  *
21  * This file is part of InspIRCd.  InspIRCd is free software: you can
22  * redistribute it and/or modify it under the terms of the GNU General Public
23  * License as published by the Free Software Foundation, version 2.
24  *
25  * This program is distributed in the hope that it will be useful, but WITHOUT
26  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
27  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
28  * details.
29  *
30  * You should have received a copy of the GNU General Public License
31  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
32  */
33 
34 
35 #include "inspircd.h"
36 #include <signal.h>
37 
38 #ifndef _WIN32
39 	#include <unistd.h>
40 	#include <sys/resource.h>
41 	#include <getopt.h>
42 	#include <pwd.h> // setuid
43 	#include <grp.h> // setgid
44 #else
45 	/** Manages formatting lines written to stderr on Windows. */
46 	WindowsStream StandardError(STD_ERROR_HANDLE);
47 
48 	/** Manages formatting lines written to stdout on Windows. */
49 	WindowsStream StandardOutput(STD_OUTPUT_HANDLE);
50 #endif
51 
52 #include <fstream>
53 #include <iostream>
54 #include "xline.h"
55 #include "exitcodes.h"
56 
57 InspIRCd* ServerInstance = NULL;
58 
59 /** Separate from the other casemap tables so that code *can* still exclusively rely on RFC casemapping
60  * if it must.
61  *
62  * This is provided as a pointer so that modules can change it to their custom mapping tables,
63  * e.g. for national character support.
64  */
65 unsigned const char *national_case_insensitive_map = rfc_case_insensitive_map;
66 
67 
68 /* Moved from exitcodes.h -- due to duplicate symbols -- Burlex
69  * XXX this is a bit ugly. -- w00t
70  */
71 const char* ExitCodes[] =
72 {
73 		"No error",								// 0
74 		"DIE command",							// 1
75 		"Config file error",					// 2
76 		"Logfile error",						// 3
77 		"POSIX fork failed",					// 4
78 		"Bad commandline parameters",			// 5
79 		"Can't write PID file",					// 6
80 		"SocketEngine could not initialize",	// 7
81 		"Refusing to start up as root",			// 8
82 		"Couldn't load module on startup",		// 9
83 		"Received SIGTERM"						// 10
84 };
85 
86 namespace
87 {
88 	void VoidSignalHandler(int);
89 
90 	// Warns a user running as root that they probably shouldn't.
CheckRoot()91 	void CheckRoot()
92 	{
93 #ifndef _WIN32
94 		if (getegid() != 0 && geteuid() != 0)
95 			return;
96 
97 		std::cout << con_red << "Warning!" << con_reset << " You have started as root. Running as root is generally not required" << std::endl
98 			<< "and may allow an attacker to gain access to your system if they find a way to" << std::endl
99 			<< "exploit your IRC server." << std::endl
100 			<< std::endl;
101 		if (isatty(fileno(stdout)))
102 		{
103 			std::cout << "InspIRCd will start in 30 seconds. If you are sure that you need to run as root" << std::endl
104 				<< "then you can pass the " << con_bright << "--runasroot" << con_reset << " option to disable this wait." << std::endl;
105 			sleep(30);
106 		}
107 		else
108 		{
109 			std::cout << "If you are sure that you need to run as root then you can pass the " << con_bright << "--runasroot" << con_reset << std::endl
110 				<< "option to disable this error." << std::endl;
111 				ServerInstance->Exit(EXIT_STATUS_ROOT);
112 		}
113 #endif
114 	}
115 
116 	// Collects performance statistics for the STATS command.
CollectStats()117 	void CollectStats()
118 	{
119 #ifndef _WIN32
120 		static rusage ru;
121 		if (getrusage(RUSAGE_SELF, &ru) == -1)
122 			return; // Should never happen.
123 
124 		ServerInstance->stats.LastSampled.tv_sec = ServerInstance->Time();
125 		ServerInstance->stats.LastSampled.tv_nsec = ServerInstance->Time_ns();
126 		ServerInstance->stats.LastCPU = ru.ru_utime;
127 #else
128 		if (!QueryPerformanceCounter(&ServerInstance->stats.LastSampled))
129 			return; // Should never happen.
130 
131 		FILETIME CreationTime;
132 		FILETIME ExitTime;
133 		FILETIME KernelTime;
134 		FILETIME UserTime;
135 		GetProcessTimes(GetCurrentProcess(), &CreationTime, &ExitTime, &KernelTime, &UserTime);
136 
137 		ServerInstance->stats.LastCPU.dwHighDateTime = KernelTime.dwHighDateTime + UserTime.dwHighDateTime;
138 		ServerInstance->stats.LastCPU.dwLowDateTime = KernelTime.dwLowDateTime + UserTime.dwLowDateTime;
139 #endif
140 	}
141 
142 	// Checks whether the server clock has skipped too much and warn about it if it has.
CheckTimeSkip(time_t oldtime,time_t newtime)143 	void CheckTimeSkip(time_t oldtime, time_t newtime)
144 	{
145 		if (!ServerInstance->Config->TimeSkipWarn)
146 			return;
147 
148 		time_t timediff = newtime - oldtime;
149 
150 		if (timediff > ServerInstance->Config->TimeSkipWarn)
151 			ServerInstance->SNO->WriteToSnoMask('a', "\002Performance warning!\002 Server clock jumped forwards by %lu seconds!", timediff);
152 
153 		else if (timediff < -ServerInstance->Config->TimeSkipWarn)
154 			ServerInstance->SNO->WriteToSnoMask('a', "\002Performance warning!\002 Server clock jumped backwards by %lu seconds!", labs(timediff));
155 	}
156 
157 	// Drops to the unprivileged user/group specified in <security:runas{user,group}>.
DropRoot()158 	void DropRoot()
159 	{
160 #ifndef _WIN32
161 		ConfigTag* security = ServerInstance->Config->ConfValue("security");
162 
163 		const std::string SetGroup = security->getString("runasgroup");
164 		if (!SetGroup.empty())
165 		{
166 			errno = 0;
167 			if (setgroups(0, NULL) == -1)
168 			{
169 				ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "setgroups() failed (wtf?): %s", strerror(errno));
170 				exit(EXIT_STATUS_CONFIG);
171 			}
172 
173 			struct group* g = getgrnam(SetGroup.c_str());
174 			if (!g)
175 			{
176 				ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "getgrnam(%s) failed (wrong group?): %s", SetGroup.c_str(), strerror(errno));
177 				exit(EXIT_STATUS_CONFIG);
178 			}
179 
180 			if (setgid(g->gr_gid) == -1)
181 			{
182 				ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "setgid(%d) failed (wrong group?): %s", g->gr_gid, strerror(errno));
183 				exit(EXIT_STATUS_CONFIG);
184 			}
185 		}
186 
187 		const std::string SetUser = security->getString("runasuser");
188 		if (!SetUser.empty())
189 		{
190 			errno = 0;
191 			struct passwd* u = getpwnam(SetUser.c_str());
192 			if (!u)
193 			{
194 				ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "getpwnam(%s) failed (wrong user?): %s", SetUser.c_str(), strerror(errno));
195 				exit(EXIT_STATUS_CONFIG);
196 			}
197 
198 			if (setuid(u->pw_uid) == -1)
199 			{
200 				ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "setuid(%d) failed (wrong user?): %s", u->pw_uid, strerror(errno));
201 				exit(EXIT_STATUS_CONFIG);
202 			}
203 		}
204 #endif
205 	}
206 
207 	// Expands a path relative to the current working directory.
ExpandPath(const char * path)208 	std::string ExpandPath(const char* path)
209 	{
210 #ifdef _WIN32
211 		TCHAR configPath[MAX_PATH + 1];
212 		if (GetFullPathName(path, MAX_PATH, configPath, NULL) > 0)
213 			return configPath;
214 #else
215 		char configPath[PATH_MAX + 1];
216 		if (realpath(path, configPath))
217 			return configPath;
218 #endif
219 		return path;
220 	}
221 
222 	// Locates a config file on the file system.
FindConfigFile(std::string & path)223 	bool FindConfigFile(std::string& path)
224 	{
225 		if (FileSystem::FileExists(path))
226 			return true;
227 
228 #ifdef _WIN32
229 		// Windows hides file extensions by default so try appending .txt to the path
230 		// to help users who have that feature enabled and can't create .conf files.
231 		const std::string txtpath = path + ".txt";
232 		if (FileSystem::FileExists(txtpath))
233 		{
234 			path.assign(txtpath);
235 			return true;
236 		}
237 #endif
238 		return false;
239 	}
240 
241 	// Attempts to fork into the background.
ForkIntoBackground()242 	void ForkIntoBackground()
243 	{
244 #ifndef _WIN32
245 		// We use VoidSignalHandler whilst forking to avoid breaking daemon scripts
246 		// if the parent process exits with SIGTERM (15) instead of EXIT_STATUS_NOERROR (0).
247 		signal(SIGTERM, VoidSignalHandler);
248 
249 		errno = 0;
250 		int childpid = fork();
251 		if (childpid < 0)
252 		{
253 			ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "fork() failed: %s", strerror(errno));
254 			std::cout << con_red << "Error:" << con_reset << " unable to fork into background: " << strerror(errno);
255 			ServerInstance->Exit(EXIT_STATUS_FORK);
256 		}
257 		else if (childpid > 0)
258 		{
259 			// Wait until the child process kills the parent so that the shell prompt
260 			// doesnt display over the output. Sending a kill with a signal of 0 just
261 			// checks that the child pid is still running. If it is not then an error
262 			// happened and the parent should exit.
263 			while (kill(childpid, 0) != -1)
264 				sleep(1);
265 			exit(EXIT_STATUS_NOERROR);
266 		}
267 		else
268 		{
269 			setsid();
270 			signal(SIGTERM, InspIRCd::SetSignal);
271 			SocketEngine::RecoverFromFork();
272 		}
273 #endif
274 	}
275 
276 	// Increase the size of a core dump file to improve debugging problems.
IncreaseCoreDumpSize()277 	void IncreaseCoreDumpSize()
278 	{
279 #ifndef _WIN32
280 		errno = 0;
281 		rlimit rl;
282 		if (getrlimit(RLIMIT_CORE, &rl) == -1)
283 		{
284 			ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "Unable to increase core dump size: getrlimit(RLIMIT_CORE) failed: %s", strerror(errno));
285 			return;
286 		}
287 
288 		rl.rlim_cur = rl.rlim_max;
289 		if (setrlimit(RLIMIT_CORE, &rl) == -1)
290 			ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "Unable to increase core dump size: setrlimit(RLIMIT_CORE) failed: %s", strerror(errno));
291 #endif
292 	}
293 
294 	// Parses the command line options.
ParseOptions()295 	void ParseOptions()
296 	{
297 		int do_debug = 0, do_nofork = 0,    do_nolog = 0;
298 		int do_nopid = 0, do_runasroot = 0, do_version = 0;
299 		struct option longopts[] =
300 		{
301 			{ "config",    required_argument, NULL,          'c' },
302 			{ "debug",     no_argument,       &do_debug,     1 },
303 			{ "nofork",    no_argument,       &do_nofork,    1 },
304 			{ "nolog",     no_argument,       &do_nolog,     1 },
305 			{ "nopid",     no_argument,       &do_nopid,     1 },
306 			{ "runasroot", no_argument,       &do_runasroot, 1 },
307 			{ "version",   no_argument,       &do_version,   1 },
308 			{ 0, 0, 0, 0 }
309 		};
310 
311 		char** argv = ServerInstance->Config->cmdline.argv;
312 		int ret;
313 		while ((ret = getopt_long(ServerInstance->Config->cmdline.argc, argv, ":c:", longopts, NULL)) != -1)
314 		{
315 			switch (ret)
316 			{
317 				case 0:
318 					// A long option was specified.
319 					break;
320 
321 				case 'c':
322 					// The -c option was specified.
323 					ServerInstance->ConfigFileName = ExpandPath(optarg);
324 					break;
325 
326 				default:
327 					// An unknown option was specified.
328 					std::cout << con_red << "Error:" <<  con_reset << " unknown option '" << argv[optind-1] << "'." << std::endl
329 						<< con_bright << "Usage: " << con_reset << argv[0] << " [--config <file>] [--debug] [--nofork] [--nolog]" << std::endl
330 						<< std::string(strlen(argv[0]) + 8, ' ') << "[--nopid] [--runasroot] [--version]" << std::endl;
331 					ServerInstance->Exit(EXIT_STATUS_ARGV);
332 					break;
333 			}
334 		}
335 
336 		if (do_version)
337 		{
338 			std::cout << INSPIRCD_VERSION << std::endl;
339 			ServerInstance->Exit(EXIT_STATUS_NOERROR);
340 		}
341 
342 		// Store the relevant parsed arguments
343 		ServerInstance->Config->cmdline.forcedebug = !!do_debug;
344 		ServerInstance->Config->cmdline.nofork = !!do_nofork;
345 		ServerInstance->Config->cmdline.runasroot = !!do_runasroot;
346 		ServerInstance->Config->cmdline.writelog = !do_nolog;
347 		ServerInstance->Config->cmdline.writepid = !do_nopid;
348 	}
349 	// Seeds the random number generator if applicable.
SeedRng(timespec ts)350 	void SeedRng(timespec ts)
351 	{
352 #if defined _WIN32
353 		srand(ts.tv_nsec ^ ts.tv_sec);
354 #elif !defined HAS_ARC4RANDOM_BUF
355 		srandom(ts.tv_nsec ^ ts.tv_sec);
356 #endif
357 	}
358 
359 	// Sets handlers for various process signals.
SetSignals()360 	void SetSignals()
361 	{
362 #ifndef _WIN32
363 		signal(SIGALRM, SIG_IGN);
364 		signal(SIGCHLD, SIG_IGN);
365 		signal(SIGHUP, InspIRCd::SetSignal);
366 		signal(SIGPIPE, SIG_IGN);
367 		signal(SIGUSR1, SIG_IGN);
368 		signal(SIGUSR2, SIG_IGN);
369 		signal(SIGXFSZ, SIG_IGN);
370 #endif
371 		signal(SIGTERM, InspIRCd::SetSignal);
372 	}
373 
TryBindPorts()374 	void TryBindPorts()
375 	{
376 		FailedPortList pl;
377 		ServerInstance->BindPorts(pl);
378 
379 		if (!pl.empty())
380 		{
381 			std::cout << con_red << "Warning!" << con_reset << " Some of your listener" << (pl.size() == 1 ? "s" : "") << " failed to bind:" << std::endl
382 				<< std::endl;
383 
384 			for (FailedPortList::const_iterator iter = pl.begin(); iter != pl.end(); ++iter)
385 			{
386 				const FailedPort& fp = *iter;
387 				std::cout << "  " << con_bright << fp.sa.str() << con_reset << ": " << strerror(fp.error) << '.' << std::endl
388 					<< "  " << "Created from <bind> tag at " << fp.tag->getTagLocation() << std::endl
389 					<< std::endl;
390 			}
391 
392 			std::cout << con_bright << "Hints:" << con_reset << std::endl
393 				<< "- For TCP/IP listeners try using a public IP address in <bind:address> instead" << std::endl
394 				<< "  of * or leaving it blank." << std::endl
395 				<< "- For UNIX socket listeners try enabling <bind:rewrite> to replace old sockets." << std::endl;
396 		}
397 	}
398 
399 	// Required for returning the proper value of EXIT_SUCCESS for the parent process.
VoidSignalHandler(int)400 	void VoidSignalHandler(int)
401 	{
402 		exit(EXIT_STATUS_NOERROR);
403 	}
404 }
405 
Cleanup()406 void InspIRCd::Cleanup()
407 {
408 	// Close all listening sockets
409 	for (unsigned int i = 0; i < ports.size(); i++)
410 	{
411 		ports[i]->cull();
412 		delete ports[i];
413 	}
414 	ports.clear();
415 
416 	// Tell modules that we're shutting down.
417 	const std::string quitmsg = "Server shutting down";
418 	FOREACH_MOD(OnShutdown, (quitmsg));
419 
420 	// Disconnect all local users
421 	const UserManager::LocalList& list = Users.GetLocalUsers();
422 	while (!list.empty())
423 		ServerInstance->Users.QuitUser(list.front(), quitmsg);
424 
425 	GlobalCulls.Apply();
426 	Modules->UnloadAll();
427 
428 	/* Delete objects dynamically allocated in constructor (destructor would be more appropriate, but we're likely exiting) */
429 	/* Must be deleted before modes as it decrements modelines */
430 	if (FakeClient)
431 	{
432 		delete FakeClient->server;
433 		FakeClient->cull();
434 	}
435 	stdalgo::delete_zero(this->FakeClient);
436 	stdalgo::delete_zero(this->XLines);
437 	stdalgo::delete_zero(this->Config);
438 	SocketEngine::Deinit();
439 	Logs->CloseLogs();
440 }
441 
WritePID(const std::string & filename,bool exitonfail)442 void InspIRCd::WritePID(const std::string& filename, bool exitonfail)
443 {
444 #ifndef _WIN32
445 	if (!ServerInstance->Config->cmdline.writepid)
446 	{
447 		this->Logs->Log("STARTUP", LOG_DEFAULT, "--nopid specified on command line; PID file not written.");
448 		return;
449 	}
450 
451 	std::string fname = ServerInstance->Config->Paths.PrependRuntime(filename.empty() ? "inspircd.pid" : filename);
452 	std::ofstream outfile(fname.c_str());
453 	if (outfile.is_open())
454 	{
455 		outfile << getpid();
456 		outfile.close();
457 	}
458 	else
459 	{
460 		if (exitonfail)
461 			std::cout << "Failed to write PID-file '" << fname << "', exiting." << std::endl;
462 		this->Logs->Log("STARTUP", LOG_DEFAULT, "Failed to write PID-file '%s'%s", fname.c_str(), (exitonfail ? ", exiting." : ""));
463 		if (exitonfail)
464 			Exit(EXIT_STATUS_PID);
465 	}
466 #endif
467 }
468 
InspIRCd(int argc,char ** argv)469 InspIRCd::InspIRCd(int argc, char** argv)
470 	: FakeClient(NULL)
471 	, ConfigFileName(INSPIRCD_CONFIG_PATH "/inspircd.conf")
472 	, ConfigThread(NULL)
473 	, Config(NULL)
474 	, XLines(NULL)
475 	, PI(&DefaultProtocolInterface)
476 	, GenRandom(&DefaultGenRandom)
477 	, IsChannel(&DefaultIsChannel)
478 	, IsNick(&DefaultIsNick)
479 	, IsIdent(&DefaultIsIdent)
480 {
481 	ServerInstance = this;
482 
483 	UpdateTime();
484 	this->startup_time = TIME.tv_sec;
485 
486 	IncreaseCoreDumpSize();
487 	SeedRng(TIME);
488 	SocketEngine::Init();
489 
490 	this->Config = new ServerConfig;
491 	dynamic_reference_base::reset_all();
492 	this->XLines = new XLineManager;
493 
494 	this->Config->cmdline.argv = argv;
495 	this->Config->cmdline.argc = argc;
496 	ParseOptions();
497 
498 	{
499 		ServiceProvider* provs[] =
500 		{
501 			&rfcevents.numeric, &rfcevents.join, &rfcevents.part, &rfcevents.kick, &rfcevents.quit, &rfcevents.nick,
502 			&rfcevents.mode, &rfcevents.topic, &rfcevents.privmsg, &rfcevents.invite, &rfcevents.ping, &rfcevents.pong,
503 			&rfcevents.error
504 		};
505 		Modules.AddServices(provs, sizeof(provs)/sizeof(provs[0]));
506 	}
507 
508 	std::cout << con_green << "InspIRCd - Internet Relay Chat Daemon" << con_reset << std::endl
509 		<< "See " << con_green << "/INFO" << con_reset << " for contributors & authors" << std::endl
510 		<< std::endl;
511 
512 	if (Config->cmdline.forcedebug)
513 	{
514 		FILE* newstdout = fdopen(dup(STDOUT_FILENO), "w");
515 		FileWriter* fw = new FileWriter(newstdout, 1);
516 		FileLogStream* fls = new FileLogStream(LOG_RAWIO, fw);
517 		Logs->AddLogTypes("*", fls, true);
518 	}
519 
520 	if (!FindConfigFile(ConfigFileName))
521 	{
522 		this->Logs->Log("STARTUP", LOG_DEFAULT, "Unable to open config file %s", ConfigFileName.c_str());
523 		std::cout << "ERROR: Cannot open config file: " << ConfigFileName << std::endl << "Exiting..." << std::endl;
524 		Exit(EXIT_STATUS_CONFIG);
525 	}
526 
527 	SetSignals();
528 	if (!Config->cmdline.runasroot)
529 		CheckRoot();
530 	if (!Config->cmdline.nofork)
531 		ForkIntoBackground();
532 
533 	std::cout << "InspIRCd Process ID: " << con_green << getpid() << con_reset << std::endl;
534 
535 	/* During startup we read the configuration now, not in
536 	 * a separate thread
537 	 */
538 	this->Config->Read();
539 	this->Config->Apply(NULL, "");
540 	Logs->OpenFileLogs();
541 
542 	// If we don't have a SID, generate one based on the server name and the server description
543 	if (Config->sid.empty())
544 		Config->sid = UIDGenerator::GenerateSID(Config->ServerName, Config->ServerDesc);
545 
546 	// Initialize the UID generator with our sid
547 	this->UIDGen.init(Config->sid);
548 
549 	// Create the server user for this server
550 	this->FakeClient = new FakeUser(Config->sid, Config->ServerName, Config->ServerDesc);
551 
552 	// This is needed as all new XLines are marked pending until ApplyLines() is called
553 	this->XLines->ApplyLines();
554 
555 	std::cout << std::endl;
556 
557 	TryBindPorts();
558 
559 	this->Modules->LoadAll();
560 
561 	// Build ISupport as ModuleManager::LoadAll() does not do it
562 	this->ISupport.Build();
563 
564 	std::cout << "InspIRCd is now running as '" << Config->ServerName << "'[" << Config->GetSID() << "] with " << SocketEngine::GetMaxFds() << " max open sockets" << std::endl;
565 
566 #ifndef _WIN32
567 	if (!Config->cmdline.nofork)
568 	{
569 		if (kill(getppid(), SIGTERM) == -1)
570 		{
571 			std::cout << "Error killing parent process: " << strerror(errno) << std::endl;
572 			Logs->Log("STARTUP", LOG_DEFAULT, "Error killing parent process: %s",strerror(errno));
573 		}
574 	}
575 
576 	/* Explicitly shut down stdio's stdin/stdout/stderr.
577 	 *
578 	 * The previous logic here was to only do this if stdio was connected to a controlling
579 	 * terminal.  However, we must do this always to avoid information leaks and other
580 	 * problems related to stdio.
581 	 *
582 	 * The only exception is if we are in debug mode.
583 	 *
584 	 *    -- nenolod
585 	 */
586 	if ((!Config->cmdline.nofork) && (!Config->cmdline.forcedebug))
587 	{
588 		int fd = open("/dev/null", O_RDWR);
589 
590 		fclose(stdin);
591 		fclose(stderr);
592 		fclose(stdout);
593 
594 		if (dup2(fd, STDIN_FILENO) < 0)
595 			Logs->Log("STARTUP", LOG_DEFAULT, "Failed to dup /dev/null to stdin.");
596 		if (dup2(fd, STDOUT_FILENO) < 0)
597 			Logs->Log("STARTUP", LOG_DEFAULT, "Failed to dup /dev/null to stdout.");
598 		if (dup2(fd, STDERR_FILENO) < 0)
599 			Logs->Log("STARTUP", LOG_DEFAULT, "Failed to dup /dev/null to stderr.");
600 		close(fd);
601 	}
602 	else
603 	{
604 		Logs->Log("STARTUP", LOG_DEFAULT, "Keeping pseudo-tty open as we are running in the foreground.");
605 	}
606 #else
607 	/* Set win32 service as running, if we are running as a service */
608 	SetServiceRunning();
609 
610 	// Handle forking
611 	if(!Config->cmdline.nofork)
612 	{
613 		FreeConsole();
614 	}
615 
616 	QueryPerformanceFrequency(&stats.QPFrequency);
617 #endif
618 
619 	WritePID(Config->PID);
620 	DropRoot();
621 
622 	Logs->Log("STARTUP", LOG_DEFAULT, "Startup complete as '%s'[%s], %lu max open sockets", Config->ServerName.c_str(),Config->GetSID().c_str(), SocketEngine::GetMaxFds());
623 }
624 
UpdateTime()625 void InspIRCd::UpdateTime()
626 {
627 #if defined HAS_CLOCK_GETTIME
628 	clock_gettime(CLOCK_REALTIME, &TIME);
629 #elif defined _WIN32
630 	SYSTEMTIME st;
631 	GetSystemTime(&st);
632 
633 	TIME.tv_sec = time(NULL);
634 	TIME.tv_nsec = st.wMilliseconds;
635 #else
636 	struct timeval tv;
637 	gettimeofday(&tv, NULL);
638 
639 	TIME.tv_sec = tv.tv_sec;
640 	TIME.tv_nsec = tv.tv_usec * 1000;
641 #endif
642 }
643 
Run()644 void InspIRCd::Run()
645 {
646 	UpdateTime();
647 	time_t OLDTIME = TIME.tv_sec;
648 
649 	while (true)
650 	{
651 		/* Check if there is a config thread which has finished executing but has not yet been freed */
652 		if (this->ConfigThread && this->ConfigThread->IsDone())
653 		{
654 			/* Rehash has completed */
655 			this->Logs->Log("CONFIG", LOG_DEBUG, "Detected ConfigThread exiting, tidying up...");
656 
657 			this->ConfigThread->Finish();
658 
659 			ConfigThread->join();
660 			delete ConfigThread;
661 			ConfigThread = NULL;
662 		}
663 
664 		UpdateTime();
665 
666 		/* Run background module timers every few seconds
667 		 * (the docs say modules should not rely on accurate
668 		 * timing using this event, so we dont have to
669 		 * time this exactly).
670 		 */
671 		if (TIME.tv_sec != OLDTIME)
672 		{
673 			CollectStats();
674 			CheckTimeSkip(OLDTIME, TIME.tv_sec);
675 
676 			OLDTIME = TIME.tv_sec;
677 
678 			if ((TIME.tv_sec % 3600) == 0)
679 				FOREACH_MOD(OnGarbageCollect, ());
680 
681 			Timers.TickTimers(TIME.tv_sec);
682 			Users->DoBackgroundUserStuff();
683 
684 			if ((TIME.tv_sec % 5) == 0)
685 			{
686 				FOREACH_MOD(OnBackgroundTimer, (TIME.tv_sec));
687 				SNO->FlushSnotices();
688 			}
689 		}
690 
691 		/* Call the socket engine to wait on the active
692 		 * file descriptors. The socket engine has everything's
693 		 * descriptors in its list... dns, modules, users,
694 		 * servers... so its nice and easy, just one call.
695 		 * This will cause any read or write events to be
696 		 * dispatched to their handlers.
697 		 */
698 		SocketEngine::DispatchTrialWrites();
699 		SocketEngine::DispatchEvents();
700 
701 		/* if any users were quit, take them out */
702 		GlobalCulls.Apply();
703 		AtomicActions.Run();
704 
705 		if (s_signal)
706 		{
707 			this->SignalHandler(s_signal);
708 			s_signal = 0;
709 		}
710 	}
711 }
712 
713 sig_atomic_t InspIRCd::s_signal = 0;
714 
SetSignal(int signal)715 void InspIRCd::SetSignal(int signal)
716 {
717 	s_signal = signal;
718 }
719 
720 /* On posix systems, the flow of the program starts right here, with
721  * ENTRYPOINT being a #define that defines main(). On Windows, ENTRYPOINT
722  * defines smain() and the real main() is in the service code under
723  * win32service.cpp. This allows the service control manager to control
724  * the process where we are running as a windows service.
725  */
726 ENTRYPOINT
727 {
728 	new InspIRCd(argc, argv);
729 	ServerInstance->Run();
730 	delete ServerInstance;
731 	return 0;
732 }
733