2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2012 William Pitcock <nenolod@dereferenced.org>
5 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
6 * Copyright (C) 2003-2008 Craig Edwards <craigedwards@brainbox.cc>
7 * Copyright (C) 2008 Uli Schlachter <psychon@znc.in>
8 * Copyright (C) 2006-2008 Robin Burchell <robin+git@viroteck.net>
9 * Copyright (C) 2006-2007 Oliver Lupton <oliverlupton@gmail.com>
10 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
11 * Copyright (C) 2007 Burlex <???@???>
12 * Copyright (C) 2003 Craig McLure <craig@chatspike.net>
13 * Copyright (C) 2003 randomdan <???@???>
15 * This file is part of InspIRCd. InspIRCd is free software: you can
16 * redistribute it and/or modify it under the terms of the GNU General Public
17 * License as published by the Free Software Foundation, version 2.
19 * This program is distributed in the hope that it will be useful, but WITHOUT
20 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
21 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
24 * You should have received a copy of the GNU General Public License
25 * along with this program. If not, see <http://www.gnu.org/licenses/>.
36 #include <sys/resource.h>
40 /* Some systems don't define RUSAGE_SELF. This should fix them. */
45 #include <pwd.h> // setuid
46 #include <grp.h> // setgid
48 WORD g_wOriginalColors;
49 WORD g_wBackgroundColor;
57 #include "socketengine.h"
59 #include "command_parse.h"
60 #include "exitcodes.h"
62 #include "testsuite.h"
64 InspIRCd* ServerInstance = NULL;
66 /** Seperate from the other casemap tables so that code *can* still exclusively rely on RFC casemapping
69 * This is provided as a pointer so that modules can change it to their custom mapping tables,
70 * e.g. for national character support.
72 unsigned const char *national_case_insensitive_map = rfc_case_insensitive_map;
75 /* Moved from exitcodes.h -- due to duplicate symbols -- Burlex
76 * XXX this is a bit ugly. -- w00t
78 const char* ExitCodes[] =
81 "DIE command", /* 1 */
82 "execv() failed", /* 2 */
83 "Internal error", /* 3 */
84 "Config file error", /* 4 */
85 "Logfile error", /* 5 */
86 "POSIX fork failed", /* 6 */
87 "Bad commandline parameters", /* 7 */
88 "No ports could be bound", /* 8 */
89 "Can't write PID file", /* 9 */
90 "SocketEngine could not initialize", /* 10 */
91 "Refusing to start up as root", /* 11 */
92 "Found a <die> tag!", /* 12 */
93 "Couldn't load module on startup", /* 13 */
94 "Could not create windows forked process", /* 14 */
95 "Received SIGTERM", /* 15 */
96 "Bad command handler loaded", /* 16 */
97 "RegisterServiceCtrlHandler failed", /* 17 */
98 "UpdateSCMStatus failed", /* 18 */
99 "CreateEvent failed" /* 19 */
102 template<typename T> static void DeleteZero(T*&n)
109 void InspIRCd::Cleanup()
111 for (unsigned int i = 0; i < ports.size(); i++)
113 /* This calls the constructor and closes the listening socket */
119 /* Close all client sockets, or the new process inherits them */
120 LocalUserList::reverse_iterator i = Users->local_users.rbegin();
121 while (i != this->Users->local_users.rend())
124 Users->QuitUser(u, "Server shutdown");
128 Modules->UnloadAll();
130 /* Delete objects dynamically allocated in constructor (destructor would be more appropriate, but we're likely exiting) */
131 /* Must be deleted before modes as it decrements modelines */
134 DeleteZero(this->FakeClient);
135 DeleteZero(this->Users);
136 DeleteZero(this->Modes);
137 DeleteZero(this->XLines);
138 DeleteZero(this->Parser);
139 DeleteZero(this->stats);
140 DeleteZero(this->Modules);
141 DeleteZero(this->BanCache);
142 DeleteZero(this->SNO);
143 DeleteZero(this->Config);
144 DeleteZero(this->chanlist);
145 DeleteZero(this->PI);
146 DeleteZero(this->Threads);
147 DeleteZero(this->Timers);
148 DeleteZero(this->SE);
150 this->Logs->CloseLogs();
151 DeleteZero(this->Logs);
154 void InspIRCd::Restart(const std::string &reason)
156 /* SendError flushes each client's queue,
157 * regardless of writeability state
159 this->SendError(reason);
161 /* Figure out our filename (if theyve renamed it, we're boned) */
164 char** argv = Config->cmdline.argv;
167 char module[MAX_PATH];
168 if (GetModuleFileNameA(NULL, module, MAX_PATH))
176 if (execv(me.c_str(), argv) == -1)
178 /* Will raise a SIGABRT if not trapped */
179 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
183 void InspIRCd::SetSignals()
186 signal(SIGALRM, SIG_IGN);
187 signal(SIGHUP, InspIRCd::SetSignal);
188 signal(SIGPIPE, SIG_IGN);
189 signal(SIGCHLD, SIG_IGN);
190 /* We want E2BIG not a signal! */
191 signal(SIGXFSZ, SIG_IGN);
193 signal(SIGTERM, InspIRCd::SetSignal);
196 void InspIRCd::QuickExit(int status)
201 bool InspIRCd::DaemonSeed()
204 std::cout << "InspIRCd Process ID: " << con_green << GetCurrentProcessId() << con_reset << std::endl;
207 signal(SIGTERM, InspIRCd::QuickExit);
210 if ((childpid = fork ()) < 0)
212 else if (childpid > 0)
214 /* We wait here for the child process to kill us,
215 * so that the shell prompt doesnt come back over
217 * Sending a kill with a signal of 0 just checks
218 * if the child pid is still around. If theyre not,
219 * they threw an error and we should give up.
221 while (kill(childpid, 0) != -1)
226 std::cout << "InspIRCd Process ID: " << con_green << getpid() << con_reset << std::endl;
228 signal(SIGTERM, InspIRCd::SetSignal);
231 if (getrlimit(RLIMIT_CORE, &rl) == -1)
233 this->Logs->Log("STARTUP",LOG_DEFAULT,"Failed to getrlimit()!");
236 rl.rlim_cur = rl.rlim_max;
238 if (setrlimit(RLIMIT_CORE, &rl) == -1)
239 this->Logs->Log("STARTUP",LOG_DEFAULT,"setrlimit() failed, cannot increase coredump size.");
245 void InspIRCd::WritePID(const std::string &filename)
248 std::string fname(filename);
250 fname = DATA_PATH "/inspircd.pid";
251 std::ofstream outfile(fname.c_str());
252 if (outfile.is_open())
259 std::cout << "Failed to write PID-file '" << fname << "', exiting." << std::endl;
260 this->Logs->Log("STARTUP",LOG_DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
261 Exit(EXIT_STATUS_PID);
266 InspIRCd::InspIRCd(int argc, char** argv) :
267 ConfigFileName(CONFIG_PATH "/inspircd.conf"),
269 /* Functor pointer initialisation.
271 * THIS MUST MATCH THE ORDER OF DECLARATION OF THE FUNCTORS, e.g. the methods
272 * themselves within the class.
274 NICKForced("NICKForced", NULL),
275 OperQuit("OperQuit", NULL),
276 GenRandom(&HandleGenRandom),
277 IsChannel(&HandleIsChannel),
278 Rehash(&HandleRehash),
279 IsNick(&HandleIsNick),
280 IsIdent(&HandleIsIdent),
281 OnCheckExemption(&HandleOnCheckExemption)
283 ServerInstance = this;
285 Extensions.Register(&NICKForced);
286 Extensions.Register(&OperQuit);
289 int do_version = 0, do_nofork = 0, do_debug = 0,
290 do_nolog = 0, do_root = 0, do_testsuite = 0; /* flag variables */
293 // Initialize so that if we exit before proper initialization they're not deleted
308 this->ConfigThread = NULL;
309 this->FakeClient = NULL;
312 this->startup_time = TIME.tv_sec;
314 // This must be created first, so other parts of Insp can use it while starting up
315 this->Logs = new LogManager;
317 SE = CreateSocketEngine();
319 this->Threads = new ThreadEngine;
321 /* Default implementation does nothing */
322 this->PI = new ProtocolInterface;
324 // Create base manager classes early, so nothing breaks
325 this->Users = new UserManager;
327 this->Users->unregistered_count = 0;
329 this->Users->clientlist = new user_hash();
330 this->Users->uuidlist = new user_hash();
331 this->chanlist = new chan_hash();
333 this->Config = new ServerConfig;
334 this->SNO = new SnomaskManager;
335 this->BanCache = new BanCacheManager;
336 this->Modules = new ModuleManager();
337 dynamic_reference_base::reset_all();
338 this->stats = new serverstats();
339 this->Timers = new TimerManager;
340 this->Parser = new CommandParser;
341 this->XLines = new XLineManager;
343 this->Config->cmdline.argv = argv;
344 this->Config->cmdline.argc = argc;
347 srand(TIME.tv_nsec ^ TIME.tv_sec);
349 // Initialize the console values
350 g_hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
351 CONSOLE_SCREEN_BUFFER_INFO bufinf;
352 if(GetConsoleScreenBufferInfo(g_hStdout, &bufinf))
354 g_wOriginalColors = bufinf.wAttributes & 0x00FF;
355 g_wBackgroundColor = bufinf.wAttributes & 0x00F0;
359 g_wOriginalColors = FOREGROUND_RED|FOREGROUND_BLUE|FOREGROUND_GREEN;
360 g_wBackgroundColor = 0;
363 srandom(TIME.tv_nsec ^ TIME.tv_sec);
366 struct option longopts[] =
368 { "nofork", no_argument, &do_nofork, 1 },
369 { "logfile", required_argument, NULL, 'f' },
370 { "config", required_argument, NULL, 'c' },
371 { "debug", no_argument, &do_debug, 1 },
372 { "nolog", no_argument, &do_nolog, 1 },
373 { "runasroot", no_argument, &do_root, 1 },
374 { "version", no_argument, &do_version, 1 },
375 { "testsuite", no_argument, &do_testsuite, 1 },
380 while ((c = getopt_long(argc, argv, ":c:f:", longopts, &index)) != -1)
385 /* Log filename was set */
386 Config->cmdline.startup_log = optarg;
389 /* Config filename was set */
390 ConfigFileName = optarg;
393 /* getopt_long_only() set an int variable, just keep going */
396 /* Unknown parameter */
398 /* Fall through to handle other weird values too */
399 std::cout << "Unknown parameter '" << argv[optind-1] << "'" << std::endl;
400 std::cout << "Usage: " << argv[0] << " [--nofork] [--nolog] [--debug] [--logfile <filename>] " << std::endl <<
401 std::string(static_cast<int>(8+strlen(argv[0])), ' ') << "[--runasroot] [--version] [--config <config>] [--testsuite]" << std::endl;
402 Exit(EXIT_STATUS_ARGV);
408 do_nofork = do_debug = true;
412 std::cout << std::endl << VERSION << " r" << REVISION << std::endl;
413 Exit(EXIT_STATUS_NOERROR);
419 WSAStartup(MAKEWORD(2,2), &wsadata);
422 /* Set the finished argument values */
423 Config->cmdline.nofork = (do_nofork != 0);
424 Config->cmdline.forcedebug = (do_debug != 0);
425 Config->cmdline.writelog = (!do_nolog != 0);
426 Config->cmdline.TestSuite = (do_testsuite != 0);
430 FileWriter* fw = new FileWriter(stdout);
431 FileLogStream* fls = new FileLogStream(LOG_RAWIO, fw);
432 Logs->AddLogTypes("*", fls, true);
434 else if (!this->OpenLog(argv, argc))
436 std::cout << "ERROR: Could not open initial logfile " << Config->cmdline.startup_log << ": " << strerror(errno) << std::endl << std::endl;
437 Exit(EXIT_STATUS_LOG);
440 if (!ServerConfig::FileExists(ConfigFileName.c_str()))
443 /* Windows can (and defaults to) hide file extensions, so let's play a bit nice for windows users. */
444 std::string txtconf = this->ConfigFileName;
445 txtconf.append(".txt");
447 if (ServerConfig::FileExists(txtconf.c_str()))
449 ConfigFileName = txtconf;
454 std::cout << "ERROR: Cannot open config file: " << ConfigFileName << std::endl << "Exiting..." << std::endl;
455 this->Logs->Log("STARTUP",LOG_DEFAULT,"Unable to open config file %s", ConfigFileName.c_str());
456 Exit(EXIT_STATUS_CONFIG);
460 std::cout << con_green << "Inspire Internet Relay Chat Server" << con_reset << ", compiled on " __DATE__ " at " __TIME__ << std::endl;
461 std::cout << con_green << "(C) InspIRCd Development Team." << con_reset << std::endl << std::endl;
462 std::cout << "Developers:" << std::endl;
463 std::cout << con_green << "\tBrain, FrostyCoolSlug, w00t, Om, Special, peavey" << std::endl;
464 std::cout << "\taquanight, psychon, dz, danieldg, jackmcbarn" << con_reset << std::endl << std::endl;
465 std::cout << "Others:\t\t\t" << con_green << "See /INFO Output" << con_reset << std::endl;
467 this->Modes = new ModeParser;
474 std::cout << "* WARNING * WARNING * WARNING * WARNING * WARNING *" << std::endl
475 << "YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED" << std::endl
476 << "AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED" << std::endl
477 << "OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR" << std::endl
478 << "SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN" << std::endl
479 << "TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART" << std::endl
480 << "THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!" << std::endl << std::endl
481 << "InspIRCd starting in 20 seconds, ctrl+c to abort..." << std::endl;
488 if (!Config->cmdline.nofork)
490 if (!this->DaemonSeed())
492 std::cout << "ERROR: could not go into daemon mode. Shutting down." << std::endl;
493 Logs->Log("STARTUP", LOG_DEFAULT, "ERROR: could not go into daemon mode. Shutting down.");
494 Exit(EXIT_STATUS_FORK);
498 SE->RecoverFromFork();
500 /* During startup we don't actually initialize this
501 * in the thread engine.
503 this->Config->Read();
504 this->Config->Apply(NULL, "");
505 Logs->OpenFileLogs();
506 ModeParser::InitBuiltinModes();
508 // If we don't have a SID, generate one based on the server name and the server description
509 if (Config->sid.empty())
510 Config->sid = UIDGenerator::GenerateSID(Config->ServerName, Config->ServerDesc);
512 // Initialize the UID generator with our sid
513 this->UIDGen.init(Config->sid);
515 /* set up fake client again this time with the correct uid */
516 this->FakeClient = new FakeUser(Config->sid, Config->ServerName);
518 // Get XLine to do it's thing.
519 this->XLines->CheckELines();
520 this->XLines->ApplyLines();
522 int bounditems = BindPorts(pl);
524 std::cout << std::endl;
526 this->Modules->LoadAll();
528 /* Just in case no modules were loaded - fix for bug #101 */
529 this->ISupport.Build();
530 Config->ApplyDisabledCommands(Config->DisabledCommands);
534 std::cout << std::endl << "WARNING: Not all your client ports could be bound -- " << std::endl << "starting anyway with " << bounditems
535 << " of " << bounditems + (int)pl.size() << " client ports bound." << std::endl << std::endl;
536 std::cout << "The following port(s) failed to bind:" << std::endl << std::endl;
538 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
540 std::cout << j << ".\tAddress: " << (i->first.empty() ? "<all>" : i->first) << " \tReason: " << i->second << std::endl;
543 std::cout << std::endl << "Hint: Try using a public IP instead of blank or *" << std::endl;
546 std::cout << "InspIRCd is now running as '" << Config->ServerName << "'[" << Config->GetSID() << "] with " << SE->GetMaxFds() << " max open sockets" << std::endl;
549 if (!Config->cmdline.nofork)
551 if (kill(getppid(), SIGTERM) == -1)
553 std::cout << "Error killing parent process: " << strerror(errno) << std::endl;
554 Logs->Log("STARTUP", LOG_DEFAULT, "Error killing parent process: %s",strerror(errno));
558 /* Explicitly shut down stdio's stdin/stdout/stderr.
560 * The previous logic here was to only do this if stdio was connected to a controlling
561 * terminal. However, we must do this always to avoid information leaks and other
562 * problems related to stdio.
564 * The only exception is if we are in debug mode.
568 if ((!do_nofork) && (!do_testsuite) && (!Config->cmdline.forcedebug))
570 int fd = open("/dev/null", O_RDWR);
576 if (dup2(fd, STDIN_FILENO) < 0)
577 Logs->Log("STARTUP", LOG_DEFAULT, "Failed to dup /dev/null to stdin.");
578 if (dup2(fd, STDOUT_FILENO) < 0)
579 Logs->Log("STARTUP", LOG_DEFAULT, "Failed to dup /dev/null to stdout.");
580 if (dup2(fd, STDERR_FILENO) < 0)
581 Logs->Log("STARTUP", LOG_DEFAULT, "Failed to dup /dev/null to stderr.");
586 Logs->Log("STARTUP", LOG_DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
589 /* Set win32 service as running, if we are running as a service */
598 QueryPerformanceFrequency(&stats->QPFrequency);
601 Logs->Log("STARTUP", LOG_DEFAULT, "Startup complete as '%s'[%s], %d max open sockets", Config->ServerName.c_str(),Config->GetSID().c_str(), SE->GetMaxFds());
604 std::string SetUser = Config->ConfValue("security")->getString("runasuser");
605 std::string SetGroup = Config->ConfValue("security")->getString("runasgroup");
606 if (!SetGroup.empty())
611 ret = setgroups(0, NULL);
615 this->Logs->Log("SETGROUPS", LOG_DEFAULT, "setgroups() failed (wtf?): %s", strerror(errno));
623 g = getgrnam(SetGroup.c_str());
627 this->Logs->Log("SETGUID", LOG_DEFAULT, "getgrnam() failed (bad user?): %s", strerror(errno));
631 ret = setgid(g->gr_gid);
635 this->Logs->Log("SETGUID", LOG_DEFAULT, "setgid() failed (bad user?): %s", strerror(errno));
640 if (!SetUser.empty())
646 u = getpwnam(SetUser.c_str());
650 this->Logs->Log("SETGUID", LOG_DEFAULT, "getpwnam() failed (bad user?): %s", strerror(errno));
654 int ret = setuid(u->pw_uid);
658 this->Logs->Log("SETGUID", LOG_DEFAULT, "setuid() failed (bad user?): %s", strerror(errno));
663 this->WritePID(Config->PID);
667 void InspIRCd::UpdateTime()
673 TIME.tv_sec = time(NULL);
674 TIME.tv_nsec = st.wMilliseconds;
676 #ifdef HAS_CLOCK_GETTIME
677 clock_gettime(CLOCK_REALTIME, &TIME);
680 gettimeofday(&tv, NULL);
681 TIME.tv_sec = tv.tv_sec;
682 TIME.tv_nsec = tv.tv_usec * 1000;
689 /* See if we're supposed to be running the test suite rather than entering the mainloop */
690 if (Config->cmdline.TestSuite)
692 TestSuite* ts = new TestSuite;
698 time_t OLDTIME = TIME.tv_sec;
706 /* Check if there is a config thread which has finished executing but has not yet been freed */
707 if (this->ConfigThread && this->ConfigThread->IsDone())
709 /* Rehash has completed */
710 this->Logs->Log("CONFIG",LOG_DEBUG,"Detected ConfigThread exiting, tidying up...");
712 this->ConfigThread->Finish();
714 ConfigThread->join();
721 /* Run background module timers every few seconds
722 * (the docs say modules shouldnt rely on accurate
723 * timing using this event, so we dont have to
724 * time this exactly).
726 if (TIME.tv_sec != OLDTIME)
729 getrusage(RUSAGE_SELF, &ru);
730 stats->LastSampled = TIME;
731 stats->LastCPU = ru.ru_utime;
733 if(QueryPerformanceCounter(&stats->LastSampled))
735 FILETIME CreationTime;
739 GetProcessTimes(GetCurrentProcess(), &CreationTime, &ExitTime, &KernelTime, &UserTime);
740 stats->LastCPU.dwHighDateTime = KernelTime.dwHighDateTime + UserTime.dwHighDateTime;
741 stats->LastCPU.dwLowDateTime = KernelTime.dwLowDateTime + UserTime.dwLowDateTime;
745 /* Allow a buffer of two seconds drift on this so that ntpdate etc dont harass admins */
746 if (TIME.tv_sec < OLDTIME - 2)
748 SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %lu secs.", (unsigned long)OLDTIME-TIME.tv_sec);
750 else if (TIME.tv_sec > OLDTIME + 2)
752 SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is jumping FORWARDS! Clock skipped %lu secs.", (unsigned long)TIME.tv_sec - OLDTIME);
755 OLDTIME = TIME.tv_sec;
757 if ((TIME.tv_sec % 3600) == 0)
759 Users->GarbageCollect();
760 FOREACH_MOD(I_OnGarbageCollect, OnGarbageCollect());
763 Timers->TickTimers(TIME.tv_sec);
764 this->DoBackgroundUserStuff();
766 if ((TIME.tv_sec % 5) == 0)
768 FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME.tv_sec));
769 SNO->FlushSnotices();
773 /* Call the socket engine to wait on the active
774 * file descriptors. The socket engine has everything's
775 * descriptors in its list... dns, modules, users,
776 * servers... so its nice and easy, just one call.
777 * This will cause any read or write events to be
778 * dispatched to their handlers.
780 this->SE->DispatchTrialWrites();
781 this->SE->DispatchEvents();
783 /* if any users were quit, take them out */
789 this->SignalHandler(s_signal);
797 /**********************************************************************************/
799 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
800 * (until this returns true, a user will block in the waiting state, waiting to connect up to the
801 * registration timeout maximum seconds)
803 bool InspIRCd::AllModulesReportReady(LocalUser* user)
806 FIRST_MOD_RESULT(OnCheckReady, res, (user));
807 return (res == MOD_RES_PASSTHRU);
810 sig_atomic_t InspIRCd::s_signal = 0;
812 void InspIRCd::SetSignal(int signal)
817 /* On posix systems, the flow of the program starts right here, with
818 * ENTRYPOINT being a #define that defines main(). On Windows, ENTRYPOINT
819 * defines smain() and the real main() is in the service code under
820 * win32service.cpp. This allows the service control manager to control
821 * the process where we are running as a windows service.
825 new InspIRCd(argc, argv);
826 ServerInstance->Run();
827 delete ServerInstance;