1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 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<User*>::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 */
116 DeleteZero(this->FakeClient);
117 DeleteZero(this->Users);
118 DeleteZero(this->Modes);
119 DeleteZero(this->XLines);
120 DeleteZero(this->Parser);
121 DeleteZero(this->stats);
122 DeleteZero(this->Modules);
123 DeleteZero(this->BanCache);
124 DeleteZero(this->SNO);
125 DeleteZero(this->Config);
126 DeleteZero(this->Res);
127 DeleteZero(this->chanlist);
128 DeleteZero(this->PI);
129 DeleteZero(this->Threads);
130 DeleteZero(this->Timers);
131 DeleteZero(this->SE);
133 this->Logs->CloseLogs();
134 DeleteZero(this->Logs);
137 void InspIRCd::Restart(const std::string &reason)
139 /* SendError flushes each client's queue,
140 * regardless of writeability state
142 this->SendError(reason);
144 /* Figure out our filename (if theyve renamed it, we're boned) */
148 char module[MAX_PATH];
149 if (GetModuleFileName(NULL, module, MAX_PATH))
152 me = Config->MyDir + "/inspircd";
155 char** argv = Config->argv;
159 if (execv(me.c_str(), argv) == -1)
161 /* Will raise a SIGABRT if not trapped */
162 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
166 void InspIRCd::ResetMaxBans()
168 for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
169 i->second->ResetMaxBans();
172 /** Because hash_map doesnt free its buckets when we delete items (this is a 'feature')
173 * we must occasionally rehash the hash (yes really).
174 * We do this by copying the entries from the old hash to a new hash, causing all
175 * empty buckets to be weeded out of the hash. We dont do this on a timer, as its
176 * very expensive, so instead we do it when the user types /REHASH and expects a
177 * short delay anyway.
179 void InspIRCd::RehashUsersAndChans()
181 user_hash* old_users = this->Users->clientlist;
182 user_hash* old_uuid = this->Users->uuidlist;
183 chan_hash* old_chans = this->chanlist;
185 this->Users->clientlist = new user_hash();
186 this->Users->uuidlist = new user_hash();
187 this->chanlist = new chan_hash();
189 for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
190 this->Users->clientlist->insert(*n);
194 for (user_hash::const_iterator n = old_uuid->begin(); n != old_uuid->end(); n++)
195 this->Users->uuidlist->insert(*n);
199 for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
200 this->chanlist->insert(*n);
205 void InspIRCd::SetSignals()
208 signal(SIGALRM, SIG_IGN);
209 signal(SIGHUP, InspIRCd::SetSignal);
210 signal(SIGPIPE, SIG_IGN);
211 signal(SIGCHLD, SIG_IGN);
212 /* We want E2BIG not a signal! */
213 signal(SIGXFSZ, SIG_IGN);
215 signal(SIGTERM, InspIRCd::SetSignal);
218 void InspIRCd::QuickExit(int status)
223 bool InspIRCd::DaemonSeed()
226 printf_c("InspIRCd Process ID: \033[1;32m%lu\033[0m\n", GetCurrentProcessId());
229 signal(SIGTERM, InspIRCd::QuickExit);
232 if ((childpid = fork ()) < 0)
234 else if (childpid > 0)
236 /* We wait here for the child process to kill us,
237 * so that the shell prompt doesnt come back over
239 * Sending a kill with a signal of 0 just checks
240 * if the child pid is still around. If theyre not,
241 * they threw an error and we should give up.
243 while (kill(childpid, 0) != -1)
249 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
251 signal(SIGTERM, InspIRCd::SetSignal);
254 if (getrlimit(RLIMIT_CORE, &rl) == -1)
256 this->Logs->Log("STARTUP",DEFAULT,"Failed to getrlimit()!");
259 rl.rlim_cur = rl.rlim_max;
261 if (setrlimit(RLIMIT_CORE, &rl) == -1)
262 this->Logs->Log("STARTUP",DEFAULT,"setrlimit() failed, cannot increase coredump size.");
268 void InspIRCd::WritePID(const std::string &filename)
270 std::string fname(filename);
272 fname = "data/inspircd.pid";
273 std::ofstream outfile(fname.c_str());
274 if (outfile.is_open())
281 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
282 this->Logs->Log("STARTUP",DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
283 Exit(EXIT_STATUS_PID);
287 InspIRCd::InspIRCd(int argc, char** argv) :
288 ConfigFileName("inspircd.conf"),
290 /* Functor pointer initialisation.
292 * THIS MUST MATCH THE ORDER OF DECLARATION OF THE FUNCTORS, e.g. the methods
293 * themselves within the class.
295 NICKForced("NICKForced", NULL),
296 OperQuit("OperQuit", NULL),
297 IsChannel(&HandleIsChannel),
299 Rehash(&HandleRehash),
300 IsNick(&HandleIsNick),
301 IsIdent(&HandleIsIdent),
302 FloodQuitUser(&HandleFloodQuitUser)
305 // Strict, frequent checking of memory on debug builds
306 _CrtSetDbgFlag ( _CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
308 // Avoid erroneous frees on early exit
312 ServerInstance = this;
314 Extensions.Register(&NICKForced);
315 Extensions.Register(&OperQuit);
318 int do_version = 0, do_nofork = 0, do_debug = 0,
319 do_nolog = 0, do_root = 0, do_testsuite = 0; /* flag variables */
322 // Initialize so that if we exit before proper initialization they're not deleted
338 this->ConfigThread = NULL;
341 this->TIME = time(NULL);
343 // This must be created first, so other parts of Insp can use it while starting up
344 this->Logs = new LogManager;
346 SE = CreateSocketEngine();
348 this->Threads = new ThreadEngine;
350 /* Default implementation does nothing */
351 this->PI = new ProtocolInterface;
355 // Create base manager classes early, so nothing breaks
356 this->Users = new UserManager;
358 this->Users->unregistered_count = 0;
360 this->Users->clientlist = new user_hash();
361 this->Users->uuidlist = new user_hash();
362 this->chanlist = new chan_hash();
364 this->Config = new ServerConfig;
365 this->SNO = new SnomaskManager;
366 this->BanCache = new BanCacheManager;
367 this->Modules = new ModuleManager();
368 this->stats = new serverstats();
369 this->Timers = new TimerManager;
370 this->Parser = new CommandParser;
371 this->XLines = new XLineManager;
373 this->Config->argv = argv;
374 this->Config->argc = argc;
376 this->TIME = this->OLDTIME = this->startup_time = time(NULL);
379 *this->LogFileName = 0;
381 struct option longopts[] =
383 { "nofork", no_argument, &do_nofork, 1 },
384 { "logfile", required_argument, NULL, 'f' },
385 { "config", required_argument, NULL, 'c' },
386 { "debug", no_argument, &do_debug, 1 },
387 { "nolog", no_argument, &do_nolog, 1 },
388 { "runasroot", no_argument, &do_root, 1 },
389 { "version", no_argument, &do_version, 1 },
390 { "testsuite", no_argument, &do_testsuite, 1 },
395 while ((c = getopt_long_only(argc, argv, ":f:", longopts, &index)) != -1)
400 /* Log filename was set */
401 strlcpy(LogFileName, optarg, MAXBUF);
404 /* Config filename was set */
405 ConfigFileName = optarg;
408 /* getopt_long_only() set an int variable, just keep going */
411 /* Unknown parameter */
413 /* Fall through to handle other weird values too */
414 printf("Unknown parameter '%s'\n", argv[optind-1]);
415 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])), " ");
416 Exit(EXIT_STATUS_ARGV);
422 do_nofork = do_debug = true;
426 printf("\n%s r%s\n", VERSION, REVISION);
427 Exit(EXIT_STATUS_NOERROR);
435 DWORD ExitCode = WindowsForkStart();
442 WSAStartup(MAKEWORD(2,0), &wsadata);
443 ChangeWindowsSpecificPointers();
446 /* Set the finished argument values */
447 Config->nofork = do_nofork;
448 Config->forcedebug = do_debug;
449 Config->writelog = !do_nolog;
450 Config->TestSuite = do_testsuite;
452 if (!this->OpenLog(argv, argc))
454 printf("ERROR: Could not open logfile %s: %s\n\n", Config->logpath.c_str(), strerror(errno));
455 Exit(EXIT_STATUS_LOG);
458 if (!ServerConfig::FileExists(ConfigFileName.c_str()))
461 /* Windows can (and defaults to) hide file extensions, so let's play a bit nice for windows users. */
462 std::string txtconf = this->ConfigFileName;
463 txtconf.append(".txt");
465 if (ServerConfig::FileExists(txtconf.c_str()))
467 ConfigFileName = txtconf;
472 printf("ERROR: Cannot open config file: %s\nExiting...\n", ConfigFileName.c_str());
473 this->Logs->Log("STARTUP",DEFAULT,"Unable to open config file %s", ConfigFileName.c_str());
474 Exit(EXIT_STATUS_CONFIG);
478 printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
479 printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
480 printf_c("Developers:\n");
481 printf_c("\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special\n");
482 printf_c("\t\033[1;32mpeavey, aquanight, psychon, dz, danieldg\033[0m\n\n");
483 printf_c("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
485 this->Modes = new ModeParser;
491 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
492 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
493 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
494 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
495 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
496 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
497 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
498 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
506 if (!this->DaemonSeed())
508 printf("ERROR: could not go into daemon mode. Shutting down.\n");
509 Logs->Log("STARTUP", DEFAULT, "ERROR: could not go into daemon mode. Shutting down.");
510 Exit(EXIT_STATUS_FORK);
514 SE->RecoverFromFork();
516 /* During startup we don't actually initialize this
517 * in the thread engine.
519 this->Config->Read();
520 this->Config->Apply(NULL, "");
521 Logs->OpenFileLogs();
526 * Initialise SID/UID.
527 * For an explanation as to exactly how this works, and why it works this way, see GetUID().
530 if (Config->sid.empty())
533 unsigned int sid = 0;
536 for (const char* x = Config->ServerName.c_str(); *x; ++x)
538 for (const char* y = Config->ServerDesc.c_str(); *y; ++y)
540 sprintf(sidstr, "%03d", sid % 1000);
542 Config->sid = sidstr;
545 /* set up fake client again this time with the correct uid */
546 this->FakeClient = new FakeUser("!");
547 this->FakeClient->SetFakeServer(Config->ServerName);
549 // Get XLine to do it's thing.
550 this->XLines->CheckELines();
551 this->XLines->ApplyLines();
553 int bounditems = BindPorts(pl);
557 this->Modules->LoadAll();
559 /* Just in case no modules were loaded - fix for bug #101 */
560 this->BuildISupport();
561 Config->ApplyDisabledCommands(Config->DisabledCommands);
565 printf("\nWARNING: Not all your client ports could be bound --\nstarting anyway with %d of %d client ports bound.\n\n",
566 bounditems, bounditems + (int)pl.size());
567 printf("The following port(s) failed to bind:\n");
568 printf("Hint: Try using a public IP instead of blank or *\n\n");
570 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
572 printf("%d.\tAddress: %s\tReason: %s\n", j, i->first.empty() ? "<all>" : i->first.c_str(), i->second.c_str());
576 printf("\nInspIRCd is now running as '%s'[%s] with %d max open sockets\n",
577 Config->ServerName.c_str(),Config->GetSID().c_str(), SE->GetMaxFds());
582 if (kill(getppid(), SIGTERM) == -1)
584 printf("Error killing parent process: %s\n",strerror(errno));
585 Logs->Log("STARTUP", DEFAULT, "Error killing parent process: %s",strerror(errno));
589 if (isatty(0) && isatty(1) && isatty(2))
591 /* We didn't start from a TTY, we must have started from a background process -
592 * e.g. we are restarting, or being launched by cron. Dont kill parent, and dont
595 if ((!do_nofork) && (!do_testsuite))
603 Logs->Log("STARTUP", DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
607 WindowsIPC = new IPC;
610 WindowsForkKillOwner();
613 /* Set win32 service as running, if we are running as a service */
617 Logs->Log("STARTUP", DEFAULT, "Startup complete as '%s'[%s], %d max open sockets", Config->ServerName.c_str(),Config->GetSID().c_str(), SE->GetMaxFds());
620 if (!Config->SetGroup.empty())
625 ret = setgroups(0, NULL);
629 this->Logs->Log("SETGROUPS", DEFAULT, "setgroups() failed (wtf?): %s", strerror(errno));
637 g = getgrnam(this->Config->SetGroup.c_str());
641 this->Logs->Log("SETGUID", DEFAULT, "getgrnam() failed (bad user?): %s", strerror(errno));
645 ret = setgid(g->gr_gid);
649 this->Logs->Log("SETGUID", DEFAULT, "setgid() failed (bad user?): %s", strerror(errno));
654 if (!Config->SetUser.empty())
660 u = getpwnam(this->Config->SetUser.c_str());
664 this->Logs->Log("SETGUID", DEFAULT, "getpwnam() failed (bad user?): %s", strerror(errno));
668 int ret = setuid(u->pw_uid);
672 this->Logs->Log("SETGUID", DEFAULT, "setuid() failed (bad user?): %s", strerror(errno));
678 this->WritePID(Config->PID);
683 /* See if we're supposed to be running the test suite rather than entering the mainloop */
684 if (Config->TestSuite)
686 TestSuite* ts = new TestSuite;
696 static time_t uptime;
697 static struct tm * stime;
698 static char window_title[100];
701 /* Check if there is a config thread which has finished executing but has not yet been freed */
702 if (this->ConfigThread && this->ConfigThread->IsDone())
704 /* Rehash has completed */
705 this->Logs->Log("CONFIG",DEBUG,"Detected ConfigThread exiting, tidying up...");
707 this->ConfigThread->Finish();
709 ConfigThread->join();
714 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
715 * Once per loop iteration is pleanty.
720 /* Run background module timers every few seconds
721 * (the docs say modules shouldnt rely on accurate
722 * timing using this event, so we dont have to
723 * time this exactly).
727 /* Allow a buffer of two seconds drift on this so that ntpdate etc dont harass admins */
728 if (TIME < OLDTIME - 2)
730 SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %lu secs.", (unsigned long)OLDTIME-TIME);
732 else if (TIME > OLDTIME + 2)
734 SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is jumping FORWARDS! Clock skipped %lu secs.", (unsigned long)TIME - OLDTIME);
737 if ((TIME % 3600) == 0)
739 this->RehashUsersAndChans();
740 FOREACH_MOD(I_OnGarbageCollect, OnGarbageCollect());
743 Timers->TickTimers(TIME);
744 this->DoBackgroundUserStuff();
748 FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME));
749 SNO->FlushSnotices();
752 /* Same change as in cmd_stats.cpp, use RUSAGE_SELF rather than '0' -- Om */
753 if (!getrusage(RUSAGE_SELF, &ru))
755 gettimeofday(&this->stats->LastSampled, NULL);
756 this->stats->LastCPU = ru.ru_utime;
763 /* Call the socket engine to wait on the active
764 * file descriptors. The socket engine has everything's
765 * descriptors in its list... dns, modules, users,
766 * servers... so its nice and easy, just one call.
767 * This will cause any read or write events to be
768 * dispatched to their handlers.
770 this->SE->DispatchTrialWrites();
771 this->SE->DispatchEvents();
773 /* if any users were quit, take them out */
779 this->SignalHandler(s_signal);
787 /**********************************************************************************/
790 * An ircd in five lines! bwahahaha. ahahahahaha. ahahah *cough*.
793 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
794 * (until this returns true, a user will block in the waiting state, waiting to connect up to the
795 * registration timeout maximum seconds)
797 bool InspIRCd::AllModulesReportReady(User* user)
800 FIRST_MOD_RESULT(OnCheckReady, res, (user));
801 return (res == MOD_RES_PASSTHRU);
804 time_t InspIRCd::Time()
809 void InspIRCd::SetSignal(int signal)
814 /* On posix systems, the flow of the program starts right here, with
815 * ENTRYPOINT being a #define that defines main(). On Windows, ENTRYPOINT
816 * defines smain() and the real main() is in the service code under
817 * win32service.cpp. This allows the service control manager to control
818 * the process where we are running as a windows service.
822 new InspIRCd(argc, argv);
823 mysig = &ServerInstance->s_signal;
824 ServerInstance->Run();
825 delete ServerInstance;