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/>.
31 #include "inspircd_version.h"
37 #include <sys/resource.h>
41 /* Some systems don't define RUSAGE_SELF. This should fix them. */
46 #include <pwd.h> // setuid
47 #include <grp.h> // setgid
53 #include "socketengine.h"
55 #include "command_parse.h"
56 #include "exitcodes.h"
58 #include "testsuite.h"
60 InspIRCd* ServerInstance = NULL;
63 /** Seperate from the other casemap tables so that code *can* still exclusively rely on RFC casemapping
66 * This is provided as a pointer so that modules can change it to their custom mapping tables,
67 * e.g. for national character support.
69 unsigned const char *national_case_insensitive_map = rfc_case_insensitive_map;
72 /* Moved from exitcodes.h -- due to duplicate symbols -- Burlex
73 * XXX this is a bit ugly. -- w00t
75 const char* ExitCodes[] =
78 "DIE command", /* 1 */
79 "execv() failed", /* 2 */
80 "Internal error", /* 3 */
81 "Config file error", /* 4 */
82 "Logfile error", /* 5 */
83 "POSIX fork failed", /* 6 */
84 "Bad commandline parameters", /* 7 */
85 "No ports could be bound", /* 8 */
86 "Can't write PID file", /* 9 */
87 "SocketEngine could not initialize", /* 10 */
88 "Refusing to start up as root", /* 11 */
89 "Found a <die> tag!", /* 12 */
90 "Couldn't load module on startup", /* 13 */
91 "Could not create windows forked process", /* 14 */
92 "Received SIGTERM", /* 15 */
93 "Bad command handler loaded", /* 16 */
94 "RegisterServiceCtrlHandler failed", /* 17 */
95 "UpdateSCMStatus failed", /* 18 */
96 "CreateEvent failed" /* 19 */
99 template<typename T> static void DeleteZero(T*&n)
106 void InspIRCd::Cleanup()
108 for (unsigned int i = 0; i < ports.size(); i++)
110 /* This calls the constructor and closes the listening socket */
116 /* Close all client sockets, or the new process inherits them */
117 std::vector<LocalUser*>::reverse_iterator i = Users->local_users.rbegin();
118 while (i != this->Users->local_users.rend())
121 Users->QuitUser(u, "Server shutdown");
125 Modules->UnloadAll();
127 /* Delete objects dynamically allocated in constructor (destructor would be more appropriate, but we're likely exiting) */
128 /* Must be deleted before modes as it decrements modelines */
133 DeleteZero(this->FakeClient);
134 DeleteZero(this->Users);
135 DeleteZero(this->Modes);
136 DeleteZero(this->XLines);
137 DeleteZero(this->Parser);
138 DeleteZero(this->stats);
139 DeleteZero(this->Modules);
140 DeleteZero(this->BanCache);
141 DeleteZero(this->SNO);
142 DeleteZero(this->Config);
143 DeleteZero(this->Res);
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 (GetModuleFileName(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::ResetMaxBans()
185 for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
186 i->second->ResetMaxBans();
189 /** Because hash_map doesn't free its buckets when we delete items, we occasionally
190 * recreate the hash to free them up.
191 * We do this by copying the entries from the old hash to a new hash, causing all
192 * empty buckets to be weeded out of the hash.
193 * Since this is quite expensive, it's not done very often.
195 void InspIRCd::RehashUsersAndChans()
197 user_hash* old_users = Users->clientlist;
198 user_hash* old_uuid = Users->uuidlist;
199 chan_hash* old_chans = chanlist;
201 Users->clientlist = new user_hash();
202 Users->uuidlist = new user_hash();
203 chanlist = new chan_hash();
205 for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
206 Users->clientlist->insert(*n);
208 for (user_hash::const_iterator n = old_uuid->begin(); n != old_uuid->end(); n++)
209 Users->uuidlist->insert(*n);
211 for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
212 chanlist->insert(*n);
218 // Reset the already_sent IDs so we don't wrap it around and drop a message
219 LocalUser::already_sent_id = 0;
220 for (std::vector<LocalUser*>::const_iterator i = Users->local_users.begin(); i != Users->local_users.end(); i++)
222 (**i).already_sent = 0;
226 void InspIRCd::SetSignals()
229 signal(SIGALRM, SIG_IGN);
230 signal(SIGHUP, InspIRCd::SetSignal);
231 signal(SIGPIPE, SIG_IGN);
232 signal(SIGCHLD, SIG_IGN);
233 /* We want E2BIG not a signal! */
234 signal(SIGXFSZ, SIG_IGN);
236 signal(SIGTERM, InspIRCd::SetSignal);
239 void InspIRCd::QuickExit(int status)
244 bool InspIRCd::DaemonSeed()
247 printf_c("InspIRCd Process ID: \033[1;32m%lu\033[0m\n", GetCurrentProcessId());
250 signal(SIGTERM, InspIRCd::QuickExit);
253 if ((childpid = fork ()) < 0)
255 else if (childpid > 0)
257 /* We wait here for the child process to kill us,
258 * so that the shell prompt doesnt come back over
260 * Sending a kill with a signal of 0 just checks
261 * if the child pid is still around. If theyre not,
262 * they threw an error and we should give up.
264 while (kill(childpid, 0) != -1)
269 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
271 signal(SIGTERM, InspIRCd::SetSignal);
274 if (getrlimit(RLIMIT_CORE, &rl) == -1)
276 this->Logs->Log("STARTUP",DEFAULT,"Failed to getrlimit()!");
279 rl.rlim_cur = rl.rlim_max;
281 if (setrlimit(RLIMIT_CORE, &rl) == -1)
282 this->Logs->Log("STARTUP",DEFAULT,"setrlimit() failed, cannot increase coredump size.");
288 void InspIRCd::WritePID(const std::string &filename)
290 std::string fname(filename);
292 fname = "data/inspircd.pid";
293 std::ofstream outfile(fname.c_str());
294 if (outfile.is_open())
301 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
302 this->Logs->Log("STARTUP",DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
303 Exit(EXIT_STATUS_PID);
307 InspIRCd::InspIRCd(int argc, char** argv) :
308 ConfigFileName("conf/inspircd.conf"),
310 /* Functor pointer initialisation.
312 * THIS MUST MATCH THE ORDER OF DECLARATION OF THE FUNCTORS, e.g. the methods
313 * themselves within the class.
315 NICKForced("NICKForced", NULL),
316 OperQuit("OperQuit", NULL),
317 GenRandom(&HandleGenRandom),
318 IsChannel(&HandleIsChannel),
320 Rehash(&HandleRehash),
321 IsNick(&HandleIsNick),
322 IsIdent(&HandleIsIdent),
323 FloodQuitUser(&HandleFloodQuitUser),
324 OnCheckExemption(&HandleOnCheckExemption)
327 // Strict, frequent checking of memory on debug builds
328 _CrtSetDbgFlag ( _CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
330 // Avoid erroneous frees on early exit
334 ServerInstance = this;
336 Extensions.Register(&NICKForced);
337 Extensions.Register(&OperQuit);
340 int do_version = 0, do_nofork = 0, do_debug = 0,
341 do_nolog = 0, do_root = 0, do_testsuite = 0; /* flag variables */
344 // Initialize so that if we exit before proper initialization they're not deleted
360 this->ConfigThread = NULL;
363 this->startup_time = TIME.tv_sec;
365 // This must be created first, so other parts of Insp can use it while starting up
366 this->Logs = new LogManager;
368 SE = CreateSocketEngine();
370 this->Threads = new ThreadEngine;
372 /* Default implementation does nothing */
373 this->PI = new ProtocolInterface;
377 // Create base manager classes early, so nothing breaks
378 this->Users = new UserManager;
380 this->Users->unregistered_count = 0;
382 this->Users->clientlist = new user_hash();
383 this->Users->uuidlist = new user_hash();
384 this->chanlist = new chan_hash();
386 this->Config = new ServerConfig;
387 this->SNO = new SnomaskManager;
388 this->BanCache = new BanCacheManager;
389 this->Modules = new ModuleManager();
390 this->stats = new serverstats();
391 this->Timers = new TimerManager;
392 this->Parser = new CommandParser;
393 this->XLines = new XLineManager;
395 this->Config->cmdline.argv = argv;
396 this->Config->cmdline.argc = argc;
398 srandom(TIME.tv_nsec ^ TIME.tv_sec);
400 struct option longopts[] =
402 { "nofork", no_argument, &do_nofork, 1 },
403 { "logfile", required_argument, NULL, 'f' },
404 { "config", required_argument, NULL, 'c' },
405 { "debug", no_argument, &do_debug, 1 },
406 { "nolog", no_argument, &do_nolog, 1 },
407 { "runasroot", no_argument, &do_root, 1 },
408 { "version", no_argument, &do_version, 1 },
409 { "testsuite", no_argument, &do_testsuite, 1 },
414 while ((c = getopt_long(argc, argv, ":f:", longopts, &index)) != -1)
419 /* Log filename was set */
420 Config->cmdline.startup_log = optarg;
423 /* Config filename was set */
424 ConfigFileName = optarg;
427 /* getopt_long_only() set an int variable, just keep going */
430 /* Unknown parameter */
432 /* Fall through to handle other weird values too */
433 printf("Unknown parameter '%s'\n", argv[optind-1]);
434 printf("Usage: %s [--nofork] [--nolog] [--debug] [--logfile <filename>]\n%*s[--runasroot] [--version] [--config <config>] [--testsuite]\n", argv[0], static_cast<int>(8+strlen(argv[0])), " ");
435 Exit(EXIT_STATUS_ARGV);
441 do_nofork = do_debug = true;
445 printf("\n%s r%s\n", VERSION, REVISION);
446 Exit(EXIT_STATUS_NOERROR);
454 DWORD ExitCode = WindowsForkStart();
461 WSAStartup(MAKEWORD(2,0), &wsadata);
462 ChangeWindowsSpecificPointers();
465 /* Set the finished argument values */
466 Config->cmdline.nofork = do_nofork;
467 Config->cmdline.forcedebug = do_debug;
468 Config->cmdline.writelog = !do_nolog;
469 Config->cmdline.TestSuite = do_testsuite;
473 FileWriter* fw = new FileWriter(stdout);
474 FileLogStream* fls = new FileLogStream(RAWIO, fw);
475 Logs->AddLogTypes("*", fls, true);
477 else if (!this->OpenLog(argv, argc))
479 printf("ERROR: Could not open initial logfile %s: %s\n\n", Config->cmdline.startup_log.c_str(), strerror(errno));
480 Exit(EXIT_STATUS_LOG);
483 if (!ServerConfig::FileExists(ConfigFileName.c_str()))
486 /* Windows can (and defaults to) hide file extensions, so let's play a bit nice for windows users. */
487 std::string txtconf = this->ConfigFileName;
488 txtconf.append(".txt");
490 if (ServerConfig::FileExists(txtconf.c_str()))
492 ConfigFileName = txtconf;
497 printf("ERROR: Cannot open config file: %s\nExiting...\n", ConfigFileName.c_str());
498 this->Logs->Log("STARTUP",DEFAULT,"Unable to open config file %s", ConfigFileName.c_str());
499 Exit(EXIT_STATUS_CONFIG);
503 printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
504 printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
505 printf_c("Developers:\n");
506 printf_c("\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special, peavey\n");
507 printf_c("\t\033[1;32maquanight, psychon, dz, danieldg, jackmcbarn\033[0m\n\n");
508 printf_c("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
510 this->Modes = new ModeParser;
516 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
517 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
518 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
519 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
520 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
521 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
522 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
523 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
529 if (!Config->cmdline.nofork)
531 if (!this->DaemonSeed())
533 printf("ERROR: could not go into daemon mode. Shutting down.\n");
534 Logs->Log("STARTUP", DEFAULT, "ERROR: could not go into daemon mode. Shutting down.");
535 Exit(EXIT_STATUS_FORK);
539 SE->RecoverFromFork();
541 /* During startup we don't actually initialize this
542 * in the thread engine.
544 this->Config->Read();
545 this->Config->Apply(NULL, "");
546 Logs->OpenFileLogs();
548 this->Res = new DNS();
551 * Initialise SID/UID.
552 * For an explanation as to exactly how this works, and why it works this way, see GetUID().
555 if (Config->sid.empty())
558 unsigned int sid = 0;
561 for (const char* x = Config->ServerName.c_str(); *x; ++x)
563 for (const char* y = Config->ServerDesc.c_str(); *y; ++y)
565 sprintf(sidstr, "%03d", sid % 1000);
567 Config->sid = sidstr;
570 /* set up fake client again this time with the correct uid */
571 this->FakeClient = new FakeUser(Config->sid, Config->ServerName);
573 // Get XLine to do it's thing.
574 this->XLines->CheckELines();
575 this->XLines->ApplyLines();
577 int bounditems = BindPorts(pl);
581 this->Modules->LoadAll();
583 /* Just in case no modules were loaded - fix for bug #101 */
584 this->BuildISupport();
585 Config->ApplyDisabledCommands(Config->DisabledCommands);
589 printf("\nWARNING: Not all your client ports could be bound --\nstarting anyway with %d of %d client ports bound.\n\n",
590 bounditems, bounditems + (int)pl.size());
591 printf("The following port(s) failed to bind:\n");
592 printf("Hint: Try using a public IP instead of blank or *\n\n");
594 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
596 printf("%d.\tAddress: %s\tReason: %s\n", j, i->first.empty() ? "<all>" : i->first.c_str(), i->second.c_str());
600 printf("\nInspIRCd is now running as '%s'[%s] with %d max open sockets\n",
601 Config->ServerName.c_str(),Config->GetSID().c_str(), SE->GetMaxFds());
604 if (!Config->cmdline.nofork)
606 if (kill(getppid(), SIGTERM) == -1)
608 printf("Error killing parent process: %s\n",strerror(errno));
609 Logs->Log("STARTUP", DEFAULT, "Error killing parent process: %s",strerror(errno));
613 /* Explicitly shut down stdio's stdin/stdout/stderr.
615 * The previous logic here was to only do this if stdio was connected to a controlling
616 * terminal. However, we must do this always to avoid information leaks and other
617 * problems related to stdio.
619 * The only exception is if we are in debug mode.
623 if ((!do_nofork) && (!do_testsuite) && (!Config->cmdline.forcedebug))
631 fd = open("/dev/null", O_RDWR);
633 Logs->Log("STARTUP", DEFAULT, "Failed to dup /dev/null to stdin.");
635 Logs->Log("STARTUP", DEFAULT, "Failed to dup /dev/null to stdout.");
637 Logs->Log("STARTUP", DEFAULT, "Failed to dup /dev/null to stderr.");
642 Logs->Log("STARTUP", DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
645 WindowsIPC = new IPC;
646 if(!Config->cmdline.nofork)
648 WindowsForkKillOwner();
651 /* Set win32 service as running, if we are running as a service */
655 Logs->Log("STARTUP", DEFAULT, "Startup complete as '%s'[%s], %d max open sockets", Config->ServerName.c_str(),Config->GetSID().c_str(), SE->GetMaxFds());
658 std::string SetUser = Config->ConfValue("security")->getString("runasuser");
659 std::string SetGroup = Config->ConfValue("security")->getString("runasgroup");
660 if (!SetGroup.empty())
665 ret = setgroups(0, NULL);
669 this->Logs->Log("SETGROUPS", DEFAULT, "setgroups() failed (wtf?): %s", strerror(errno));
677 g = getgrnam(SetGroup.c_str());
681 this->Logs->Log("SETGUID", DEFAULT, "getgrnam() failed (bad user?): %s", strerror(errno));
685 ret = setgid(g->gr_gid);
689 this->Logs->Log("SETGUID", DEFAULT, "setgid() failed (bad user?): %s", strerror(errno));
694 if (!SetUser.empty())
700 u = getpwnam(SetUser.c_str());
704 this->Logs->Log("SETGUID", DEFAULT, "getpwnam() failed (bad user?): %s", strerror(errno));
708 int ret = setuid(u->pw_uid);
712 this->Logs->Log("SETGUID", DEFAULT, "setuid() failed (bad user?): %s", strerror(errno));
718 this->WritePID(Config->PID);
721 void InspIRCd::UpdateTime()
723 #ifdef HAS_CLOCK_GETTIME
724 clock_gettime(CLOCK_REALTIME, &TIME);
727 gettimeofday(&tv, NULL);
728 TIME.tv_sec = tv.tv_sec;
729 TIME.tv_nsec = tv.tv_usec * 1000;
735 /* See if we're supposed to be running the test suite rather than entering the mainloop */
736 if (Config->cmdline.TestSuite)
738 TestSuite* ts = new TestSuite;
744 time_t OLDTIME = TIME.tv_sec;
751 static time_t uptime;
752 static struct tm * stime;
753 static char window_title[100];
756 /* Check if there is a config thread which has finished executing but has not yet been freed */
757 if (this->ConfigThread && this->ConfigThread->IsDone())
759 /* Rehash has completed */
760 this->Logs->Log("CONFIG",DEBUG,"Detected ConfigThread exiting, tidying up...");
762 this->ConfigThread->Finish();
764 ConfigThread->join();
771 /* Run background module timers every few seconds
772 * (the docs say modules shouldnt rely on accurate
773 * timing using this event, so we dont have to
774 * time this exactly).
776 if (TIME.tv_sec != OLDTIME)
778 OLDTIME = TIME.tv_sec;
780 getrusage(RUSAGE_SELF, &ru);
781 stats->LastSampled = TIME;
782 stats->LastCPU = ru.ru_utime;
787 /* Allow a buffer of two seconds drift on this so that ntpdate etc dont harass admins */
788 if (TIME.tv_sec < OLDTIME - 2)
790 SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %lu secs.", (unsigned long)OLDTIME-TIME.tv_sec);
792 else if (TIME.tv_sec > OLDTIME + 2)
794 SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is jumping FORWARDS! Clock skipped %lu secs.", (unsigned long)TIME.tv_sec - OLDTIME);
797 if ((TIME.tv_sec % 3600) == 0)
799 this->RehashUsersAndChans();
800 FOREACH_MOD(I_OnGarbageCollect, OnGarbageCollect());
803 Timers->TickTimers(TIME.tv_sec);
804 this->DoBackgroundUserStuff();
806 if ((TIME.tv_sec % 5) == 0)
808 FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME.tv_sec));
809 SNO->FlushSnotices();
813 /* Call the socket engine to wait on the active
814 * file descriptors. The socket engine has everything's
815 * descriptors in its list... dns, modules, users,
816 * servers... so its nice and easy, just one call.
817 * This will cause any read or write events to be
818 * dispatched to their handlers.
820 this->SE->DispatchTrialWrites();
821 this->SE->DispatchEvents();
823 /* if any users were quit, take them out */
829 this->SignalHandler(s_signal);
837 /**********************************************************************************/
840 * An ircd in five lines! bwahahaha. ahahahahaha. ahahah *cough*.
843 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
844 * (until this returns true, a user will block in the waiting state, waiting to connect up to the
845 * registration timeout maximum seconds)
847 bool InspIRCd::AllModulesReportReady(LocalUser* user)
850 FIRST_MOD_RESULT(OnCheckReady, res, (user));
851 return (res == MOD_RES_PASSTHRU);
854 void InspIRCd::SetSignal(int signal)
859 /* On posix systems, the flow of the program starts right here, with
860 * ENTRYPOINT being a #define that defines main(). On Windows, ENTRYPOINT
861 * defines smain() and the real main() is in the service code under
862 * win32service.cpp. This allows the service control manager to control
863 * the process where we are running as a windows service.
867 new InspIRCd(argc, argv);
868 mysig = &ServerInstance->s_signal;
869 ServerInstance->Run();
870 delete ServerInstance;