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)
93 void InspIRCd::Cleanup()
97 for (unsigned int i = 0; i < ports.size(); i++)
99 /* This calls the constructor and closes the listening socket */
106 /* Close all client sockets, or the new process inherits them */
107 std::vector<User*>::reverse_iterator i = Users->local_users.rbegin();
108 while (i != this->Users->local_users.rend())
111 Users->QuitUser(u, "Server shutdown");
114 /* We do this more than once, so that any service providers get a
115 * chance to be unhooked by the modules using them, but then get
116 * a chance to be removed themsleves.
118 * XXX there may be a better way to do this
120 for (int tries = 0; tries < 4; tries++)
122 std::vector<std::string> module_names = Modules->GetAllModuleNames(0);
123 for (std::vector<std::string>::iterator k = module_names.begin(); k != module_names.end(); ++k)
125 /* Unload all modules, so they get a chance to clean up their listeners */
126 this->Modules->Unload(k->c_str());
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 */
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) */
165 char module[MAX_PATH];
166 if (GetModuleFileName(NULL, module, MAX_PATH))
169 me = Config->MyDir + "/inspircd";
172 char** argv = Config->argv;
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 doesnt free its buckets when we delete items (this is a 'feature')
190 * we must occasionally rehash the hash (yes really).
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. We dont do this on a timer, as its
193 * very expensive, so instead we do it when the user types /REHASH and expects a
194 * short delay anyway.
196 void InspIRCd::RehashUsersAndChans()
198 user_hash* old_users = this->Users->clientlist;
199 user_hash* old_uuid = this->Users->uuidlist;
200 chan_hash* old_chans = this->chanlist;
202 this->Users->clientlist = new user_hash();
203 this->Users->uuidlist = new user_hash();
204 this->chanlist = new chan_hash();
206 for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
207 this->Users->clientlist->insert(*n);
211 for (user_hash::const_iterator n = old_uuid->begin(); n != old_uuid->end(); n++)
212 this->Users->uuidlist->insert(*n);
216 for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
217 this->chanlist->insert(*n);
222 void InspIRCd::SetSignals()
225 signal(SIGALRM, SIG_IGN);
226 signal(SIGHUP, InspIRCd::SetSignal);
227 signal(SIGPIPE, SIG_IGN);
228 signal(SIGCHLD, SIG_IGN);
229 /* We want E2BIG not a signal! */
230 signal(SIGXFSZ, SIG_IGN);
232 signal(SIGTERM, InspIRCd::SetSignal);
235 void InspIRCd::QuickExit(int status)
240 bool InspIRCd::DaemonSeed()
243 printf_c("InspIRCd Process ID: \033[1;32m%lu\033[0m\n", GetCurrentProcessId());
246 signal(SIGTERM, InspIRCd::QuickExit);
249 if ((childpid = fork ()) < 0)
251 else if (childpid > 0)
253 /* We wait here for the child process to kill us,
254 * so that the shell prompt doesnt come back over
256 * Sending a kill with a signal of 0 just checks
257 * if the child pid is still around. If theyre not,
258 * they threw an error and we should give up.
260 while (kill(childpid, 0) != -1)
266 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
268 signal(SIGTERM, InspIRCd::SetSignal);
271 if (getrlimit(RLIMIT_CORE, &rl) == -1)
273 this->Logs->Log("STARTUP",DEFAULT,"Failed to getrlimit()!");
278 rl.rlim_cur = rl.rlim_max;
279 if (setrlimit(RLIMIT_CORE, &rl) == -1)
280 this->Logs->Log("STARTUP",DEFAULT,"setrlimit() failed, cannot increase coredump size.");
287 void InspIRCd::WritePID(const std::string &filename)
289 std::string fname = (filename.empty() ? "inspircd.pid" : filename);
290 std::replace(fname.begin(), fname.end(), '\\', '/');
291 if ((fname[0] != '/') && (!Config->StartsWithWindowsDriveLetter(filename)))
293 std::string::size_type pos;
294 std::string confpath = this->ConfigFileName;
295 if ((pos = confpath.rfind("/")) != std::string::npos)
297 /* Leaves us with just the path */
298 fname = confpath.substr(0, pos) + std::string("/") + fname;
301 std::ofstream outfile(fname.c_str());
302 if (outfile.is_open())
309 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
310 this->Logs->Log("STARTUP",DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
311 Exit(EXIT_STATUS_PID);
315 InspIRCd::InspIRCd(int argc, char** argv) :
316 ConfigFileName("inspircd.conf"),
318 /* Functor pointer initialisation.
320 * THIS MUST MATCH THE ORDER OF DECLARATION OF THE FUNCTORS, e.g. the methods
321 * themselves within the class.
323 NICKForced("NICKForced", NULL),
324 OperQuit("OperQuit", NULL),
325 IsChannel(&HandleIsChannel),
327 Rehash(&HandleRehash),
328 IsNick(&HandleIsNick),
329 IsIdent(&HandleIsIdent),
330 FloodQuitUser(&HandleFloodQuitUser)
333 // Strict, frequent checking of memory on debug builds
334 _CrtSetDbgFlag ( _CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
336 // Avoid erroneous frees on early exit
340 ServerInstance = this;
342 Extensible::Register(&NICKForced);
343 Extensible::Register(&OperQuit);
346 int do_version = 0, do_nofork = 0, do_debug = 0,
347 do_nolog = 0, do_root = 0, do_testsuite = 0; /* flag variables */
350 // Initialize so that if we exit before proper initialization they're not deleted
366 this->ConfigThread = NULL;
369 this->TIME = time(NULL);
371 // This must be created first, so other parts of Insp can use it while starting up
372 this->Logs = new LogManager;
374 SE = CreateSocketEngine();
376 this->Threads = new ThreadEngine;
378 /* Default implementation does nothing */
379 this->PI = new ProtocolInterface;
383 // Create base manager classes early, so nothing breaks
384 this->Users = new UserManager;
386 this->Users->unregistered_count = 0;
388 this->Users->clientlist = new user_hash();
389 this->Users->uuidlist = new user_hash();
390 this->chanlist = new chan_hash();
392 this->Config = new ServerConfig;
393 this->SNO = new SnomaskManager;
394 this->BanCache = new BanCacheManager;
395 this->Modules = new ModuleManager();
396 this->stats = new serverstats();
397 this->Timers = new TimerManager;
398 this->Parser = new CommandParser;
399 this->XLines = new XLineManager;
401 this->Config->argv = argv;
402 this->Config->argc = argc;
404 if (chdir(Config->GetFullProgDir().c_str()))
406 printf("Unable to change to my directory: %s\nAborted.", strerror(errno));
410 this->Config->opertypes.clear();
411 this->Config->operclass.clear();
413 this->TIME = this->OLDTIME = this->startup_time = time(NULL);
416 *this->LogFileName = 0;
418 struct option longopts[] =
420 { "nofork", no_argument, &do_nofork, 1 },
421 { "logfile", required_argument, NULL, 'f' },
422 { "config", required_argument, NULL, 'c' },
423 { "debug", no_argument, &do_debug, 1 },
424 { "nolog", no_argument, &do_nolog, 1 },
425 { "runasroot", no_argument, &do_root, 1 },
426 { "version", no_argument, &do_version, 1 },
427 { "testsuite", no_argument, &do_testsuite, 1 },
432 while ((c = getopt_long_only(argc, argv, ":f:", longopts, &index)) != -1)
437 /* Log filename was set */
438 strlcpy(LogFileName, optarg, MAXBUF);
441 /* Config filename was set */
442 ConfigFileName = optarg;
445 /* getopt_long_only() set an int variable, just keep going */
448 /* Unknown parameter */
450 /* Fall through to handle other weird values too */
451 printf("Unknown parameter '%s'\n", argv[optind-1]);
452 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])), " ");
453 Exit(EXIT_STATUS_ARGV);
459 do_nofork = do_debug = true;
463 printf("\n%s r%s\n", VERSION, REVISION);
464 Exit(EXIT_STATUS_NOERROR);
472 DWORD ExitCode = WindowsForkStart();
479 WSAStartup(MAKEWORD(2,0), &wsadata);
480 ChangeWindowsSpecificPointers();
482 Config->MyExecutable = argv[0];
484 /* Set the finished argument values */
485 Config->nofork = do_nofork;
486 Config->forcedebug = do_debug;
487 Config->writelog = !do_nolog;
488 Config->TestSuite = do_testsuite;
490 if (!this->OpenLog(argv, argc))
492 printf("ERROR: Could not open logfile %s: %s\n\n", Config->logpath.c_str(), strerror(errno));
493 Exit(EXIT_STATUS_LOG);
496 if (!ServerConfig::FileExists(ConfigFileName.c_str()))
499 /* Windows can (and defaults to) hide file extensions, so let's play a bit nice for windows users. */
500 std::string txtconf = this->ConfigFileName;
501 txtconf.append(".txt");
503 if (ServerConfig::FileExists(txtconf.c_str()))
505 ConfigFileName = txtconf;
510 printf("ERROR: Cannot open config file: %s\nExiting...\n", ConfigFileName.c_str());
511 this->Logs->Log("STARTUP",DEFAULT,"Unable to open config file %s", ConfigFileName.c_str());
512 Exit(EXIT_STATUS_CONFIG);
516 printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
517 printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
518 printf_c("Developers:\n");
519 printf_c("\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special\n");
520 printf_c("\t\033[1;32mpeavey, aquanight, psychon, dz, danieldg\033[0m\n\n");
521 printf_c("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
523 this->Modes = new ModeParser;
529 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
530 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
531 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
532 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
533 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
534 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
535 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
536 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
544 if (!this->DaemonSeed())
546 printf("ERROR: could not go into daemon mode. Shutting down.\n");
547 Logs->Log("STARTUP", DEFAULT, "ERROR: could not go into daemon mode. Shutting down.");
548 Exit(EXIT_STATUS_FORK);
552 SE->RecoverFromFork();
554 /* During startup we don't actually initialize this
555 * in the thread engine.
557 this->Config->Read();
558 this->Config->Apply(NULL, "");
559 Logs->OpenFileLogs();
564 * Initialise SID/UID.
565 * For an explanation as to exactly how this works, and why it works this way, see GetUID().
568 if (Config->sid.empty())
574 for (const char* x = Config->ServerName.c_str(); *x; ++x)
576 for (const char* y = Config->ServerDesc.c_str(); *y; ++y)
578 sprintf(sidstr, "%03d", sid % 1000);
580 Config->sid = sidstr;
583 /* set up fake client again this time with the correct uid */
584 this->FakeClient = new FakeUser("!");
585 this->FakeClient->SetFakeServer(Config->ServerName);
587 // Get XLine to do it's thing.
588 this->XLines->CheckELines();
589 this->XLines->ApplyLines();
591 int bounditems = BindPorts(pl);
595 this->Modules->LoadAll();
597 /* Just in case no modules were loaded - fix for bug #101 */
598 this->BuildISupport();
599 Config->ApplyDisabledCommands(Config->DisabledCommands);
603 printf("\nWARNING: Not all your client ports could be bound --\nstarting anyway with %d of %d client ports bound.\n\n",
604 bounditems, bounditems + (int)pl.size());
605 printf("The following port(s) failed to bind:\n");
606 printf("Hint: Try using a public IP instead of blank or *\n\n");
608 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
610 printf("%d.\tAddress: %s\tReason: %s\n", j, i->first.empty() ? "<all>" : i->first.c_str(), i->second.c_str());
614 printf("\nInspIRCd is now running as '%s'[%s] with %d max open sockets\n",
615 Config->ServerName.c_str(),Config->GetSID().c_str(), SE->GetMaxFds());
620 if (kill(getppid(), SIGTERM) == -1)
622 printf("Error killing parent process: %s\n",strerror(errno));
623 Logs->Log("STARTUP", DEFAULT, "Error killing parent process: %s",strerror(errno));
627 if (isatty(0) && isatty(1) && isatty(2))
629 /* We didn't start from a TTY, we must have started from a background process -
630 * e.g. we are restarting, or being launched by cron. Dont kill parent, and dont
633 if ((!do_nofork) && (!do_testsuite))
641 Logs->Log("STARTUP", DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
645 WindowsIPC = new IPC;
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 if (!Config->SetGroup.empty())
663 ret = setgroups(0, NULL);
667 this->Logs->Log("SETGROUPS", DEFAULT, "setgroups() failed (wtf?): %s", strerror(errno));
675 g = getgrnam(this->Config->SetGroup.c_str());
679 this->Logs->Log("SETGUID", DEFAULT, "getgrnam() failed (bad user?): %s", strerror(errno));
683 ret = setgid(g->gr_gid);
687 this->Logs->Log("SETGUID", DEFAULT, "setgid() failed (bad user?): %s", strerror(errno));
692 if (!Config->SetUser.empty())
698 u = getpwnam(this->Config->SetUser.c_str());
702 this->Logs->Log("SETGUID", DEFAULT, "getpwnam() failed (bad user?): %s", strerror(errno));
706 int ret = setuid(u->pw_uid);
710 this->Logs->Log("SETGUID", DEFAULT, "setuid() failed (bad user?): %s", strerror(errno));
716 this->WritePID(Config->PID);
721 /* See if we're supposed to be running the test suite rather than entering the mainloop */
722 if (Config->TestSuite)
724 TestSuite* ts = new TestSuite;
734 static time_t uptime;
735 static struct tm * stime;
736 static char window_title[100];
739 /* Check if there is a config thread which has finished executing but has not yet been freed */
740 if (this->ConfigThread && this->ConfigThread->IsDone())
742 /* Rehash has completed */
743 this->Logs->Log("CONFIG",DEBUG,"Detected ConfigThread exiting, tidying up...");
745 this->ConfigThread->Finish();
747 ConfigThread->join();
752 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
753 * Once per loop iteration is pleanty.
758 /* Run background module timers every few seconds
759 * (the docs say modules shouldnt rely on accurate
760 * timing using this event, so we dont have to
761 * time this exactly).
765 /* Allow a buffer of two seconds drift on this so that ntpdate etc dont harass admins */
766 if (TIME < OLDTIME - 2)
768 SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %lu secs.", (unsigned long)OLDTIME-TIME);
770 else if (TIME > OLDTIME + 2)
772 SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is jumping FORWARDS! Clock skipped %lu secs.", (unsigned long)TIME - OLDTIME);
775 if ((TIME % 3600) == 0)
777 this->RehashUsersAndChans();
778 FOREACH_MOD(I_OnGarbageCollect, OnGarbageCollect());
781 Timers->TickTimers(TIME);
782 this->DoBackgroundUserStuff();
786 FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME));
787 SNO->FlushSnotices();
790 /* Same change as in cmd_stats.cpp, use RUSAGE_SELF rather than '0' -- Om */
791 if (!getrusage(RUSAGE_SELF, &ru))
793 gettimeofday(&this->stats->LastSampled, NULL);
794 this->stats->LastCPU = ru.ru_utime;
801 /* Call the socket engine to wait on the active
802 * file descriptors. The socket engine has everything's
803 * descriptors in its list... dns, modules, users,
804 * servers... so its nice and easy, just one call.
805 * This will cause any read or write events to be
806 * dispatched to their handlers.
808 this->SE->DispatchTrialWrites();
809 this->SE->DispatchEvents();
811 /* if any users were quit, take them out */
812 this->GlobalCulls.Apply();
816 this->SignalHandler(s_signal);
824 /**********************************************************************************/
827 * An ircd in five lines! bwahahaha. ahahahahaha. ahahah *cough*.
830 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
831 * (until this returns true, a user will block in the waiting state, waiting to connect up to the
832 * registration timeout maximum seconds)
834 bool InspIRCd::AllModulesReportReady(User* user)
837 FIRST_MOD_RESULT(OnCheckReady, res, (user));
838 return (res == MOD_RES_PASSTHRU);
841 time_t InspIRCd::Time()
846 void InspIRCd::SetSignal(int signal)
851 /* On posix systems, the flow of the program starts right here, with
852 * ENTRYPOINT being a #define that defines main(). On Windows, ENTRYPOINT
853 * defines smain() and the real main() is in the service code under
854 * win32service.cpp. This allows the service control manager to control
855 * the process where we are running as a windows service.
859 new InspIRCd(argc, argv);
860 mysig = &ServerInstance->s_signal;
861 ServerInstance->Run();
862 delete ServerInstance;