1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2010 InspIRCd Development Team
6 * See: http://wiki.inspircd.org/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
16 #include "inspircd_version.h"
22 #include <sys/resource.h>
26 /* Some systems don't define RUSAGE_SELF. This should fix them. */
31 #include <pwd.h> // setuid
32 #include <grp.h> // setgid
38 #include "socketengine.h"
40 #include "command_parse.h"
41 #include "exitcodes.h"
43 #include "testsuite.h"
45 InspIRCd* ServerInstance = NULL;
48 /** Seperate from the other casemap tables so that code *can* still exclusively rely on RFC casemapping
51 * This is provided as a pointer so that modules can change it to their custom mapping tables,
52 * e.g. for national character support.
54 unsigned const char *national_case_insensitive_map = rfc_case_insensitive_map;
57 /* Moved from exitcodes.h -- due to duplicate symbols -- Burlex
58 * XXX this is a bit ugly. -- w00t
60 const char* ExitCodes[] =
63 "DIE command", /* 1 */
64 "execv() failed", /* 2 */
65 "Internal error", /* 3 */
66 "Config file error", /* 4 */
67 "Logfile error", /* 5 */
68 "POSIX fork failed", /* 6 */
69 "Bad commandline parameters", /* 7 */
70 "No ports could be bound", /* 8 */
71 "Can't write PID file", /* 9 */
72 "SocketEngine could not initialize", /* 10 */
73 "Refusing to start up as root", /* 11 */
74 "Found a <die> tag!", /* 12 */
75 "Couldn't load module on startup", /* 13 */
76 "Could not create windows forked process", /* 14 */
77 "Received SIGTERM", /* 15 */
78 "Bad command handler loaded", /* 16 */
79 "RegisterServiceCtrlHandler failed", /* 17 */
80 "UpdateSCMStatus failed", /* 18 */
81 "CreateEvent failed" /* 19 */
84 template<typename T> static void DeleteZero(T*&n)
91 void InspIRCd::Cleanup()
93 for (unsigned int i = 0; i < ports.size(); i++)
95 /* This calls the constructor and closes the listening socket */
101 /* Close all client sockets, or the new process inherits them */
102 std::vector<LocalUser*>::reverse_iterator i = Users->local_users.rbegin();
103 while (i != this->Users->local_users.rend())
106 Users->QuitUser(u, "Server shutdown");
110 Modules->UnloadAll();
112 /* Delete objects dynamically allocated in constructor (destructor would be more appropriate, but we're likely exiting) */
113 /* Must be deleted before modes as it decrements modelines */
118 DeleteZero(this->FakeClient);
119 DeleteZero(this->Users);
120 DeleteZero(this->Modes);
121 DeleteZero(this->XLines);
122 DeleteZero(this->Parser);
123 DeleteZero(this->stats);
124 DeleteZero(this->Modules);
125 DeleteZero(this->BanCache);
126 DeleteZero(this->SNO);
127 DeleteZero(this->Config);
128 DeleteZero(this->Res);
129 DeleteZero(this->chanlist);
130 DeleteZero(this->PI);
131 DeleteZero(this->Threads);
132 DeleteZero(this->Timers);
133 DeleteZero(this->SE);
135 this->Logs->CloseLogs();
136 DeleteZero(this->Logs);
139 void InspIRCd::Restart(const std::string &reason)
141 /* SendError flushes each client's queue,
142 * regardless of writeability state
144 this->SendError(reason);
146 /* Figure out our filename (if theyve renamed it, we're boned) */
149 char** argv = Config->cmdline.argv;
152 char module[MAX_PATH];
153 if (GetModuleFileName(NULL, module, MAX_PATH))
161 if (execv(me.c_str(), argv) == -1)
163 /* Will raise a SIGABRT if not trapped */
164 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
168 void InspIRCd::ResetMaxBans()
170 for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
171 i->second->ResetMaxBans();
174 /** Because hash_map doesn't free its buckets when we delete items, we occasionally
175 * recreate the hash to free them up.
176 * We do this by copying the entries from the old hash to a new hash, causing all
177 * empty buckets to be weeded out of the hash.
178 * Since this is quite expensive, it's not done very often.
180 void InspIRCd::RehashUsersAndChans()
182 user_hash* old_users = Users->clientlist;
183 user_hash* old_uuid = Users->uuidlist;
184 chan_hash* old_chans = chanlist;
186 Users->clientlist = new user_hash();
187 Users->uuidlist = new user_hash();
188 chanlist = new chan_hash();
190 for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
191 Users->clientlist->insert(*n);
193 for (user_hash::const_iterator n = old_uuid->begin(); n != old_uuid->end(); n++)
194 Users->uuidlist->insert(*n);
196 for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
197 chanlist->insert(*n);
203 // Reset the already_sent IDs so we don't wrap it around and drop a message
204 LocalUser::already_sent_id = 0;
205 for (std::vector<LocalUser*>::const_iterator i = Users->local_users.begin(); i != Users->local_users.end(); i++)
207 (**i).already_sent = 0;
211 void InspIRCd::SetSignals()
214 signal(SIGALRM, SIG_IGN);
215 signal(SIGHUP, InspIRCd::SetSignal);
216 signal(SIGPIPE, SIG_IGN);
217 signal(SIGCHLD, SIG_IGN);
218 /* We want E2BIG not a signal! */
219 signal(SIGXFSZ, SIG_IGN);
221 signal(SIGTERM, InspIRCd::SetSignal);
224 void InspIRCd::QuickExit(int status)
229 bool InspIRCd::DaemonSeed()
232 printf_c("InspIRCd Process ID: \033[1;32m%lu\033[0m\n", GetCurrentProcessId());
235 signal(SIGTERM, InspIRCd::QuickExit);
238 if ((childpid = fork ()) < 0)
240 else if (childpid > 0)
242 /* We wait here for the child process to kill us,
243 * so that the shell prompt doesnt come back over
245 * Sending a kill with a signal of 0 just checks
246 * if the child pid is still around. If theyre not,
247 * they threw an error and we should give up.
249 while (kill(childpid, 0) != -1)
254 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
256 signal(SIGTERM, InspIRCd::SetSignal);
259 if (getrlimit(RLIMIT_CORE, &rl) == -1)
261 this->Logs->Log("STARTUP",DEFAULT,"Failed to getrlimit()!");
264 rl.rlim_cur = rl.rlim_max;
266 if (setrlimit(RLIMIT_CORE, &rl) == -1)
267 this->Logs->Log("STARTUP",DEFAULT,"setrlimit() failed, cannot increase coredump size.");
273 void InspIRCd::WritePID(const std::string &filename)
275 std::string fname(filename);
277 fname = "data/inspircd.pid";
278 std::ofstream outfile(fname.c_str());
279 if (outfile.is_open())
286 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
287 this->Logs->Log("STARTUP",DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
288 Exit(EXIT_STATUS_PID);
292 InspIRCd::InspIRCd(int argc, char** argv) :
293 ConfigFileName("conf/inspircd.conf"),
295 /* Functor pointer initialisation.
297 * THIS MUST MATCH THE ORDER OF DECLARATION OF THE FUNCTORS, e.g. the methods
298 * themselves within the class.
300 NICKForced("NICKForced", NULL),
301 OperQuit("OperQuit", NULL),
302 GenRandom(&HandleGenRandom),
303 IsChannel(&HandleIsChannel),
305 Rehash(&HandleRehash),
306 IsNick(&HandleIsNick),
307 IsIdent(&HandleIsIdent),
308 FloodQuitUser(&HandleFloodQuitUser),
309 OnCheckExemption(&HandleOnCheckExemption)
312 // Strict, frequent checking of memory on debug builds
313 _CrtSetDbgFlag ( _CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
315 // Avoid erroneous frees on early exit
319 ServerInstance = this;
321 Extensions.Register(&NICKForced);
322 Extensions.Register(&OperQuit);
325 int do_version = 0, do_nofork = 0, do_debug = 0,
326 do_nolog = 0, do_root = 0, do_testsuite = 0; /* flag variables */
329 // Initialize so that if we exit before proper initialization they're not deleted
345 this->ConfigThread = NULL;
348 clock_gettime(CLOCK_REALTIME, &TIME);
349 this->startup_time = TIME.tv_sec;
351 // This must be created first, so other parts of Insp can use it while starting up
352 this->Logs = new LogManager;
354 SE = CreateSocketEngine();
356 this->Threads = new ThreadEngine;
358 /* Default implementation does nothing */
359 this->PI = new ProtocolInterface;
363 // Create base manager classes early, so nothing breaks
364 this->Users = new UserManager;
366 this->Users->unregistered_count = 0;
368 this->Users->clientlist = new user_hash();
369 this->Users->uuidlist = new user_hash();
370 this->chanlist = new chan_hash();
372 this->Config = new ServerConfig;
373 this->SNO = new SnomaskManager;
374 this->BanCache = new BanCacheManager;
375 this->Modules = new ModuleManager();
376 this->stats = new serverstats();
377 this->Timers = new TimerManager;
378 this->Parser = new CommandParser;
379 this->XLines = new XLineManager;
381 this->Config->cmdline.argv = argv;
382 this->Config->cmdline.argc = argc;
384 srandom(TIME.tv_nsec ^ TIME.tv_sec);
386 struct option longopts[] =
388 { "nofork", no_argument, &do_nofork, 1 },
389 { "logfile", required_argument, NULL, 'f' },
390 { "config", required_argument, NULL, 'c' },
391 { "debug", no_argument, &do_debug, 1 },
392 { "nolog", no_argument, &do_nolog, 1 },
393 { "runasroot", no_argument, &do_root, 1 },
394 { "version", no_argument, &do_version, 1 },
395 { "testsuite", no_argument, &do_testsuite, 1 },
400 while ((c = getopt_long(argc, argv, ":f:", longopts, &index)) != -1)
405 /* Log filename was set */
406 Config->cmdline.startup_log = optarg;
409 /* Config filename was set */
410 ConfigFileName = optarg;
413 /* getopt_long_only() set an int variable, just keep going */
416 /* Unknown parameter */
418 /* Fall through to handle other weird values too */
419 printf("Unknown parameter '%s'\n", argv[optind-1]);
420 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])), " ");
421 Exit(EXIT_STATUS_ARGV);
427 do_nofork = do_debug = true;
431 printf("\n%s r%s\n", VERSION, REVISION);
432 Exit(EXIT_STATUS_NOERROR);
440 DWORD ExitCode = WindowsForkStart();
447 WSAStartup(MAKEWORD(2,0), &wsadata);
448 ChangeWindowsSpecificPointers();
451 /* Set the finished argument values */
452 Config->cmdline.nofork = do_nofork;
453 Config->cmdline.forcedebug = do_debug;
454 Config->cmdline.writelog = !do_nolog;
455 Config->cmdline.TestSuite = do_testsuite;
459 FileWriter* fw = new FileWriter(stdout);
460 FileLogStream* fls = new FileLogStream(RAWIO, fw);
461 Logs->AddLogTypes("*", fls, true);
463 else if (!this->OpenLog(argv, argc))
465 printf("ERROR: Could not open initial logfile %s: %s\n\n", Config->cmdline.startup_log.c_str(), strerror(errno));
466 Exit(EXIT_STATUS_LOG);
469 if (!ServerConfig::FileExists(ConfigFileName.c_str()))
472 /* Windows can (and defaults to) hide file extensions, so let's play a bit nice for windows users. */
473 std::string txtconf = this->ConfigFileName;
474 txtconf.append(".txt");
476 if (ServerConfig::FileExists(txtconf.c_str()))
478 ConfigFileName = txtconf;
483 printf("ERROR: Cannot open config file: %s\nExiting...\n", ConfigFileName.c_str());
484 this->Logs->Log("STARTUP",DEFAULT,"Unable to open config file %s", ConfigFileName.c_str());
485 Exit(EXIT_STATUS_CONFIG);
489 printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
490 printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
491 printf_c("Developers:\n");
492 printf_c("\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special\n");
493 printf_c("\t\033[1;32mpeavey, aquanight, psychon, dz, danieldg\033[0m\n\n");
494 printf_c("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
496 this->Modes = new ModeParser;
502 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
503 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
504 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
505 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
506 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
507 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
508 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
509 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
515 if (!Config->cmdline.nofork)
517 if (!this->DaemonSeed())
519 printf("ERROR: could not go into daemon mode. Shutting down.\n");
520 Logs->Log("STARTUP", DEFAULT, "ERROR: could not go into daemon mode. Shutting down.");
521 Exit(EXIT_STATUS_FORK);
525 SE->RecoverFromFork();
527 /* During startup we don't actually initialize this
528 * in the thread engine.
530 this->Config->Read();
531 this->Config->Apply(NULL, "");
532 Logs->OpenFileLogs();
534 this->Res = new DNS();
537 * Initialise SID/UID.
538 * For an explanation as to exactly how this works, and why it works this way, see GetUID().
541 if (Config->sid.empty())
544 unsigned int sid = 0;
547 for (const char* x = Config->ServerName.c_str(); *x; ++x)
549 for (const char* y = Config->ServerDesc.c_str(); *y; ++y)
551 sprintf(sidstr, "%03d", sid % 1000);
553 Config->sid = sidstr;
556 /* set up fake client again this time with the correct uid */
557 this->FakeClient = new FakeUser(Config->sid, Config->ServerName);
559 // Get XLine to do it's thing.
560 this->XLines->CheckELines();
561 this->XLines->ApplyLines();
563 int bounditems = BindPorts(pl);
567 this->Modules->LoadAll();
569 /* Just in case no modules were loaded - fix for bug #101 */
570 this->BuildISupport();
571 Config->ApplyDisabledCommands(Config->DisabledCommands);
575 printf("\nWARNING: Not all your client ports could be bound --\nstarting anyway with %d of %d client ports bound.\n\n",
576 bounditems, bounditems + (int)pl.size());
577 printf("The following port(s) failed to bind:\n");
578 printf("Hint: Try using a public IP instead of blank or *\n\n");
580 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
582 printf("%d.\tAddress: %s\tReason: %s\n", j, i->first.empty() ? "<all>" : i->first.c_str(), i->second.c_str());
586 printf("\nInspIRCd is now running as '%s'[%s] with %d max open sockets\n",
587 Config->ServerName.c_str(),Config->GetSID().c_str(), SE->GetMaxFds());
590 if (!Config->cmdline.nofork)
592 if (kill(getppid(), SIGTERM) == -1)
594 printf("Error killing parent process: %s\n",strerror(errno));
595 Logs->Log("STARTUP", DEFAULT, "Error killing parent process: %s",strerror(errno));
599 if (isatty(0) && isatty(1) && isatty(2))
601 /* We didn't start from a TTY, we must have started from a background process -
602 * e.g. we are restarting, or being launched by cron. Dont kill parent, and dont
605 if ((!do_nofork) && (!do_testsuite))
609 if (!Config->cmdline.forcedebug)
614 Logs->Log("STARTUP", DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
618 WindowsIPC = new IPC;
621 WindowsForkKillOwner();
624 /* Set win32 service as running, if we are running as a service */
628 Logs->Log("STARTUP", DEFAULT, "Startup complete as '%s'[%s], %d max open sockets", Config->ServerName.c_str(),Config->GetSID().c_str(), SE->GetMaxFds());
631 std::string SetUser = Config->ConfValue("security")->getString("runasuser");
632 std::string SetGroup = Config->ConfValue("security")->getString("runasgroup");
633 if (!SetGroup.empty())
638 ret = setgroups(0, NULL);
642 this->Logs->Log("SETGROUPS", DEFAULT, "setgroups() failed (wtf?): %s", strerror(errno));
650 g = getgrnam(SetGroup.c_str());
654 this->Logs->Log("SETGUID", DEFAULT, "getgrnam() failed (bad user?): %s", strerror(errno));
658 ret = setgid(g->gr_gid);
662 this->Logs->Log("SETGUID", DEFAULT, "setgid() failed (bad user?): %s", strerror(errno));
667 if (!SetUser.empty())
673 u = getpwnam(SetUser.c_str());
677 this->Logs->Log("SETGUID", DEFAULT, "getpwnam() failed (bad user?): %s", strerror(errno));
681 int ret = setuid(u->pw_uid);
685 this->Logs->Log("SETGUID", DEFAULT, "setuid() failed (bad user?): %s", strerror(errno));
691 this->WritePID(Config->PID);
694 void InspIRCd::UpdateTime()
696 clock_gettime(CLOCK_REALTIME, &TIME);
701 /* See if we're supposed to be running the test suite rather than entering the mainloop */
702 if (Config->cmdline.TestSuite)
704 TestSuite* ts = new TestSuite;
710 time_t OLDTIME = TIME.tv_sec;
717 static time_t uptime;
718 static struct tm * stime;
719 static char window_title[100];
722 /* Check if there is a config thread which has finished executing but has not yet been freed */
723 if (this->ConfigThread && this->ConfigThread->IsDone())
725 /* Rehash has completed */
726 this->Logs->Log("CONFIG",DEBUG,"Detected ConfigThread exiting, tidying up...");
728 this->ConfigThread->Finish();
730 ConfigThread->join();
737 /* Run background module timers every few seconds
738 * (the docs say modules shouldnt rely on accurate
739 * timing using this event, so we dont have to
740 * time this exactly).
742 if (TIME.tv_sec != OLDTIME)
744 OLDTIME = TIME.tv_sec;
746 getrusage(RUSAGE_SELF, &ru);
747 stats->LastSampled = TIME;
748 stats->LastCPU = ru.ru_utime;
753 /* Allow a buffer of two seconds drift on this so that ntpdate etc dont harass admins */
754 if (TIME.tv_sec < OLDTIME - 2)
756 SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %lu secs.", (unsigned long)OLDTIME-TIME.tv_sec);
758 else if (TIME.tv_sec > OLDTIME + 2)
760 SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is jumping FORWARDS! Clock skipped %lu secs.", (unsigned long)TIME.tv_sec - OLDTIME);
763 if ((TIME.tv_sec % 3600) == 0)
765 this->RehashUsersAndChans();
766 FOREACH_MOD(I_OnGarbageCollect, OnGarbageCollect());
769 Timers->TickTimers(TIME.tv_sec);
770 this->DoBackgroundUserStuff();
772 if ((TIME.tv_sec % 5) == 0)
774 FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME.tv_sec));
775 SNO->FlushSnotices();
779 /* Call the socket engine to wait on the active
780 * file descriptors. The socket engine has everything's
781 * descriptors in its list... dns, modules, users,
782 * servers... so its nice and easy, just one call.
783 * This will cause any read or write events to be
784 * dispatched to their handlers.
786 this->SE->DispatchTrialWrites();
787 this->SE->DispatchEvents();
789 /* if any users were quit, take them out */
795 this->SignalHandler(s_signal);
803 /**********************************************************************************/
806 * An ircd in five lines! bwahahaha. ahahahahaha. ahahah *cough*.
809 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
810 * (until this returns true, a user will block in the waiting state, waiting to connect up to the
811 * registration timeout maximum seconds)
813 bool InspIRCd::AllModulesReportReady(LocalUser* user)
816 FIRST_MOD_RESULT(OnCheckReady, res, (user));
817 return (res == MOD_RES_PASSTHRU);
820 void InspIRCd::SetSignal(int signal)
825 /* On posix systems, the flow of the program starts right here, with
826 * ENTRYPOINT being a #define that defines main(). On Windows, ENTRYPOINT
827 * defines smain() and the real main() is in the service code under
828 * win32service.cpp. This allows the service control manager to control
829 * the process where we are running as a windows service.
833 new InspIRCd(argc, argv);
834 mysig = &ServerInstance->s_signal;
835 ServerInstance->Run();
836 delete ServerInstance;