1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2008 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
14 /* w00t was here. ;p */
16 /* $Install: src/inspircd $(BINPATH) */
23 #include <sys/resource.h>
27 /* Some systems don't define RUSAGE_SELF. This should fix them. */
32 /* CRT memory debugging */
34 #define _CRTDBG_MAP_ALLOC
43 #include "socketengine.h"
44 #include "inspircd_se_config.h"
46 #include "command_parse.h"
47 #include "exitcodes.h"
49 #include "testsuite.h"
55 /* Moved from exitcodes.h -- due to duplicate symbols -- Burlex
56 * XXX this is a bit ugly. -- w00t
58 const char* ExitCodes[] =
61 "DIE command", /* 1 */
62 "execv() failed", /* 2 */
63 "Internal error", /* 3 */
64 "Config file error", /* 4 */
65 "Logfile error", /* 5 */
66 "POSIX fork failed", /* 6 */
67 "Bad commandline parameters", /* 7 */
68 "No ports could be bound", /* 8 */
69 "Can't write PID file", /* 9 */
70 "SocketEngine could not initialize", /* 10 */
71 "Refusing to start up as root", /* 11 */
72 "Found a <die> tag!", /* 12 */
73 "Couldn't load module on startup", /* 13 */
74 "Could not create windows forked process", /* 14 */
75 "Received SIGTERM", /* 15 */
76 "Bad command handler loaded", /* 16 */
77 "RegisterServiceCtrlHandler failed", /* 17 */
78 "UpdateSCMStatus failed", /* 18 */
79 "CreateEvent failed" /* 19 */
82 void InspIRCd::Cleanup()
86 for (unsigned int i = 0; i < Config->ports.size(); i++)
88 /* This calls the constructor and closes the listening socket */
89 delete Config->ports[i];
92 Config->ports.clear();
95 /* Close all client sockets, or the new process inherits them */
96 for (std::vector<User*>::const_iterator i = this->Users->local_users.begin(); i != this->Users->local_users.end(); i++)
98 this->Users->QuitUser((*i), "Server shutdown");
102 /* We do this more than once, so that any service providers get a
103 * chance to be unhooked by the modules using them, but then get
104 * a chance to be removed themsleves.
106 * XXX there may be a better way to do this with 1.2
108 for (int tries = 0; tries < 3; tries++)
110 std::vector<std::string> module_names = Modules->GetAllModuleNames(0);
111 for (std::vector<std::string>::iterator k = module_names.begin(); k != module_names.end(); ++k)
113 /* Unload all modules, so they get a chance to clean up their listeners */
114 this->Modules->Unload(k->c_str());
117 /* Remove core commands */
118 Parser->RemoveCommands("<core>");
120 /* Cleanup Server Names */
121 for(servernamelist::iterator itr = servernames.begin(); itr != servernames.end(); ++itr)
124 /* Delete objects dynamically allocated in constructor
125 * (destructor would be more appropriate, but we're likely exiting)
128 // Must be deleted before modes as it decrements modelines
160 delete this->Modules;
165 delete this->BanCache;
201 delete this->Threads;
205 /* Needs to be deleted after Res, DNS has a timer */
213 this->Logs->CloseLogs();
222 void InspIRCd::Restart(const std::string &reason)
224 /* SendError flushes each client's queue,
225 * regardless of writeability state
227 this->SendError(reason);
229 /* Figure out our filename (if theyve renamed it, we're boned) */
233 char module[MAX_PATH];
234 if (GetModuleFileName(NULL, module, MAX_PATH))
237 me = Config->MyDir + "/inspircd";
240 char** argv = Config->argv;
244 if (execv(me.c_str(), argv) == -1)
246 /* Will raise a SIGABRT if not trapped */
247 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
251 void InspIRCd::ResetMaxBans()
253 for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
254 i->second->ResetMaxBans();
257 /** Because hash_map doesnt free its buckets when we delete items (this is a 'feature')
258 * we must occasionally rehash the hash (yes really).
259 * We do this by copying the entries from the old hash to a new hash, causing all
260 * empty buckets to be weeded out of the hash. We dont do this on a timer, as its
261 * very expensive, so instead we do it when the user types /REHASH and expects a
262 * short delay anyway.
264 void InspIRCd::RehashUsersAndChans()
266 user_hash* old_users = this->Users->clientlist;
267 user_hash* old_uuid = this->Users->uuidlist;
268 chan_hash* old_chans = this->chanlist;
270 this->Users->clientlist = new user_hash();
271 this->Users->uuidlist = new user_hash();
272 this->chanlist = new chan_hash();
274 for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
275 this->Users->clientlist->insert(*n);
279 for (user_hash::const_iterator n = old_uuid->begin(); n != old_uuid->end(); n++)
280 this->Users->uuidlist->insert(*n);
284 for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
285 this->chanlist->insert(*n);
290 void InspIRCd::SetSignals()
293 signal(SIGALRM, SIG_IGN);
294 signal(SIGHUP, InspIRCd::SetSignal);
295 signal(SIGPIPE, SIG_IGN);
296 signal(SIGCHLD, SIG_IGN);
298 signal(SIGTERM, InspIRCd::SetSignal);
301 void InspIRCd::QuickExit(int status)
306 bool InspIRCd::DaemonSeed()
309 printf_c("InspIRCd Process ID: \033[1;32m%lu\033[0m\n", GetCurrentProcessId());
312 signal(SIGTERM, InspIRCd::QuickExit);
315 if ((childpid = fork ()) < 0)
317 else if (childpid > 0)
319 /* We wait here for the child process to kill us,
320 * so that the shell prompt doesnt come back over
322 * Sending a kill with a signal of 0 just checks
323 * if the child pid is still around. If theyre not,
324 * they threw an error and we should give up.
326 while (kill(childpid, 0) != -1)
332 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
334 signal(SIGTERM, InspIRCd::SetSignal);
337 if (getrlimit(RLIMIT_CORE, &rl) == -1)
339 this->Logs->Log("STARTUP",DEFAULT,"Failed to getrlimit()!");
344 rl.rlim_cur = rl.rlim_max;
345 if (setrlimit(RLIMIT_CORE, &rl) == -1)
346 this->Logs->Log("STARTUP",DEFAULT,"setrlimit() failed, cannot increase coredump size.");
353 void InspIRCd::WritePID(const std::string &filename)
355 std::string fname = (filename.empty() ? "inspircd.pid" : filename);
356 std::replace(fname.begin(), fname.end(), '\\', '/');
357 if ((fname[0] != '/') && (!Config->StartsWithWindowsDriveLetter(filename)))
359 std::string::size_type pos;
360 std::string confpath = this->ConfigFileName;
361 if ((pos = confpath.rfind("/")) != std::string::npos)
363 /* Leaves us with just the path */
364 fname = confpath.substr(0, pos) + std::string("/") + fname;
367 std::ofstream outfile(fname.c_str());
368 if (outfile.is_open())
375 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
376 this->Logs->Log("STARTUP",DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
377 Exit(EXIT_STATUS_PID);
381 InspIRCd::InspIRCd(int argc, char** argv)
384 /* Functor initialisation. Note that the ordering here is very important.
386 * THIS MUST MATCH ORDER OF DECLARATION OF THE HandleWhateverFunc classes
387 * within class InspIRCd.
389 HandleProcessUser(this),
392 HandleFindDescriptor(this),
393 HandleFloodQuitUser(this),
394 HandleIsChannel(this),
398 /* Functor pointer initialisation. Must match the order of the list above
400 * THIS MUST MATCH THE ORDER OF DECLARATION OF THE FUNCTORS, e.g. the methods
401 * themselves within the class.
403 ProcessUser(&HandleProcessUser),
404 IsChannel(&HandleIsChannel),
406 Rehash(&HandleRehash),
407 IsNick(&HandleIsNick),
408 IsIdent(&HandleIsIdent),
409 FindDescriptor(&HandleFindDescriptor),
410 FloodQuitUser(&HandleFloodQuitUser)
414 // Strict, frequent checking of memory on debug builds
415 _CrtSetDbgFlag ( _CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
417 // Avoid erroneous frees on early exit
422 int do_version = 0, do_nofork = 0, do_debug = 0,
423 do_nolog = 0, do_root = 0, do_testsuite = 0; /* flag variables */
426 // Initialize so that if we exit before proper initialization they're not deleted
444 memset(&server, 0, sizeof(server));
445 memset(&client, 0, sizeof(client));
447 // This must be created first, so other parts of Insp can use it while starting up
448 this->Logs = new LogManager(this);
450 SocketEngineFactory* SEF = new SocketEngineFactory();
451 SE = SEF->Create(this);
454 ThreadEngineFactory* tef = new ThreadEngineFactory();
455 this->Threads = tef->Create(this);
457 this->Mutexes = new MutexFactory(this);
459 /* Default implementation does nothing */
460 this->PI = new ProtocolInterface(this);
464 // Create base manager classes early, so nothing breaks
465 this->Users = new UserManager(this);
467 this->Users->unregistered_count = 0;
469 this->Users->clientlist = new user_hash();
470 this->Users->uuidlist = new user_hash();
471 this->chanlist = new chan_hash();
473 this->Config = new ServerConfig(this);
474 this->SNO = new SnomaskManager(this);
475 this->BanCache = new BanCacheManager(this);
476 this->Modules = new ModuleManager(this);
477 this->stats = new serverstats();
478 this->Timers = new TimerManager(this);
479 this->Parser = new CommandParser(this);
480 this->XLines = new XLineManager(this);
482 this->Config->argv = argv;
483 this->Config->argc = argc;
485 if (chdir(Config->GetFullProgDir().c_str()))
487 printf("Unable to change to my directory: %s\nAborted.", strerror(errno));
491 this->Config->opertypes.clear();
492 this->Config->operclass.clear();
494 this->TIME = this->OLDTIME = this->startup_time = time(NULL);
497 *this->LogFileName = 0;
498 strlcpy(this->ConfigFileName, CONFIG_FILE, MAXBUF);
500 struct option longopts[] =
502 { "nofork", no_argument, &do_nofork, 1 },
503 { "logfile", required_argument, NULL, 'f' },
504 { "config", required_argument, NULL, 'c' },
505 { "debug", no_argument, &do_debug, 1 },
506 { "nolog", no_argument, &do_nolog, 1 },
507 { "runasroot", no_argument, &do_root, 1 },
508 { "version", no_argument, &do_version, 1 },
509 { "testsuite", no_argument, &do_testsuite, 1 },
513 while ((c = getopt_long_only(argc, argv, ":f:", longopts, NULL)) != -1)
518 /* Log filename was set */
519 strlcpy(LogFileName, optarg, MAXBUF);
522 /* Config filename was set */
523 strlcpy(ConfigFileName, optarg, MAXBUF);
526 /* getopt_long_only() set an int variable, just keep going */
529 /* Unknown parameter! DANGER, INTRUDER.... err.... yeah. */
530 printf("Usage: %s [--nofork] [--nolog] [--debug] [--logfile <filename>]\n\
531 [--runasroot] [--version] [--config <config>] [--testsuite]\n", argv[0]);
532 Exit(EXIT_STATUS_ARGV);
538 do_nofork = do_debug = true;
542 printf("\n%s r%s\n", VERSION, REVISION);
543 Exit(EXIT_STATUS_NOERROR);
551 DWORD ExitCode = WindowsForkStart(this);
558 WSAStartup(MAKEWORD(2,0), &wsadata);
559 ChangeWindowsSpecificPointers(this);
561 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
563 /* Set the finished argument values */
564 Config->nofork = do_nofork;
565 Config->forcedebug = do_debug;
566 Config->writelog = !do_nolog;
567 Config->TestSuite = do_testsuite;
569 if (!this->OpenLog(argv, argc))
571 printf("ERROR: Could not open logfile %s: %s\n\n", Config->logpath.c_str(), strerror(errno));
572 Exit(EXIT_STATUS_LOG);
575 if (!ServerConfig::FileExists(this->ConfigFileName))
577 printf("ERROR: Cannot open config file: %s\nExiting...\n", this->ConfigFileName);
578 this->Logs->Log("STARTUP",DEFAULT,"Unable to open config file %s", this->ConfigFileName);
579 Exit(EXIT_STATUS_CONFIG);
582 printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
583 printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
584 printf_c("Developers:\n");
585 printf_c("\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special\n");
586 printf_c("\t\033[1;32mpippijn, peavey, aquanight, fez\033[0m\n\n");
587 printf_c("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
589 Config->ClearStack();
591 this->Modes = new ModeParser(this);
597 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
598 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
599 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
600 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
601 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
602 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
603 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
604 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
612 if (!this->DaemonSeed())
614 printf("ERROR: could not go into daemon mode. Shutting down.\n");
615 Logs->Log("STARTUP", DEFAULT, "ERROR: could not go into daemon mode. Shutting down.");
616 Exit(EXIT_STATUS_FORK);
620 SE->RecoverFromFork();
622 /* During startup we don't actually initialize this
623 * in the thread engine.
625 this->ConfigThread = new ConfigReaderThread(this, true, "");
628 this->ConfigThread = NULL;
630 this->Res = new DNS(this);
632 this->AddServerName(Config->ServerName);
635 * Initialise SID/UID.
636 * For an explanation as to exactly how this works, and why it works this way, see GetUID().
644 for (const char* x = Config->ServerName; *x; ++x)
646 for (const char* y = Config->ServerDesc; *y; ++y)
650 Config->sid[0] = (char)(sid / 100 + 48);
651 Config->sid[1] = (char)(((sid / 10) % 10) + 48);
652 Config->sid[2] = (char)(sid % 10 + 48);
653 Config->sid[3] = '\0';
656 /* set up fake client again this time with the correct uid */
657 this->FakeClient = new User(this, "#INVALID");
658 this->FakeClient->SetFd(FD_MAGIC_NUMBER);
660 // Get XLine to do it's thing.
661 this->XLines->CheckELines();
662 this->XLines->ApplyLines();
665 int bounditems = BindPorts(true, found_ports, pl);
669 this->Modules->LoadAll();
671 /* Just in case no modules were loaded - fix for bug #101 */
672 this->BuildISupport();
673 InitializeDisabledCommands(Config->DisabledCommands, this);
675 if (Config->ports.size() != (unsigned int)found_ports)
677 printf("\nWARNING: Not all your client ports could be bound --\nstarting anyway with %d of %d client ports bound.\n\n", bounditems, found_ports);
678 printf("The following port(s) failed to bind:\n");
679 printf("Hint: Try using a public IP instead of blank or *\n\n");
681 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
683 printf("%d.\tAddress: %s\tReason: %s\n", j, i->first.empty() ? "<all>" : i->first.c_str(), i->second.c_str());
687 printf("\nInspIRCd is now running as '%s'[%s] with %d max open sockets\n", Config->ServerName,Config->GetSID().c_str(), SE->GetMaxFds());
692 if (kill(getppid(), SIGTERM) == -1)
694 printf("Error killing parent process: %s\n",strerror(errno));
695 Logs->Log("STARTUP", DEFAULT, "Error killing parent process: %s",strerror(errno));
699 if (isatty(0) && isatty(1) && isatty(2))
701 /* We didn't start from a TTY, we must have started from a background process -
702 * e.g. we are restarting, or being launched by cron. Dont kill parent, and dont
705 if ((!do_nofork) && (!do_testsuite))
713 Logs->Log("STARTUP", DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
717 WindowsIPC = new IPC(this);
720 WindowsForkKillOwner(this);
723 /* Set win32 service as running, if we are running as a service */
727 Logs->Log("STARTUP", DEFAULT, "Startup complete as '%s'[%s], %d max open sockets", Config->ServerName,Config->GetSID().c_str(), SE->GetMaxFds());
729 this->WritePID(Config->PID);
734 /* See if we're supposed to be running the test suite rather than entering the mainloop */
735 if (Config->TestSuite)
737 TestSuite* ts = new TestSuite(this);
747 static time_t uptime;
748 static struct tm * stime;
749 static char window_title[100];
752 /* Check if there is a config thread which has finished executing but has not yet been freed */
753 if (this->ConfigThread && this->ConfigThread->GetExitFlag())
755 /* Rehash has completed */
756 this->Logs->Log("CONFIG",DEBUG,"Detected ConfigThread exiting, tidying up...");
758 /* IMPORTANT: This delete may hang if you fuck up your thread syncronization.
759 * It will hang waiting for the ConfigThread to 'join' to avoid race conditons,
760 * until the other thread is completed.
765 /* These are currently not known to be threadsafe, so they are executed outside
766 * of the thread. It would be pretty simple to move them to the thread Run method
767 * once they are known threadsafe with all the correct mutexes in place.
769 * XXX: The order of these is IMPORTANT, do not reorder them without testing
772 this->XLines->CheckELines();
773 this->XLines->ApplyLines();
775 this->ResetMaxBans();
776 InitializeDisabledCommands(Config->DisabledCommands, this);
777 User* user = !Config->RehashUserUID.empty() ? FindNick(Config->RehashUserUID) : NULL;
778 FOREACH_MOD_I(this, I_OnRehash, OnRehash(user, Config->RehashParameter));
779 this->BuildISupport();
782 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
783 * Once per loop iteration is pleanty.
788 /* Run background module timers every few seconds
789 * (the docs say modules shouldnt rely on accurate
790 * timing using this event, so we dont have to
791 * time this exactly).
795 /* Allow a buffer of two seconds drift on this so that ntpdate etc dont harass admins */
796 if (TIME < OLDTIME - 2)
798 SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %lu secs.", (unsigned long)OLDTIME-TIME);
800 else if (TIME > OLDTIME + 2)
802 SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is jumping FORWARDS! Clock skipped %lu secs.", (unsigned long)TIME - OLDTIME);
805 if ((TIME % 3600) == 0)
807 this->RehashUsersAndChans();
808 FOREACH_MOD_I(this, I_OnGarbageCollect, OnGarbageCollect());
811 Timers->TickTimers(TIME);
812 this->DoBackgroundUserStuff();
816 FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
817 SNO->FlushSnotices();
820 /* Same change as in cmd_stats.cpp, use RUSAGE_SELF rather than '0' -- Om */
821 if (!getrusage(RUSAGE_SELF, &ru))
823 gettimeofday(&this->stats->LastSampled, NULL);
824 this->stats->LastCPU = ru.ru_utime;
831 /* Call the socket engine to wait on the active
832 * file descriptors. The socket engine has everything's
833 * descriptors in its list... dns, modules, users,
834 * servers... so its nice and easy, just one call.
835 * This will cause any read or write events to be
836 * dispatched to their handlers.
838 this->SE->DispatchEvents();
840 /* if any users were quit, take them out */
841 this->GlobalCulls.Apply();
843 /* If any inspsockets closed, remove them */
844 this->BufferedSocketCull();
848 this->SignalHandler(s_signal);
856 void InspIRCd::BufferedSocketCull()
858 for (std::map<BufferedSocket*,BufferedSocket*>::iterator x = SocketCull.begin(); x != SocketCull.end(); ++x)
860 this->Logs->Log("MISC",DEBUG,"Cull socket");
861 SE->DelFd(x->second);
868 /**********************************************************************************/
871 * An ircd in five lines! bwahahaha. ahahahahaha. ahahah *cough*.
874 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
875 * (until this returns true, a user will block in the waiting state, waiting to connect up to the
876 * registration timeout maximum seconds)
878 bool InspIRCd::AllModulesReportReady(User* user)
880 for (EventHandlerIter i = Modules->EventHandlers[I_OnCheckReady].begin(); i != Modules->EventHandlers[I_OnCheckReady].end(); ++i)
882 if (!(*i)->OnCheckReady(user))
888 time_t InspIRCd::Time()
893 void InspIRCd::SetSignal(int signal)
898 /* On posix systems, the flow of the program starts right here, with
899 * ENTRYPOINT being a #define that defines main(). On Windows, ENTRYPOINT
900 * defines smain() and the real main() is in the service code under
901 * win32service.cpp. This allows the service control manager to control
902 * the process where we are running as a windows service.
906 SI = new InspIRCd(argc, argv);
907 mysig = &SI->s_signal;