2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2020 Matt Schatz <genius3000@g3k.solutions>
5 * Copyright (C) 2018 Chris Novakovic <chrisnovakovic@users.noreply.github.com>
6 * Copyright (C) 2013, 2018-2021 Sadie Powell <sadie@witchery.services>
7 * Copyright (C) 2013 Adam <Adam@anope.org>
8 * Copyright (C) 2012-2014, 2016, 2018 Attila Molnar <attilamolnar@hush.com>
9 * Copyright (C) 2012 Robby <robby@chatbelgie.be>
10 * Copyright (C) 2012 ChrisTX <xpipe@hotmail.de>
11 * Copyright (C) 2012 Ariadne Conill <ariadne@dereferenced.org>
12 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
13 * Copyright (C) 2009 Uli Schlachter <psychon@inspircd.org>
14 * Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
15 * Copyright (C) 2007-2008, 2010 Craig Edwards <brain@inspircd.org>
16 * Copyright (C) 2007-2008 Robin Burchell <robin+git@viroteck.net>
17 * Copyright (C) 2007 Oliver Lupton <om@inspircd.org>
18 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
20 * This file is part of InspIRCd. InspIRCd is free software: you can
21 * redistribute it and/or modify it under the terms of the GNU General Public
22 * License as published by the Free Software Foundation, version 2.
24 * This program is distributed in the hope that it will be useful, but WITHOUT
25 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
26 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
29 * You should have received a copy of the GNU General Public License
30 * along with this program. If not, see <http://www.gnu.org/licenses/>.
39 #include <sys/resource.h>
41 #include <pwd.h> // setuid
42 #include <grp.h> // setgid
44 /** Manages formatting lines written to stderr on Windows. */
45 WindowsStream StandardError(STD_ERROR_HANDLE);
47 /** Manages formatting lines written to stdout on Windows. */
48 WindowsStream StandardOutput(STD_OUTPUT_HANDLE);
54 #include "exitcodes.h"
56 InspIRCd* ServerInstance = NULL;
58 /** Separate from the other casemap tables so that code *can* still exclusively rely on RFC casemapping
61 * This is provided as a pointer so that modules can change it to their custom mapping tables,
62 * e.g. for national character support.
64 unsigned const char *national_case_insensitive_map = rfc_case_insensitive_map;
67 /* Moved from exitcodes.h -- due to duplicate symbols -- Burlex
68 * XXX this is a bit ugly. -- w00t
70 const char* ExitCodes[] =
74 "Config file error", // 2
76 "POSIX fork failed", // 4
77 "Bad commandline parameters", // 5
78 "Can't write PID file", // 6
79 "SocketEngine could not initialize", // 7
80 "Refusing to start up as root", // 8
81 "Couldn't load module on startup", // 9
82 "Received SIGTERM" // 10
87 void VoidSignalHandler(int);
89 // Warns a user running as root that they probably shouldn't.
93 if (getegid() != 0 && geteuid() != 0)
96 std::cout << con_red << "Warning!" << con_reset << " You have started as root. Running as root is generally not required" << std::endl
97 << "and may allow an attacker to gain access to your system if they find a way to" << std::endl
98 << "exploit your IRC server." << std::endl
100 if (isatty(fileno(stdout)))
102 std::cout << "InspIRCd will start in 30 seconds. If you are sure that you need to run as root" << std::endl
103 << "then you can pass the " << con_bright << "--runasroot" << con_reset << " option to disable this wait." << std::endl;
108 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
109 << "option to disable this error." << std::endl;
110 ServerInstance->Exit(EXIT_STATUS_ROOT);
115 // Collects performance statistics for the STATS command.
120 if (getrusage(RUSAGE_SELF, &ru) == -1)
121 return; // Should never happen.
123 ServerInstance->stats.LastSampled.tv_sec = ServerInstance->Time();
124 ServerInstance->stats.LastSampled.tv_nsec = ServerInstance->Time_ns();
125 ServerInstance->stats.LastCPU = ru.ru_utime;
127 if (!QueryPerformanceCounter(&ServerInstance->stats.LastSampled))
128 return; // Should never happen.
130 FILETIME CreationTime;
134 GetProcessTimes(GetCurrentProcess(), &CreationTime, &ExitTime, &KernelTime, &UserTime);
136 ServerInstance->stats.LastCPU.dwHighDateTime = KernelTime.dwHighDateTime + UserTime.dwHighDateTime;
137 ServerInstance->stats.LastCPU.dwLowDateTime = KernelTime.dwLowDateTime + UserTime.dwLowDateTime;
141 // Checks whether the server clock has skipped too much and warn about it if it has.
142 void CheckTimeSkip(time_t oldtime, time_t newtime)
144 if (!ServerInstance->Config->TimeSkipWarn)
147 time_t timediff = newtime - oldtime;
149 if (timediff > ServerInstance->Config->TimeSkipWarn)
150 ServerInstance->SNO->WriteToSnoMask('a', "\002Performance warning!\002 Server clock jumped forwards by %lu seconds!", timediff);
152 else if (timediff < -ServerInstance->Config->TimeSkipWarn)
153 ServerInstance->SNO->WriteToSnoMask('a', "\002Performance warning!\002 Server clock jumped backwards by %lu seconds!", labs(timediff));
156 // Drops to the unprivileged user/group specified in <security:runas{user,group}>.
160 ConfigTag* security = ServerInstance->Config->ConfValue("security");
162 const std::string SetGroup = security->getString("runasgroup");
163 if (!SetGroup.empty())
166 if (setgroups(0, NULL) == -1)
168 ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "setgroups() failed (wtf?): %s", strerror(errno));
169 exit(EXIT_STATUS_CONFIG);
172 struct group* g = getgrnam(SetGroup.c_str());
175 ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "getgrnam(%s) failed (wrong group?): %s", SetGroup.c_str(), strerror(errno));
176 exit(EXIT_STATUS_CONFIG);
179 if (setgid(g->gr_gid) == -1)
181 ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "setgid(%d) failed (wrong group?): %s", g->gr_gid, strerror(errno));
182 exit(EXIT_STATUS_CONFIG);
186 const std::string SetUser = security->getString("runasuser");
187 if (!SetUser.empty())
190 struct passwd* u = getpwnam(SetUser.c_str());
193 ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "getpwnam(%s) failed (wrong user?): %s", SetUser.c_str(), strerror(errno));
194 exit(EXIT_STATUS_CONFIG);
197 if (setuid(u->pw_uid) == -1)
199 ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "setuid(%d) failed (wrong user?): %s", u->pw_uid, strerror(errno));
200 exit(EXIT_STATUS_CONFIG);
206 // Expands a path relative to the current working directory.
207 std::string ExpandPath(const char* path)
210 TCHAR configPath[MAX_PATH + 1];
211 if (GetFullPathName(path, MAX_PATH, configPath, NULL) > 0)
214 char configPath[PATH_MAX + 1];
215 if (realpath(path, configPath))
221 // Locates a config file on the file system.
222 bool FindConfigFile(std::string& path)
224 if (FileSystem::FileExists(path))
228 // Windows hides file extensions by default so try appending .txt to the path
229 // to help users who have that feature enabled and can't create .conf files.
230 const std::string txtpath = path + ".txt";
231 if (FileSystem::FileExists(txtpath))
233 path.assign(txtpath);
240 // Attempts to fork into the background.
241 void ForkIntoBackground()
244 // We use VoidSignalHandler whilst forking to avoid breaking daemon scripts
245 // if the parent process exits with SIGTERM (15) instead of EXIT_STATUS_NOERROR (0).
246 signal(SIGTERM, VoidSignalHandler);
249 int childpid = fork();
252 ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "fork() failed: %s", strerror(errno));
253 std::cout << con_red << "Error:" << con_reset << " unable to fork into background: " << strerror(errno);
254 ServerInstance->Exit(EXIT_STATUS_FORK);
256 else if (childpid > 0)
258 // Wait until the child process kills the parent so that the shell prompt
259 // doesnt display over the output. Sending a kill with a signal of 0 just
260 // checks that the child pid is still running. If it is not then an error
261 // happened and the parent should exit.
262 while (kill(childpid, 0) != -1)
264 exit(EXIT_STATUS_NOERROR);
269 signal(SIGTERM, InspIRCd::SetSignal);
270 SocketEngine::RecoverFromFork();
275 // Increase the size of a core dump file to improve debugging problems.
276 void IncreaseCoreDumpSize()
281 if (getrlimit(RLIMIT_CORE, &rl) == -1)
283 ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "Unable to increase core dump size: getrlimit(RLIMIT_CORE) failed: %s", strerror(errno));
287 rl.rlim_cur = rl.rlim_max;
288 if (setrlimit(RLIMIT_CORE, &rl) == -1)
289 ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "Unable to increase core dump size: setrlimit(RLIMIT_CORE) failed: %s", strerror(errno));
293 // Parses the command line options.
296 int do_debug = 0, do_nofork = 0, do_nolog = 0;
297 int do_nopid = 0, do_runasroot = 0, do_version = 0;
298 struct option longopts[] =
300 { "config", required_argument, NULL, 'c' },
301 { "debug", no_argument, &do_debug, 1 },
302 { "nofork", no_argument, &do_nofork, 1 },
303 { "nolog", no_argument, &do_nolog, 1 },
304 { "nopid", no_argument, &do_nopid, 1 },
305 { "runasroot", no_argument, &do_runasroot, 1 },
306 { "version", no_argument, &do_version, 1 },
310 char** argv = ServerInstance->Config->cmdline.argv;
312 while ((ret = getopt_long(ServerInstance->Config->cmdline.argc, argv, ":c:", longopts, NULL)) != -1)
317 // A long option was specified.
321 // The -c option was specified.
322 ServerInstance->ConfigFileName = ExpandPath(optarg);
326 // An unknown option was specified.
327 std::cout << con_red << "Error:" << con_reset << " unknown option '" << argv[optind] << "'." << std::endl
328 << con_bright << "Usage: " << con_reset << argv[0] << " [--config <file>] [--debug] [--nofork] [--nolog]" << std::endl
329 << std::string(strlen(argv[0]) + 8, ' ') << "[--nopid] [--runasroot] [--version]" << std::endl;
330 ServerInstance->Exit(EXIT_STATUS_ARGV);
337 std::cout << INSPIRCD_VERSION << std::endl;
338 ServerInstance->Exit(EXIT_STATUS_NOERROR);
341 // Store the relevant parsed arguments
342 ServerInstance->Config->cmdline.forcedebug = !!do_debug;
343 ServerInstance->Config->cmdline.nofork = !!do_nofork;
344 ServerInstance->Config->cmdline.runasroot = !!do_runasroot;
345 ServerInstance->Config->cmdline.writelog = !do_nolog;
346 ServerInstance->Config->cmdline.writepid = !do_nopid;
348 // Seeds the random number generator if applicable.
349 void SeedRng(timespec ts)
352 srand(ts.tv_nsec ^ ts.tv_sec);
353 #elif !defined HAS_ARC4RANDOM_BUF
354 srandom(ts.tv_nsec ^ ts.tv_sec);
358 // Sets handlers for various process signals.
362 signal(SIGALRM, SIG_IGN);
363 signal(SIGCHLD, SIG_IGN);
364 signal(SIGHUP, InspIRCd::SetSignal);
365 signal(SIGPIPE, SIG_IGN);
366 signal(SIGUSR1, SIG_IGN);
367 signal(SIGUSR2, SIG_IGN);
368 signal(SIGXFSZ, SIG_IGN);
370 signal(SIGTERM, InspIRCd::SetSignal);
376 ServerInstance->BindPorts(pl);
380 std::cout << con_red << "Warning!" << con_reset << " Some of your listener" << (pl.size() == 1 ? "s" : "") << " failed to bind:" << std::endl
383 for (FailedPortList::const_iterator iter = pl.begin(); iter != pl.end(); ++iter)
385 const FailedPort& fp = *iter;
386 std::cout << " " << con_bright << fp.sa.str() << con_reset << ": " << strerror(fp.error) << '.' << std::endl
387 << " " << "Created from <bind> tag at " << fp.tag->getTagLocation() << std::endl
391 std::cout << con_bright << "Hints:" << con_reset << std::endl
392 << "- For TCP/IP listeners try using a public IP address in <bind:address> instead" << std::endl
393 << " of * or leaving it blank." << std::endl
394 << "- For UNIX socket listeners try enabling <bind:rewrite> to replace old sockets." << std::endl;
398 // Required for returning the proper value of EXIT_SUCCESS for the parent process.
399 void VoidSignalHandler(int)
401 exit(EXIT_STATUS_NOERROR);
405 void InspIRCd::Cleanup()
407 // Close all listening sockets
408 for (unsigned int i = 0; i < ports.size(); i++)
415 // Tell modules that we're shutting down.
416 const std::string quitmsg = "Server shutting down";
417 FOREACH_MOD(OnShutdown, (quitmsg));
419 // Disconnect all local users
420 const UserManager::LocalList& list = Users.GetLocalUsers();
421 while (!list.empty())
422 ServerInstance->Users.QuitUser(list.front(), quitmsg);
425 Modules->UnloadAll();
427 /* Delete objects dynamically allocated in constructor (destructor would be more appropriate, but we're likely exiting) */
428 /* Must be deleted before modes as it decrements modelines */
431 delete FakeClient->server;
434 stdalgo::delete_zero(this->FakeClient);
435 stdalgo::delete_zero(this->XLines);
436 stdalgo::delete_zero(this->Config);
437 SocketEngine::Deinit();
441 void InspIRCd::WritePID(const std::string& filename, bool exitonfail)
444 if (!ServerInstance->Config->cmdline.writepid)
446 this->Logs->Log("STARTUP", LOG_DEFAULT, "--nopid specified on command line; PID file not written.");
450 std::string fname = ServerInstance->Config->Paths.PrependRuntime(filename.empty() ? "inspircd.pid" : filename);
451 std::ofstream outfile(fname.c_str());
452 if (outfile.is_open())
460 std::cout << "Failed to write PID-file '" << fname << "', exiting." << std::endl;
461 this->Logs->Log("STARTUP", LOG_DEFAULT, "Failed to write PID-file '%s'%s", fname.c_str(), (exitonfail ? ", exiting." : ""));
463 Exit(EXIT_STATUS_PID);
468 InspIRCd::InspIRCd(int argc, char** argv)
470 , ConfigFileName(INSPIRCD_CONFIG_PATH "/inspircd.conf")
474 , PI(&DefaultProtocolInterface)
475 , GenRandom(&DefaultGenRandom)
476 , IsChannel(&DefaultIsChannel)
477 , IsNick(&DefaultIsNick)
478 , IsIdent(&DefaultIsIdent)
480 ServerInstance = this;
483 this->startup_time = TIME.tv_sec;
485 IncreaseCoreDumpSize();
487 SocketEngine::Init();
489 this->Config = new ServerConfig;
490 dynamic_reference_base::reset_all();
491 this->XLines = new XLineManager;
493 this->Config->cmdline.argv = argv;
494 this->Config->cmdline.argc = argc;
498 ServiceProvider* provs[] =
500 &rfcevents.numeric, &rfcevents.join, &rfcevents.part, &rfcevents.kick, &rfcevents.quit, &rfcevents.nick,
501 &rfcevents.mode, &rfcevents.topic, &rfcevents.privmsg, &rfcevents.invite, &rfcevents.ping, &rfcevents.pong,
504 Modules.AddServices(provs, sizeof(provs)/sizeof(provs[0]));
507 std::cout << con_green << "InspIRCd - Internet Relay Chat Daemon" << con_reset << std::endl
508 << "See " << con_green << "/INFO" << con_reset << " for contributors & authors" << std::endl
511 if (Config->cmdline.forcedebug)
513 FILE* newstdout = fdopen(dup(STDOUT_FILENO), "w");
514 FileWriter* fw = new FileWriter(newstdout, 1);
515 FileLogStream* fls = new FileLogStream(LOG_RAWIO, fw);
516 Logs->AddLogTypes("*", fls, true);
519 if (!FindConfigFile(ConfigFileName))
521 this->Logs->Log("STARTUP", LOG_DEFAULT, "Unable to open config file %s", ConfigFileName.c_str());
522 std::cout << "ERROR: Cannot open config file: " << ConfigFileName << std::endl << "Exiting..." << std::endl;
523 Exit(EXIT_STATUS_CONFIG);
527 if (!Config->cmdline.runasroot)
529 if (!Config->cmdline.nofork)
530 ForkIntoBackground();
532 std::cout << "InspIRCd Process ID: " << con_green << getpid() << con_reset << std::endl;
534 /* During startup we read the configuration now, not in
537 this->Config->Read();
538 this->Config->Apply(NULL, "");
539 Logs->OpenFileLogs();
541 // If we don't have a SID, generate one based on the server name and the server description
542 if (Config->sid.empty())
543 Config->sid = UIDGenerator::GenerateSID(Config->ServerName, Config->ServerDesc);
545 // Initialize the UID generator with our sid
546 this->UIDGen.init(Config->sid);
548 // Create the server user for this server
549 this->FakeClient = new FakeUser(Config->sid, Config->ServerName, Config->ServerDesc);
551 // This is needed as all new XLines are marked pending until ApplyLines() is called
552 this->XLines->ApplyLines();
554 std::cout << std::endl;
558 this->Modules->LoadAll();
560 // Build ISupport as ModuleManager::LoadAll() does not do it
561 this->ISupport.Build();
563 std::cout << "InspIRCd is now running as '" << Config->ServerName << "'[" << Config->GetSID() << "] with " << SocketEngine::GetMaxFds() << " max open sockets" << std::endl;
566 if (!Config->cmdline.nofork)
568 if (kill(getppid(), SIGTERM) == -1)
570 std::cout << "Error killing parent process: " << strerror(errno) << std::endl;
571 Logs->Log("STARTUP", LOG_DEFAULT, "Error killing parent process: %s",strerror(errno));
575 /* Explicitly shut down stdio's stdin/stdout/stderr.
577 * The previous logic here was to only do this if stdio was connected to a controlling
578 * terminal. However, we must do this always to avoid information leaks and other
579 * problems related to stdio.
581 * The only exception is if we are in debug mode.
585 if ((!Config->cmdline.nofork) && (!Config->cmdline.forcedebug))
587 int fd = open("/dev/null", O_RDWR);
593 if (dup2(fd, STDIN_FILENO) < 0)
594 Logs->Log("STARTUP", LOG_DEFAULT, "Failed to dup /dev/null to stdin.");
595 if (dup2(fd, STDOUT_FILENO) < 0)
596 Logs->Log("STARTUP", LOG_DEFAULT, "Failed to dup /dev/null to stdout.");
597 if (dup2(fd, STDERR_FILENO) < 0)
598 Logs->Log("STARTUP", LOG_DEFAULT, "Failed to dup /dev/null to stderr.");
603 Logs->Log("STARTUP", LOG_DEFAULT, "Keeping pseudo-tty open as we are running in the foreground.");
606 /* Set win32 service as running, if we are running as a service */
610 if(!Config->cmdline.nofork)
615 QueryPerformanceFrequency(&stats.QPFrequency);
618 WritePID(Config->PID);
621 Logs->Log("STARTUP", LOG_DEFAULT, "Startup complete as '%s'[%s], %lu max open sockets", Config->ServerName.c_str(),Config->GetSID().c_str(), SocketEngine::GetMaxFds());
624 void InspIRCd::UpdateTime()
626 #if defined HAS_CLOCK_GETTIME
627 clock_gettime(CLOCK_REALTIME, &TIME);
632 TIME.tv_sec = time(NULL);
633 TIME.tv_nsec = st.wMilliseconds;
636 gettimeofday(&tv, NULL);
638 TIME.tv_sec = tv.tv_sec;
639 TIME.tv_nsec = tv.tv_usec * 1000;
646 time_t OLDTIME = TIME.tv_sec;
650 /* Check if there is a config thread which has finished executing but has not yet been freed */
651 if (this->ConfigThread && this->ConfigThread->IsDone())
653 /* Rehash has completed */
654 this->Logs->Log("CONFIG", LOG_DEBUG, "Detected ConfigThread exiting, tidying up...");
656 this->ConfigThread->Finish();
658 ConfigThread->join();
665 /* Run background module timers every few seconds
666 * (the docs say modules should not rely on accurate
667 * timing using this event, so we dont have to
668 * time this exactly).
670 if (TIME.tv_sec != OLDTIME)
673 CheckTimeSkip(OLDTIME, TIME.tv_sec);
675 OLDTIME = TIME.tv_sec;
677 if ((TIME.tv_sec % 3600) == 0)
678 FOREACH_MOD(OnGarbageCollect, ());
680 Timers.TickTimers(TIME.tv_sec);
681 Users->DoBackgroundUserStuff();
683 if ((TIME.tv_sec % 5) == 0)
685 FOREACH_MOD(OnBackgroundTimer, (TIME.tv_sec));
686 SNO->FlushSnotices();
690 /* Call the socket engine to wait on the active
691 * file descriptors. The socket engine has everything's
692 * descriptors in its list... dns, modules, users,
693 * servers... so its nice and easy, just one call.
694 * This will cause any read or write events to be
695 * dispatched to their handlers.
697 SocketEngine::DispatchTrialWrites();
698 SocketEngine::DispatchEvents();
700 /* if any users were quit, take them out */
706 this->SignalHandler(s_signal);
712 sig_atomic_t InspIRCd::s_signal = 0;
714 void InspIRCd::SetSignal(int signal)
719 /* On posix systems, the flow of the program starts right here, with
720 * ENTRYPOINT being a #define that defines main(). On Windows, ENTRYPOINT
721 * defines smain() and the real main() is in the service code under
722 * win32service.cpp. This allows the service control manager to control
723 * the process where we are running as a windows service.
727 new InspIRCd(argc, argv);
728 ServerInstance->Run();
729 delete ServerInstance;