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;
67 /** Seperate from the other casemap tables so that code *can* still exclusively rely on RFC casemapping
70 * This is provided as a pointer so that modules can change it to their custom mapping tables,
71 * e.g. for national character support.
73 unsigned const char *national_case_insensitive_map = rfc_case_insensitive_map;
76 /* Moved from exitcodes.h -- due to duplicate symbols -- Burlex
77 * XXX this is a bit ugly. -- w00t
79 const char* ExitCodes[] =
82 "DIE command", /* 1 */
83 "execv() failed", /* 2 */
84 "Internal error", /* 3 */
85 "Config file error", /* 4 */
86 "Logfile error", /* 5 */
87 "POSIX fork failed", /* 6 */
88 "Bad commandline parameters", /* 7 */
89 "No ports could be bound", /* 8 */
90 "Can't write PID file", /* 9 */
91 "SocketEngine could not initialize", /* 10 */
92 "Refusing to start up as root", /* 11 */
93 "Found a <die> tag!", /* 12 */
94 "Couldn't load module on startup", /* 13 */
95 "Could not create windows forked process", /* 14 */
96 "Received SIGTERM", /* 15 */
97 "Bad command handler loaded", /* 16 */
98 "RegisterServiceCtrlHandler failed", /* 17 */
99 "UpdateSCMStatus failed", /* 18 */
100 "CreateEvent failed" /* 19 */
103 template<typename T> static void DeleteZero(T*&n)
110 void InspIRCd::Cleanup()
112 for (unsigned int i = 0; i < ports.size(); i++)
114 /* This calls the constructor and closes the listening socket */
120 /* Close all client sockets, or the new process inherits them */
121 LocalUserList::reverse_iterator i = Users->local_users.rbegin();
122 while (i != this->Users->local_users.rend())
125 Users->QuitUser(u, "Server shutdown");
129 Modules->UnloadAll();
131 /* Delete objects dynamically allocated in constructor (destructor would be more appropriate, but we're likely exiting) */
132 /* Must be deleted before modes as it decrements modelines */
137 DeleteZero(this->FakeClient);
138 DeleteZero(this->Users);
139 DeleteZero(this->Modes);
140 DeleteZero(this->XLines);
141 DeleteZero(this->Parser);
142 DeleteZero(this->stats);
143 DeleteZero(this->Modules);
144 DeleteZero(this->BanCache);
145 DeleteZero(this->SNO);
146 DeleteZero(this->Config);
147 DeleteZero(this->Res);
148 DeleteZero(this->chanlist);
149 DeleteZero(this->PI);
150 DeleteZero(this->Threads);
151 DeleteZero(this->Timers);
152 DeleteZero(this->SE);
154 this->Logs->CloseLogs();
155 DeleteZero(this->Logs);
158 void InspIRCd::Restart(const std::string &reason)
160 /* SendError flushes each client's queue,
161 * regardless of writeability state
163 this->SendError(reason);
165 /* Figure out our filename (if theyve renamed it, we're boned) */
168 char** argv = Config->cmdline.argv;
171 char module[MAX_PATH];
172 if (GetModuleFileNameA(NULL, module, MAX_PATH))
180 if (execv(me.c_str(), argv) == -1)
182 /* Will raise a SIGABRT if not trapped */
183 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
187 void InspIRCd::ResetMaxBans()
189 for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
190 i->second->ResetMaxBans();
193 void InspIRCd::SetSignals()
196 signal(SIGALRM, SIG_IGN);
197 signal(SIGHUP, InspIRCd::SetSignal);
198 signal(SIGPIPE, SIG_IGN);
199 signal(SIGCHLD, SIG_IGN);
200 /* We want E2BIG not a signal! */
201 signal(SIGXFSZ, SIG_IGN);
203 signal(SIGTERM, InspIRCd::SetSignal);
206 void InspIRCd::QuickExit(int status)
211 bool InspIRCd::DaemonSeed()
214 std::cout << "InspIRCd Process ID: " << con_green << GetCurrentProcessId() << con_reset << std::endl;
217 signal(SIGTERM, InspIRCd::QuickExit);
220 if ((childpid = fork ()) < 0)
222 else if (childpid > 0)
224 /* We wait here for the child process to kill us,
225 * so that the shell prompt doesnt come back over
227 * Sending a kill with a signal of 0 just checks
228 * if the child pid is still around. If theyre not,
229 * they threw an error and we should give up.
231 while (kill(childpid, 0) != -1)
236 std::cout << "InspIRCd Process ID: " << con_green << getpid() << con_reset << std::endl;
238 signal(SIGTERM, InspIRCd::SetSignal);
241 if (getrlimit(RLIMIT_CORE, &rl) == -1)
243 this->Logs->Log("STARTUP",DEFAULT,"Failed to getrlimit()!");
246 rl.rlim_cur = rl.rlim_max;
248 if (setrlimit(RLIMIT_CORE, &rl) == -1)
249 this->Logs->Log("STARTUP",DEFAULT,"setrlimit() failed, cannot increase coredump size.");
255 void InspIRCd::WritePID(const std::string &filename)
258 std::string fname(filename);
260 fname = DATA_PATH "/inspircd.pid";
261 std::ofstream outfile(fname.c_str());
262 if (outfile.is_open())
269 std::cout << "Failed to write PID-file '" << fname << "', exiting." << std::endl;
270 this->Logs->Log("STARTUP",DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
271 Exit(EXIT_STATUS_PID);
276 InspIRCd::InspIRCd(int argc, char** argv) :
277 ConfigFileName(CONFIG_PATH "/inspircd.conf"),
279 /* Functor pointer initialisation.
281 * THIS MUST MATCH THE ORDER OF DECLARATION OF THE FUNCTORS, e.g. the methods
282 * themselves within the class.
284 NICKForced("NICKForced", NULL),
285 OperQuit("OperQuit", NULL),
286 GenRandom(&HandleGenRandom),
287 IsChannel(&HandleIsChannel),
288 Rehash(&HandleRehash),
289 IsNick(&HandleIsNick),
290 IsIdent(&HandleIsIdent),
291 OnCheckExemption(&HandleOnCheckExemption)
293 ServerInstance = this;
295 Extensions.Register(&NICKForced);
296 Extensions.Register(&OperQuit);
299 int do_version = 0, do_nofork = 0, do_debug = 0,
300 do_nolog = 0, do_root = 0, do_testsuite = 0; /* flag variables */
303 // Initialize so that if we exit before proper initialization they're not deleted
319 this->ConfigThread = NULL;
320 this->FakeClient = NULL;
323 this->startup_time = TIME.tv_sec;
325 // This must be created first, so other parts of Insp can use it while starting up
326 this->Logs = new LogManager;
328 SE = CreateSocketEngine();
330 this->Threads = new ThreadEngine;
332 /* Default implementation does nothing */
333 this->PI = new ProtocolInterface;
337 // Create base manager classes early, so nothing breaks
338 this->Users = new UserManager;
340 this->Users->unregistered_count = 0;
342 this->Users->clientlist = new user_hash();
343 this->Users->uuidlist = new user_hash();
344 this->chanlist = new chan_hash();
346 this->Config = new ServerConfig;
347 this->SNO = new SnomaskManager;
348 this->BanCache = new BanCacheManager;
349 this->Modules = new ModuleManager();
350 this->stats = new serverstats();
351 this->Timers = new TimerManager;
352 this->Parser = new CommandParser;
353 this->XLines = new XLineManager;
355 this->Config->cmdline.argv = argv;
356 this->Config->cmdline.argc = argc;
359 srand(TIME.tv_nsec ^ TIME.tv_sec);
361 // Initialize the console values
362 g_hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
363 CONSOLE_SCREEN_BUFFER_INFO bufinf;
364 if(GetConsoleScreenBufferInfo(g_hStdout, &bufinf))
366 g_wOriginalColors = bufinf.wAttributes & 0x00FF;
367 g_wBackgroundColor = bufinf.wAttributes & 0x00F0;
371 g_wOriginalColors = FOREGROUND_RED|FOREGROUND_BLUE|FOREGROUND_GREEN;
372 g_wBackgroundColor = 0;
375 srandom(TIME.tv_nsec ^ TIME.tv_sec);
378 struct option longopts[] =
380 { "nofork", no_argument, &do_nofork, 1 },
381 { "logfile", required_argument, NULL, 'f' },
382 { "config", required_argument, NULL, 'c' },
383 { "debug", no_argument, &do_debug, 1 },
384 { "nolog", no_argument, &do_nolog, 1 },
385 { "runasroot", no_argument, &do_root, 1 },
386 { "version", no_argument, &do_version, 1 },
387 { "testsuite", no_argument, &do_testsuite, 1 },
392 while ((c = getopt_long(argc, argv, ":c:f:", longopts, &index)) != -1)
397 /* Log filename was set */
398 Config->cmdline.startup_log = optarg;
401 /* Config filename was set */
402 ConfigFileName = optarg;
405 /* getopt_long_only() set an int variable, just keep going */
408 /* Unknown parameter */
410 /* Fall through to handle other weird values too */
411 std::cout << "Unknown parameter '" << argv[optind-1] << "'" << std::endl;
412 std::cout << "Usage: " << argv[0] << " [--nofork] [--nolog] [--debug] [--logfile <filename>] " << std::endl <<
413 std::string(static_cast<int>(8+strlen(argv[0])), ' ') << "[--runasroot] [--version] [--config <config>] [--testsuite]" << std::endl;
414 Exit(EXIT_STATUS_ARGV);
420 do_nofork = do_debug = true;
424 std::cout << std::endl << VERSION << " r" << REVISION << std::endl;
425 Exit(EXIT_STATUS_NOERROR);
431 WSAStartup(MAKEWORD(2,2), &wsadata);
434 /* Set the finished argument values */
435 Config->cmdline.nofork = (do_nofork != 0);
436 Config->cmdline.forcedebug = (do_debug != 0);
437 Config->cmdline.writelog = (!do_nolog != 0);
438 Config->cmdline.TestSuite = (do_testsuite != 0);
442 FileWriter* fw = new FileWriter(stdout);
443 FileLogStream* fls = new FileLogStream(RAWIO, fw);
444 Logs->AddLogTypes("*", fls, true);
446 else if (!this->OpenLog(argv, argc))
448 std::cout << "ERROR: Could not open initial logfile " << Config->cmdline.startup_log << ": " << strerror(errno) << std::endl << std::endl;
449 Exit(EXIT_STATUS_LOG);
452 if (!ServerConfig::FileExists(ConfigFileName.c_str()))
455 /* Windows can (and defaults to) hide file extensions, so let's play a bit nice for windows users. */
456 std::string txtconf = this->ConfigFileName;
457 txtconf.append(".txt");
459 if (ServerConfig::FileExists(txtconf.c_str()))
461 ConfigFileName = txtconf;
466 std::cout << "ERROR: Cannot open config file: " << ConfigFileName << std::endl << "Exiting..." << std::endl;
467 this->Logs->Log("STARTUP",DEFAULT,"Unable to open config file %s", ConfigFileName.c_str());
468 Exit(EXIT_STATUS_CONFIG);
472 std::cout << con_green << "Inspire Internet Relay Chat Server" << con_reset << ", compiled on " __DATE__ " at " __TIME__ << std::endl;
473 std::cout << con_green << "(C) InspIRCd Development Team." << con_reset << std::endl << std::endl;
474 std::cout << "Developers:" << std::endl;
475 std::cout << con_green << "\tBrain, FrostyCoolSlug, w00t, Om, Special, peavey" << std::endl;
476 std::cout << "\taquanight, psychon, dz, danieldg, jackmcbarn" << con_reset << std::endl << std::endl;
477 std::cout << "Others:\t\t\t" << con_green << "See /INFO Output" << con_reset << std::endl;
479 this->Modes = new ModeParser;
486 std::cout << "* WARNING * WARNING * WARNING * WARNING * WARNING *" << std::endl
487 << "YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED" << std::endl
488 << "AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED" << std::endl
489 << "OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR" << std::endl
490 << "SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN" << std::endl
491 << "TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART" << std::endl
492 << "THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!" << std::endl << std::endl
493 << "InspIRCd starting in 20 seconds, ctrl+c to abort..." << std::endl;
500 if (!Config->cmdline.nofork)
502 if (!this->DaemonSeed())
504 std::cout << "ERROR: could not go into daemon mode. Shutting down." << std::endl;
505 Logs->Log("STARTUP", DEFAULT, "ERROR: could not go into daemon mode. Shutting down.");
506 Exit(EXIT_STATUS_FORK);
510 SE->RecoverFromFork();
512 /* During startup we don't actually initialize this
513 * in the thread engine.
515 this->Config->Read();
516 this->Config->Apply(NULL, "");
517 Logs->OpenFileLogs();
519 this->Res = new DNS();
522 * Initialise SID/UID.
523 * For an explanation as to exactly how this works, and why it works this way, see GetUID().
526 if (Config->sid.empty())
529 unsigned int sid = 0;
532 for (const char* x = Config->ServerName.c_str(); *x; ++x)
534 for (const char* y = Config->ServerDesc.c_str(); *y; ++y)
536 sprintf(sidstr, "%03d", sid % 1000);
538 Config->sid = sidstr;
541 /* set up fake client again this time with the correct uid */
542 this->FakeClient = new FakeUser(Config->sid, Config->ServerName);
544 // Get XLine to do it's thing.
545 this->XLines->CheckELines();
546 this->XLines->ApplyLines();
548 int bounditems = BindPorts(pl);
550 std::cout << std::endl;
552 this->Modules->LoadAll();
554 /* Just in case no modules were loaded - fix for bug #101 */
555 this->BuildISupport();
556 Config->ApplyDisabledCommands(Config->DisabledCommands);
560 std::cout << std::endl << "WARNING: Not all your client ports could be bound -- " << std::endl << "starting anyway with " << bounditems
561 << " of " << bounditems + (int)pl.size() << " client ports bound." << std::endl << std::endl;
562 std::cout << "The following port(s) failed to bind:" << std::endl << std::endl;
564 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
566 std::cout << j << ".\tAddress: " << (i->first.empty() ? "<all>" : i->first) << " \tReason: " << i->second << std::endl;
569 std::cout << std::endl << "Hint: Try using a public IP instead of blank or *" << std::endl;
572 std::cout << "InspIRCd is now running as '" << Config->ServerName << "'[" << Config->GetSID() << "] with " << SE->GetMaxFds() << " max open sockets" << std::endl;
575 if (!Config->cmdline.nofork)
577 if (kill(getppid(), SIGTERM) == -1)
579 std::cout << "Error killing parent process: " << strerror(errno) << std::endl;
580 Logs->Log("STARTUP", DEFAULT, "Error killing parent process: %s",strerror(errno));
584 /* Explicitly shut down stdio's stdin/stdout/stderr.
586 * The previous logic here was to only do this if stdio was connected to a controlling
587 * terminal. However, we must do this always to avoid information leaks and other
588 * problems related to stdio.
590 * The only exception is if we are in debug mode.
594 if ((!do_nofork) && (!do_testsuite) && (!Config->cmdline.forcedebug))
596 int fd = open("/dev/null", O_RDWR);
602 if (dup2(fd, STDIN_FILENO) < 0)
603 Logs->Log("STARTUP", DEFAULT, "Failed to dup /dev/null to stdin.");
604 if (dup2(fd, STDOUT_FILENO) < 0)
605 Logs->Log("STARTUP", DEFAULT, "Failed to dup /dev/null to stdout.");
606 if (dup2(fd, STDERR_FILENO) < 0)
607 Logs->Log("STARTUP", DEFAULT, "Failed to dup /dev/null to stderr.");
612 Logs->Log("STARTUP", DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
615 /* Set win32 service as running, if we are running as a service */
624 QueryPerformanceFrequency(&stats->QPFrequency);
627 Logs->Log("STARTUP", DEFAULT, "Startup complete as '%s'[%s], %d max open sockets", Config->ServerName.c_str(),Config->GetSID().c_str(), SE->GetMaxFds());
630 std::string SetUser = Config->ConfValue("security")->getString("runasuser");
631 std::string SetGroup = Config->ConfValue("security")->getString("runasgroup");
632 if (!SetGroup.empty())
637 ret = setgroups(0, NULL);
641 this->Logs->Log("SETGROUPS", DEFAULT, "setgroups() failed (wtf?): %s", strerror(errno));
649 g = getgrnam(SetGroup.c_str());
653 this->Logs->Log("SETGUID", DEFAULT, "getgrnam() failed (bad user?): %s", strerror(errno));
657 ret = setgid(g->gr_gid);
661 this->Logs->Log("SETGUID", DEFAULT, "setgid() failed (bad user?): %s", strerror(errno));
666 if (!SetUser.empty())
672 u = getpwnam(SetUser.c_str());
676 this->Logs->Log("SETGUID", DEFAULT, "getpwnam() failed (bad user?): %s", strerror(errno));
680 int ret = setuid(u->pw_uid);
684 this->Logs->Log("SETGUID", DEFAULT, "setuid() failed (bad user?): %s", strerror(errno));
689 this->WritePID(Config->PID);
693 void InspIRCd::UpdateTime()
699 TIME.tv_sec = time(NULL);
700 TIME.tv_nsec = st.wMilliseconds;
702 #ifdef HAS_CLOCK_GETTIME
703 clock_gettime(CLOCK_REALTIME, &TIME);
706 gettimeofday(&tv, NULL);
707 TIME.tv_sec = tv.tv_sec;
708 TIME.tv_nsec = tv.tv_usec * 1000;
715 /* See if we're supposed to be running the test suite rather than entering the mainloop */
716 if (Config->cmdline.TestSuite)
718 TestSuite* ts = new TestSuite;
724 time_t OLDTIME = TIME.tv_sec;
732 /* Check if there is a config thread which has finished executing but has not yet been freed */
733 if (this->ConfigThread && this->ConfigThread->IsDone())
735 /* Rehash has completed */
736 this->Logs->Log("CONFIG",DEBUG,"Detected ConfigThread exiting, tidying up...");
738 this->ConfigThread->Finish();
740 ConfigThread->join();
747 /* Run background module timers every few seconds
748 * (the docs say modules shouldnt rely on accurate
749 * timing using this event, so we dont have to
750 * time this exactly).
752 if (TIME.tv_sec != OLDTIME)
755 getrusage(RUSAGE_SELF, &ru);
756 stats->LastSampled = TIME;
757 stats->LastCPU = ru.ru_utime;
759 if(QueryPerformanceCounter(&stats->LastSampled))
761 FILETIME CreationTime;
765 GetProcessTimes(GetCurrentProcess(), &CreationTime, &ExitTime, &KernelTime, &UserTime);
766 stats->LastCPU.dwHighDateTime = KernelTime.dwHighDateTime + UserTime.dwHighDateTime;
767 stats->LastCPU.dwLowDateTime = KernelTime.dwLowDateTime + UserTime.dwLowDateTime;
771 /* Allow a buffer of two seconds drift on this so that ntpdate etc dont harass admins */
772 if (TIME.tv_sec < OLDTIME - 2)
774 SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %lu secs.", (unsigned long)OLDTIME-TIME.tv_sec);
776 else if (TIME.tv_sec > OLDTIME + 2)
778 SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is jumping FORWARDS! Clock skipped %lu secs.", (unsigned long)TIME.tv_sec - OLDTIME);
781 OLDTIME = TIME.tv_sec;
783 if ((TIME.tv_sec % 3600) == 0)
785 Users->GarbageCollect();
786 FOREACH_MOD(I_OnGarbageCollect, OnGarbageCollect());
789 Timers->TickTimers(TIME.tv_sec);
790 this->DoBackgroundUserStuff();
792 if ((TIME.tv_sec % 5) == 0)
794 FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME.tv_sec));
795 SNO->FlushSnotices();
799 /* Call the socket engine to wait on the active
800 * file descriptors. The socket engine has everything's
801 * descriptors in its list... dns, modules, users,
802 * servers... so its nice and easy, just one call.
803 * This will cause any read or write events to be
804 * dispatched to their handlers.
806 this->SE->DispatchTrialWrites();
807 this->SE->DispatchEvents();
809 /* if any users were quit, take them out */
815 this->SignalHandler(s_signal);
823 /**********************************************************************************/
826 * An ircd in five lines! bwahahaha. ahahahahaha. ahahah *cough*.
829 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
830 * (until this returns true, a user will block in the waiting state, waiting to connect up to the
831 * registration timeout maximum seconds)
833 bool InspIRCd::AllModulesReportReady(LocalUser* user)
836 FIRST_MOD_RESULT(OnCheckReady, res, (user));
837 return (res == MOD_RES_PASSTHRU);
840 void InspIRCd::SetSignal(int signal)
845 /* On posix systems, the flow of the program starts right here, with
846 * ENTRYPOINT being a #define that defines main(). On Windows, ENTRYPOINT
847 * defines smain() and the real main() is in the service code under
848 * win32service.cpp. This allows the service control manager to control
849 * the process where we are running as a windows service.
853 new InspIRCd(argc, argv);
854 mysig = &ServerInstance->s_signal;
855 ServerInstance->Run();
856 delete ServerInstance;