2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2018 Chris Novakovic <chrisnovakovic@users.noreply.github.com>
5 * Copyright (C) 2013, 2017-2020 Sadie Powell <sadie@witchery.services>
6 * Copyright (C) 2013 Adam <Adam@anope.org>
7 * Copyright (C) 2012-2014, 2016, 2018 Attila Molnar <attilamolnar@hush.com>
8 * Copyright (C) 2012 William Pitcock <nenolod@dereferenced.org>
9 * Copyright (C) 2012 Robby <robby@chatbelgie.be>
10 * Copyright (C) 2012 ChrisTX <xpipe@hotmail.de>
11 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
12 * Copyright (C) 2009 Uli Schlachter <psychon@inspircd.org>
13 * Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
14 * Copyright (C) 2007-2008, 2010 Craig Edwards <brain@inspircd.org>
15 * Copyright (C) 2007-2008 Robin Burchell <robin+git@viroteck.net>
16 * Copyright (C) 2007 Oliver Lupton <om@inspircd.org>
17 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
19 * This file is part of InspIRCd. InspIRCd is free software: you can
20 * redistribute it and/or modify it under the terms of the GNU General Public
21 * License as published by the Free Software Foundation, version 2.
23 * This program is distributed in the hope that it will be useful, but WITHOUT
24 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
25 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
28 * You should have received a copy of the GNU General Public License
29 * along with this program. If not, see <http://www.gnu.org/licenses/>.
38 #include <sys/resource.h>
40 #include <pwd.h> // setuid
41 #include <grp.h> // setgid
43 WORD g_wOriginalColors;
44 WORD g_wBackgroundColor;
51 #include "exitcodes.h"
53 InspIRCd* ServerInstance = NULL;
55 /** Seperate from the other casemap tables so that code *can* still exclusively rely on RFC casemapping
58 * This is provided as a pointer so that modules can change it to their custom mapping tables,
59 * e.g. for national character support.
61 unsigned const char *national_case_insensitive_map = rfc_case_insensitive_map;
64 /* Moved from exitcodes.h -- due to duplicate symbols -- Burlex
65 * XXX this is a bit ugly. -- w00t
67 const char* ExitCodes[] =
71 "Config file error", // 2
73 "POSIX fork failed", // 4
74 "Bad commandline parameters", // 5
75 "Can't write PID file", // 6
76 "SocketEngine could not initialize", // 7
77 "Refusing to start up as root", // 8
78 "Couldn't load module on startup", // 9
79 "Received SIGTERM" // 10
84 void VoidSignalHandler(int);
86 // Warns a user running as root that they probably shouldn't.
90 if (getegid() != 0 && geteuid() != 0)
93 std::cout << con_red << "Warning!" << con_reset << " You have started as root. Running as root is generally not required" << std::endl
94 << "and may allow an attacker to gain access to your system if they find a way to" << std::endl
95 << "exploit your IRC server." << std::endl
97 if (isatty(fileno(stdout)))
99 std::cout << "InspIRCd will start in 30 seconds. If you are sure that you need to run as root" << std::endl
100 << "then you can pass the " << con_bright << "--runasroot" << con_reset << " option to disable this wait." << std::endl;
105 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
106 << "option to disable this error." << std::endl;
107 ServerInstance->Exit(EXIT_STATUS_ROOT);
112 // Collects performance statistics for the STATS command.
117 if (getrusage(RUSAGE_SELF, &ru) == -1)
118 return; // Should never happen.
120 ServerInstance->stats.LastSampled.tv_sec = ServerInstance->Time();
121 ServerInstance->stats.LastSampled.tv_nsec = ServerInstance->Time_ns();
122 ServerInstance->stats.LastCPU = ru.ru_utime;
124 if (!QueryPerformanceCounter(&ServerInstance->stats.LastSampled))
125 return; // Should never happen.
127 FILETIME CreationTime;
131 GetProcessTimes(GetCurrentProcess(), &CreationTime, &ExitTime, &KernelTime, &UserTime);
133 ServerInstance->stats.LastCPU.dwHighDateTime = KernelTime.dwHighDateTime + UserTime.dwHighDateTime;
134 ServerInstance->stats.LastCPU.dwLowDateTime = KernelTime.dwLowDateTime + UserTime.dwLowDateTime;
138 // Checks whether the server clock has skipped too much and warn about it if it has.
139 void CheckTimeSkip(time_t oldtime, time_t newtime)
141 if (!ServerInstance->Config->TimeSkipWarn)
144 time_t timediff = oldtime - newtime;
146 if (timediff > ServerInstance->Config->TimeSkipWarn)
147 ServerInstance->SNO->WriteToSnoMask('a', "\002Performance warning!\002 Server clock jumped forwards by %lu seconds!", timediff);
149 else if (timediff < -ServerInstance->Config->TimeSkipWarn)
150 ServerInstance->SNO->WriteToSnoMask('a', "\002Performance warning!\002 Server clock jumped backwards by %lu seconds!", labs(timediff));
153 // Drops to the unprivileged user/group specified in <security:runas{user,group}>.
157 ConfigTag* security = ServerInstance->Config->ConfValue("security");
159 const std::string SetGroup = security->getString("runasgroup");
160 if (!SetGroup.empty())
163 if (setgroups(0, NULL) == -1)
165 ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "setgroups() failed (wtf?): %s", strerror(errno));
166 exit(EXIT_STATUS_CONFIG);
169 struct group* g = getgrnam(SetGroup.c_str());
172 ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "getgrnam(%s) failed (wrong group?): %s", SetGroup.c_str(), strerror(errno));
173 exit(EXIT_STATUS_CONFIG);
176 if (setgid(g->gr_gid) == -1)
178 ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "setgid(%d) failed (wrong group?): %s", g->gr_gid, strerror(errno));
179 exit(EXIT_STATUS_CONFIG);
183 const std::string SetUser = security->getString("runasuser");
184 if (!SetUser.empty())
187 struct passwd* u = getpwnam(SetUser.c_str());
190 ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "getpwnam(%s) failed (wrong user?): %s", SetUser.c_str(), strerror(errno));
191 exit(EXIT_STATUS_CONFIG);
194 if (setuid(u->pw_uid) == -1)
196 ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "setuid(%d) failed (wrong user?): %s", u->pw_uid, strerror(errno));
197 exit(EXIT_STATUS_CONFIG);
203 // Expands a path relative to the current working directory.
204 std::string ExpandPath(const char* path)
207 TCHAR configPath[MAX_PATH + 1];
208 if (GetFullPathName(path, MAX_PATH, configPath, NULL) > 0)
211 char configPath[PATH_MAX + 1];
212 if (realpath(path, configPath))
218 // Locates a config file on the file system.
219 bool FindConfigFile(std::string& path)
221 if (FileSystem::FileExists(path))
225 // Windows hides file extensions by default so try appending .txt to the path
226 // to help users who have that feature enabled and can't create .conf files.
227 const std::string txtpath = path + ".txt";
228 if (FileSystem::FileExists(txtpath))
230 path.assign(txtpath);
237 // Attempts to fork into the background.
238 void ForkIntoBackground()
241 // We use VoidSignalHandler whilst forking to avoid breaking daemon scripts
242 // if the parent process exits with SIGTERM (15) instead of EXIT_STATUS_NOERROR (0).
243 signal(SIGTERM, VoidSignalHandler);
246 int childpid = fork();
249 ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "fork() failed: %s", strerror(errno));
250 std::cout << con_red << "Error:" << con_reset << " unable to fork into background: " << strerror(errno);
251 ServerInstance->Exit(EXIT_STATUS_FORK);
253 else if (childpid > 0)
255 // Wait until the child process kills the parent so that the shell prompt
256 // doesnt display over the output. Sending a kill with a signal of 0 just
257 // checks that the child pid is still running. If it is not then an error
258 // happened and the parent should exit.
259 while (kill(childpid, 0) != -1)
261 exit(EXIT_STATUS_NOERROR);
266 signal(SIGTERM, InspIRCd::SetSignal);
267 SocketEngine::RecoverFromFork();
272 // Increase the size of a core dump file to improve debugging problems.
273 void IncreaseCoreDumpSize()
278 if (getrlimit(RLIMIT_CORE, &rl) == -1)
280 ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "Unable to increase core dump size: getrlimit(RLIMIT_CORE) failed: %s", strerror(errno));
284 rl.rlim_cur = rl.rlim_max;
285 if (setrlimit(RLIMIT_CORE, &rl) == -1)
286 ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "Unable to increase core dump size: setrlimit(RLIMIT_CORE) failed: %s", strerror(errno));
290 // Parses the command line options.
293 int do_debug = 0, do_nofork = 0, do_nolog = 0;
294 int do_nopid = 0, do_runasroot = 0, do_version = 0;
295 struct option longopts[] =
297 { "config", required_argument, NULL, 'c' },
298 { "debug", no_argument, &do_debug, 1 },
299 { "nofork", no_argument, &do_nofork, 1 },
300 { "nolog", no_argument, &do_nolog, 1 },
301 { "nopid", no_argument, &do_nopid, 1 },
302 { "runasroot", no_argument, &do_runasroot, 1 },
303 { "version", no_argument, &do_version, 1 },
307 char** argv = ServerInstance->Config->cmdline.argv;
309 while ((ret = getopt_long(ServerInstance->Config->cmdline.argc, argv, ":c:", longopts, NULL)) != -1)
314 // A long option was specified.
318 // The -c option was specified.
319 ServerInstance->ConfigFileName = ExpandPath(optarg);
323 // An unknown option was specified.
324 std::cout << con_red << "Error:" << con_reset << " unknown option '" << argv[optind - 1] << "'." << std::endl
325 << con_bright << "Usage: " << con_reset << argv[0] << " [--config <file>] [--debug] [--nofork] [--nolog]" << std::endl
326 << std::string(strlen(argv[0]) + 8, ' ') << "[--nopid] [--runasroot] [--version]" << std::endl;
327 ServerInstance->Exit(EXIT_STATUS_ARGV);
334 std::cout << std::endl << INSPIRCD_VERSION << std::endl;
335 ServerInstance->Exit(EXIT_STATUS_NOERROR);
338 // Store the relevant parsed arguments
339 ServerInstance->Config->cmdline.forcedebug = !!do_debug;
340 ServerInstance->Config->cmdline.nofork = !!do_nofork;
341 ServerInstance->Config->cmdline.runasroot = !!do_runasroot;
342 ServerInstance->Config->cmdline.writelog = !do_nolog;
343 ServerInstance->Config->cmdline.writepid = !do_nopid;
345 // Seeds the random number generator if applicable.
346 void SeedRng(timespec ts)
349 srand(ts.tv_nsec ^ ts.tv_sec);
350 #elif !defined HAS_ARC4RANDOM_BUF
351 srandom(ts.tv_nsec ^ ts.tv_sec);
355 // Sets handlers for various process signals.
359 signal(SIGALRM, SIG_IGN);
360 signal(SIGCHLD, SIG_IGN);
361 signal(SIGHUP, InspIRCd::SetSignal);
362 signal(SIGPIPE, SIG_IGN);
363 signal(SIGUSR1, SIG_IGN);
364 signal(SIGUSR2, SIG_IGN);
365 signal(SIGXFSZ, SIG_IGN);
367 signal(SIGTERM, InspIRCd::SetSignal);
373 ServerInstance->BindPorts(pl);
377 std::cout << con_red << "Warning!" << con_reset << " Some of your listener" << (pl.size() == 1 ? "s" : "") << " failed to bind:" << std::endl
380 for (FailedPortList::const_iterator iter = pl.begin(); iter != pl.end(); ++iter)
382 const FailedPort& fp = *iter;
383 std::cout << " " << con_bright << fp.sa.str() << con_reset << ": " << strerror(fp.error) << '.' << std::endl
384 << " " << "Created from <bind> tag at " << fp.tag->getTagLocation() << std::endl
388 std::cout << con_bright << "Hints:" << con_reset << std::endl
389 << "- For TCP/IP listeners try using a public IP address in <bind:address> instead" << std::endl
390 << " of * of leaving it blank." << std::endl
391 << "- For UNIX socket listeners try enabling <bind:rewrite> to replace old sockets." << std::endl;
395 // Required for returning the proper value of EXIT_SUCCESS for the parent process.
396 void VoidSignalHandler(int)
398 exit(EXIT_STATUS_NOERROR);
402 void InspIRCd::Cleanup()
404 // Close all listening sockets
405 for (unsigned int i = 0; i < ports.size(); i++)
412 // Tell modules that we're shutting down.
413 const std::string quitmsg = "Server shutting down";
414 FOREACH_MOD(OnShutdown, (quitmsg));
416 // Disconnect all local users
417 const UserManager::LocalList& list = Users.GetLocalUsers();
418 while (!list.empty())
419 ServerInstance->Users.QuitUser(list.front(), quitmsg);
422 Modules->UnloadAll();
424 /* Delete objects dynamically allocated in constructor (destructor would be more appropriate, but we're likely exiting) */
425 /* Must be deleted before modes as it decrements modelines */
428 delete FakeClient->server;
431 stdalgo::delete_zero(this->FakeClient);
432 stdalgo::delete_zero(this->XLines);
433 stdalgo::delete_zero(this->Config);
434 SocketEngine::Deinit();
438 void InspIRCd::WritePID(const std::string& filename, bool exitonfail)
441 if (!ServerInstance->Config->cmdline.writepid)
443 this->Logs->Log("STARTUP", LOG_DEFAULT, "--nopid specified on command line; PID file not written.");
447 std::string fname = ServerInstance->Config->Paths.PrependData(filename.empty() ? "inspircd.pid" : filename);
448 std::ofstream outfile(fname.c_str());
449 if (outfile.is_open())
457 std::cout << "Failed to write PID-file '" << fname << "', exiting." << std::endl;
458 this->Logs->Log("STARTUP", LOG_DEFAULT, "Failed to write PID-file '%s'%s", fname.c_str(), (exitonfail ? ", exiting." : ""));
460 Exit(EXIT_STATUS_PID);
465 InspIRCd::InspIRCd(int argc, char** argv)
467 , ConfigFileName(INSPIRCD_CONFIG_PATH "/inspircd.conf")
471 , PI(&DefaultProtocolInterface)
472 , GenRandom(&DefaultGenRandom)
473 , IsChannel(&DefaultIsChannel)
474 , IsNick(&DefaultIsNick)
475 , IsIdent(&DefaultIsIdent)
477 ServerInstance = this;
480 this->startup_time = TIME.tv_sec;
482 IncreaseCoreDumpSize();
484 SocketEngine::Init();
486 this->Config = new ServerConfig;
487 dynamic_reference_base::reset_all();
488 this->XLines = new XLineManager;
490 this->Config->cmdline.argv = argv;
491 this->Config->cmdline.argc = argc;
494 // Initialize the console values
495 g_hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
496 CONSOLE_SCREEN_BUFFER_INFO bufinf;
497 if(GetConsoleScreenBufferInfo(g_hStdout, &bufinf))
499 g_wOriginalColors = bufinf.wAttributes & 0x00FF;
500 g_wBackgroundColor = bufinf.wAttributes & 0x00F0;
504 g_wOriginalColors = FOREGROUND_RED|FOREGROUND_BLUE|FOREGROUND_GREEN;
505 g_wBackgroundColor = 0;
510 ServiceProvider* provs[] =
512 &rfcevents.numeric, &rfcevents.join, &rfcevents.part, &rfcevents.kick, &rfcevents.quit, &rfcevents.nick,
513 &rfcevents.mode, &rfcevents.topic, &rfcevents.privmsg, &rfcevents.invite, &rfcevents.ping, &rfcevents.pong,
516 Modules.AddServices(provs, sizeof(provs)/sizeof(provs[0]));
519 std::cout << con_green << "InspIRCd - Internet Relay Chat Daemon" << con_reset << std::endl
520 << "See " << con_green << "/INFO" << con_reset << " for contributors & authors" << std::endl
524 if (Config->cmdline.forcedebug)
526 FileWriter* fw = new FileWriter(stdout, 1);
527 FileLogStream* fls = new FileLogStream(LOG_RAWIO, fw);
528 Logs->AddLogTypes("*", fls, true);
531 if (!FindConfigFile(ConfigFileName))
533 this->Logs->Log("STARTUP", LOG_DEFAULT, "Unable to open config file %s", ConfigFileName.c_str());
534 std::cout << "ERROR: Cannot open config file: " << ConfigFileName << std::endl << "Exiting..." << std::endl;
535 Exit(EXIT_STATUS_CONFIG);
539 if (!Config->cmdline.runasroot)
541 if (!Config->cmdline.nofork)
542 ForkIntoBackground();
544 std::cout << "InspIRCd Process ID: " << con_green << getpid() << con_reset << std::endl;
546 /* During startup we read the configuration now, not in
549 this->Config->Read();
550 this->Config->Apply(NULL, "");
551 Logs->OpenFileLogs();
553 // If we don't have a SID, generate one based on the server name and the server description
554 if (Config->sid.empty())
555 Config->sid = UIDGenerator::GenerateSID(Config->ServerName, Config->ServerDesc);
557 // Initialize the UID generator with our sid
558 this->UIDGen.init(Config->sid);
560 // Create the server user for this server
561 this->FakeClient = new FakeUser(Config->sid, Config->ServerName, Config->ServerDesc);
563 // This is needed as all new XLines are marked pending until ApplyLines() is called
564 this->XLines->ApplyLines();
566 std::cout << std::endl;
570 this->Modules->LoadAll();
572 // Build ISupport as ModuleManager::LoadAll() does not do it
573 this->ISupport.Build();
575 std::cout << "InspIRCd is now running as '" << Config->ServerName << "'[" << Config->GetSID() << "] with " << SocketEngine::GetMaxFds() << " max open sockets" << std::endl;
578 if (!Config->cmdline.nofork)
580 if (kill(getppid(), SIGTERM) == -1)
582 std::cout << "Error killing parent process: " << strerror(errno) << std::endl;
583 Logs->Log("STARTUP", LOG_DEFAULT, "Error killing parent process: %s",strerror(errno));
587 /* Explicitly shut down stdio's stdin/stdout/stderr.
589 * The previous logic here was to only do this if stdio was connected to a controlling
590 * terminal. However, we must do this always to avoid information leaks and other
591 * problems related to stdio.
593 * The only exception is if we are in debug mode.
597 if ((!Config->cmdline.nofork) && (!Config->cmdline.forcedebug))
599 int fd = open("/dev/null", O_RDWR);
605 if (dup2(fd, STDIN_FILENO) < 0)
606 Logs->Log("STARTUP", LOG_DEFAULT, "Failed to dup /dev/null to stdin.");
607 if (dup2(fd, STDOUT_FILENO) < 0)
608 Logs->Log("STARTUP", LOG_DEFAULT, "Failed to dup /dev/null to stdout.");
609 if (dup2(fd, STDERR_FILENO) < 0)
610 Logs->Log("STARTUP", LOG_DEFAULT, "Failed to dup /dev/null to stderr.");
615 Logs->Log("STARTUP", LOG_DEFAULT, "Keeping pseudo-tty open as we are running in the foreground.");
618 /* Set win32 service as running, if we are running as a service */
622 if(!Config->cmdline.nofork)
627 QueryPerformanceFrequency(&stats.QPFrequency);
630 WritePID(Config->PID);
633 Logs->Log("STARTUP", LOG_DEFAULT, "Startup complete as '%s'[%s], %lu max open sockets", Config->ServerName.c_str(),Config->GetSID().c_str(), SocketEngine::GetMaxFds());
636 void InspIRCd::UpdateTime()
638 #if defined HAS_CLOCK_GETTIME
639 clock_gettime(CLOCK_REALTIME, &TIME);
644 TIME.tv_sec = time(NULL);
645 TIME.tv_nsec = st.wMilliseconds;
648 gettimeofday(&tv, NULL);
650 TIME.tv_sec = tv.tv_sec;
651 TIME.tv_nsec = tv.tv_usec * 1000;
658 time_t OLDTIME = TIME.tv_sec;
662 /* Check if there is a config thread which has finished executing but has not yet been freed */
663 if (this->ConfigThread && this->ConfigThread->IsDone())
665 /* Rehash has completed */
666 this->Logs->Log("CONFIG", LOG_DEBUG, "Detected ConfigThread exiting, tidying up...");
668 this->ConfigThread->Finish();
670 ConfigThread->join();
677 /* Run background module timers every few seconds
678 * (the docs say modules shouldnt rely on accurate
679 * timing using this event, so we dont have to
680 * time this exactly).
682 if (TIME.tv_sec != OLDTIME)
685 CheckTimeSkip(OLDTIME, TIME.tv_sec);
687 OLDTIME = TIME.tv_sec;
689 if ((TIME.tv_sec % 3600) == 0)
690 FOREACH_MOD(OnGarbageCollect, ());
692 Timers.TickTimers(TIME.tv_sec);
693 Users->DoBackgroundUserStuff();
695 if ((TIME.tv_sec % 5) == 0)
697 FOREACH_MOD(OnBackgroundTimer, (TIME.tv_sec));
698 SNO->FlushSnotices();
702 /* Call the socket engine to wait on the active
703 * file descriptors. The socket engine has everything's
704 * descriptors in its list... dns, modules, users,
705 * servers... so its nice and easy, just one call.
706 * This will cause any read or write events to be
707 * dispatched to their handlers.
709 SocketEngine::DispatchTrialWrites();
710 SocketEngine::DispatchEvents();
712 /* if any users were quit, take them out */
718 this->SignalHandler(s_signal);
724 sig_atomic_t InspIRCd::s_signal = 0;
726 void InspIRCd::SetSignal(int signal)
731 /* On posix systems, the flow of the program starts right here, with
732 * ENTRYPOINT being a #define that defines main(). On Windows, ENTRYPOINT
733 * defines smain() and the real main() is in the service code under
734 * win32service.cpp. This allows the service control manager to control
735 * the process where we are running as a windows service.
739 new InspIRCd(argc, argv);
740 ServerInstance->Run();
741 delete ServerInstance;