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"
51 using irc::sockets::insp_ntoa;
52 using irc::sockets::insp_inaddr;
53 using irc::sockets::insp_sockaddr;
59 /* Moved from exitcodes.h -- due to duplicate symbols -- Burlex
60 * XXX this is a bit ugly. -- w00t
62 const char* ExitCodes[] =
65 "DIE command", /* 1 */
66 "execv() failed", /* 2 */
67 "Internal error", /* 3 */
68 "Config file error", /* 4 */
69 "Logfile error", /* 5 */
70 "POSIX fork failed", /* 6 */
71 "Bad commandline parameters", /* 7 */
72 "No ports could be bound", /* 8 */
73 "Can't write PID file", /* 9 */
74 "SocketEngine could not initialize", /* 10 */
75 "Refusing to start up as root", /* 11 */
76 "Found a <die> tag!", /* 12 */
77 "Couldn't load module on startup", /* 13 */
78 "Could not create windows forked process", /* 14 */
79 "Received SIGTERM", /* 15 */
80 "Bad command handler loaded", /* 16 */
81 "RegisterServiceCtrlHandler failed", /* 17 */
82 "UpdateSCMStatus failed", /* 18 */
83 "CreateEvent failed" /* 19 */
86 void InspIRCd::Cleanup()
90 for (unsigned int i = 0; i < Config->ports.size(); i++)
92 /* This calls the constructor and closes the listening socket */
93 delete Config->ports[i];
96 Config->ports.clear();
99 /* Close all client sockets, or the new process inherits them */
100 for (std::vector<User*>::const_iterator i = this->Users->local_users.begin(); i != this->Users->local_users.end(); i++)
102 this->Users->QuitUser((*i), "Server shutdown");
106 /* We do this more than once, so that any service providers get a
107 * chance to be unhooked by the modules using them, but then get
108 * a chance to be removed themsleves.
110 * XXX there may be a better way to do this with 1.2
112 for (int tries = 0; tries < 3; tries++)
114 std::vector<std::string> module_names = Modules->GetAllModuleNames(0);
115 for (std::vector<std::string>::iterator k = module_names.begin(); k != module_names.end(); ++k)
117 /* Unload all modules, so they get a chance to clean up their listeners */
118 this->Modules->Unload(k->c_str());
121 /* Remove core commands */
122 Parser->RemoveCommands("<core>");
124 /* Cleanup Server Names */
125 for(servernamelist::iterator itr = servernames.begin(); itr != servernames.end(); ++itr)
128 /* Delete objects dynamically allocated in constructor
129 * (destructor would be more appropriate, but we're likely exiting)
132 // Must be deleted before modes as it decrements modelines
164 delete this->Modules;
169 delete this->BanCache;
205 delete this->Threads;
209 /* Needs to be deleted after Res, DNS has a timer */
217 this->Logs->CloseLogs();
226 void InspIRCd::Restart(const std::string &reason)
228 /* SendError flushes each client's queue,
229 * regardless of writeability state
231 this->SendError(reason);
233 /* Figure out our filename (if theyve renamed it, we're boned) */
237 char module[MAX_PATH];
238 if (GetModuleFileName(NULL, module, MAX_PATH))
241 me = Config->MyDir + "/inspircd";
244 char** argv = Config->argv;
248 if (execv(me.c_str(), argv) == -1)
250 /* Will raise a SIGABRT if not trapped */
251 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
255 void InspIRCd::ResetMaxBans()
257 for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
258 i->second->ResetMaxBans();
261 /** Because hash_map doesnt free its buckets when we delete items (this is a 'feature')
262 * we must occasionally rehash the hash (yes really).
263 * We do this by copying the entries from the old hash to a new hash, causing all
264 * empty buckets to be weeded out of the hash. We dont do this on a timer, as its
265 * very expensive, so instead we do it when the user types /REHASH and expects a
266 * short delay anyway.
268 void InspIRCd::RehashUsersAndChans()
270 user_hash* old_users = this->Users->clientlist;
271 user_hash* old_uuid = this->Users->uuidlist;
272 chan_hash* old_chans = this->chanlist;
274 this->Users->clientlist = new user_hash();
275 this->Users->uuidlist = new user_hash();
276 this->chanlist = new chan_hash();
278 for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
279 this->Users->clientlist->insert(*n);
283 for (user_hash::const_iterator n = old_uuid->begin(); n != old_uuid->end(); n++)
284 this->Users->uuidlist->insert(*n);
288 for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
289 this->chanlist->insert(*n);
294 void InspIRCd::SetSignals()
297 signal(SIGALRM, SIG_IGN);
298 signal(SIGHUP, InspIRCd::SetSignal);
299 signal(SIGPIPE, SIG_IGN);
300 signal(SIGCHLD, SIG_IGN);
302 signal(SIGTERM, InspIRCd::SetSignal);
305 void InspIRCd::QuickExit(int status)
310 bool InspIRCd::DaemonSeed()
313 printf_c("InspIRCd Process ID: \033[1;32m%lu\033[0m\n", GetCurrentProcessId());
316 signal(SIGTERM, InspIRCd::QuickExit);
319 if ((childpid = fork ()) < 0)
321 else if (childpid > 0)
323 /* We wait here for the child process to kill us,
324 * so that the shell prompt doesnt come back over
326 * Sending a kill with a signal of 0 just checks
327 * if the child pid is still around. If theyre not,
328 * they threw an error and we should give up.
330 while (kill(childpid, 0) != -1)
336 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
338 signal(SIGTERM, InspIRCd::SetSignal);
341 if (getrlimit(RLIMIT_CORE, &rl) == -1)
343 this->Logs->Log("STARTUP",DEFAULT,"Failed to getrlimit()!");
348 rl.rlim_cur = rl.rlim_max;
349 if (setrlimit(RLIMIT_CORE, &rl) == -1)
350 this->Logs->Log("STARTUP",DEFAULT,"setrlimit() failed, cannot increase coredump size.");
357 void InspIRCd::WritePID(const std::string &filename)
359 std::string fname = (filename.empty() ? "inspircd.pid" : filename);
360 std::replace(fname.begin(), fname.end(), '\\', '/');
361 if ((fname[0] != '/') && (!Config->StartsWithWindowsDriveLetter(filename)))
363 std::string::size_type pos;
364 std::string confpath = this->ConfigFileName;
365 if ((pos = confpath.rfind("/")) != std::string::npos)
367 /* Leaves us with just the path */
368 fname = confpath.substr(0, pos) + std::string("/") + fname;
371 std::ofstream outfile(fname.c_str());
372 if (outfile.is_open())
379 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
380 this->Logs->Log("STARTUP",DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
381 Exit(EXIT_STATUS_PID);
385 InspIRCd::InspIRCd(int argc, char** argv)
388 /* Functor initialisation. Note that the ordering here is very important.
390 * THIS MUST MATCH ORDER OF DECLARATION OF THE HandleWhateverFunc classes
391 * within class InspIRCd.
393 HandleProcessUser(this),
396 HandleFindDescriptor(this),
397 HandleFloodQuitUser(this),
398 HandleIsChannel(this),
402 /* Functor pointer initialisation. Must match the order of the list above
404 * THIS MUST MATCH THE ORDER OF DECLARATION OF THE FUNCTORS, e.g. the methods
405 * themselves within the class.
407 ProcessUser(&HandleProcessUser),
408 IsChannel(&HandleIsChannel),
410 Rehash(&HandleRehash),
411 IsNick(&HandleIsNick),
412 IsIdent(&HandleIsIdent),
413 FindDescriptor(&HandleFindDescriptor),
414 FloodQuitUser(&HandleFloodQuitUser)
418 // Strict, frequent checking of memory on debug builds
419 _CrtSetDbgFlag ( _CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
421 // Avoid erroneous frees on early exit
426 int do_version = 0, do_nofork = 0, do_debug = 0,
427 do_nolog = 0, do_root = 0, do_testsuite = 0; /* flag variables */
430 // Initialize so that if we exit before proper initialization they're not deleted
448 memset(&server, 0, sizeof(server));
449 memset(&client, 0, sizeof(client));
451 // This must be created first, so other parts of Insp can use it while starting up
452 this->Logs = new LogManager(this);
454 SocketEngineFactory* SEF = new SocketEngineFactory();
455 SE = SEF->Create(this);
458 ThreadEngineFactory* tef = new ThreadEngineFactory();
459 this->Threads = tef->Create(this);
461 this->Mutexes = new MutexFactory(this);
463 /* Default implementation does nothing */
464 this->PI = new ProtocolInterface(this);
468 // Create base manager classes early, so nothing breaks
469 this->Users = new UserManager(this);
471 this->Users->unregistered_count = 0;
473 this->Users->clientlist = new user_hash();
474 this->Users->uuidlist = new user_hash();
475 this->chanlist = new chan_hash();
477 this->Config = new ServerConfig(this);
478 this->SNO = new SnomaskManager(this);
479 this->BanCache = new BanCacheManager(this);
480 this->Modules = new ModuleManager(this);
481 this->stats = new serverstats();
482 this->Timers = new TimerManager(this);
483 this->Parser = new CommandParser(this);
484 this->XLines = new XLineManager(this);
486 this->Config->argv = argv;
487 this->Config->argc = argc;
489 if (chdir(Config->GetFullProgDir().c_str()))
491 printf("Unable to change to my directory: %s\nAborted.", strerror(errno));
495 this->Config->opertypes.clear();
496 this->Config->operclass.clear();
498 this->TIME = this->OLDTIME = this->startup_time = time(NULL);
501 *this->LogFileName = 0;
502 strlcpy(this->ConfigFileName, CONFIG_FILE, MAXBUF);
504 struct option longopts[] =
506 { "nofork", no_argument, &do_nofork, 1 },
507 { "logfile", required_argument, NULL, 'f' },
508 { "config", required_argument, NULL, 'c' },
509 { "debug", no_argument, &do_debug, 1 },
510 { "nolog", no_argument, &do_nolog, 1 },
511 { "runasroot", no_argument, &do_root, 1 },
512 { "version", no_argument, &do_version, 1 },
513 { "testsuite", no_argument, &do_testsuite, 1 },
517 while ((c = getopt_long_only(argc, argv, ":f:", longopts, NULL)) != -1)
522 /* Log filename was set */
523 strlcpy(LogFileName, optarg, MAXBUF);
526 /* Config filename was set */
527 strlcpy(ConfigFileName, optarg, MAXBUF);
530 /* getopt_long_only() set an int variable, just keep going */
533 /* Unknown parameter! DANGER, INTRUDER.... err.... yeah. */
534 printf("Usage: %s [--nofork] [--nolog] [--debug] [--logfile <filename>]\n\
535 [--runasroot] [--version] [--config <config>] [--testsuite]\n", argv[0]);
536 Exit(EXIT_STATUS_ARGV);
542 do_nofork = do_debug = true;
546 printf("\n%s r%s\n", VERSION, REVISION);
547 Exit(EXIT_STATUS_NOERROR);
555 DWORD ExitCode = WindowsForkStart(this);
562 WSAStartup(MAKEWORD(2,0), &wsadata);
563 ChangeWindowsSpecificPointers(this);
565 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
567 /* Set the finished argument values */
568 Config->nofork = do_nofork;
569 Config->forcedebug = do_debug;
570 Config->writelog = !do_nolog;
571 Config->TestSuite = do_testsuite;
573 if (!this->OpenLog(argv, argc))
575 printf("ERROR: Could not open logfile %s: %s\n\n", Config->logpath.c_str(), strerror(errno));
576 Exit(EXIT_STATUS_LOG);
579 if (!ServerConfig::FileExists(this->ConfigFileName))
581 printf("ERROR: Cannot open config file: %s\nExiting...\n", this->ConfigFileName);
582 this->Logs->Log("STARTUP",DEFAULT,"Unable to open config file %s", this->ConfigFileName);
583 Exit(EXIT_STATUS_CONFIG);
586 printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
587 printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
588 printf_c("Developers:\n");
589 printf_c("\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special\n");
590 printf_c("\t\033[1;32mpippijn, peavey, aquanight, fez\033[0m\n\n");
591 printf_c("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
593 Config->ClearStack();
595 this->Modes = new ModeParser(this);
601 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
602 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
603 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
604 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
605 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
606 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
607 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
608 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
616 if (!this->DaemonSeed())
618 printf("ERROR: could not go into daemon mode. Shutting down.\n");
619 Logs->Log("STARTUP", DEFAULT, "ERROR: could not go into daemon mode. Shutting down.");
620 Exit(EXIT_STATUS_FORK);
624 SE->RecoverFromFork();
626 /* During startup we don't actually initialize this
627 * in the thread engine.
629 this->ConfigThread = new ConfigReaderThread(this, true, NULL);
632 this->ConfigThread = NULL;
634 this->Res = new DNS(this);
636 this->AddServerName(Config->ServerName);
639 * Initialise SID/UID.
640 * For an explanation as to exactly how this works, and why it works this way, see GetUID().
648 for (const char* x = Config->ServerName; *x; ++x)
650 for (const char* y = Config->ServerDesc; *y; ++y)
654 Config->sid[0] = (char)(sid / 100 + 48);
655 Config->sid[1] = (char)(((sid / 10) % 10) + 48);
656 Config->sid[2] = (char)(sid % 10 + 48);
657 Config->sid[3] = '\0';
660 /* set up fake client again this time with the correct uid */
661 this->FakeClient = new User(this, "#INVALID");
662 this->FakeClient->SetFd(FD_MAGIC_NUMBER);
664 // Get XLine to do it's thing.
665 this->XLines->CheckELines();
666 this->XLines->ApplyLines();
669 int bounditems = BindPorts(true, found_ports, pl);
673 this->Modules->LoadAll();
675 /* Just in case no modules were loaded - fix for bug #101 */
676 this->BuildISupport();
677 InitializeDisabledCommands(Config->DisabledCommands, this);
679 if (Config->ports.size() != (unsigned int)found_ports)
681 printf("\nWARNING: Not all your client ports could be bound --\nstarting anyway with %d of %d client ports bound.\n\n", bounditems, found_ports);
682 printf("The following port(s) failed to bind:\n");
683 printf("Hint: Try using a public IP instead of blank or *\n\n");
685 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
687 printf("%d.\tAddress: %s\tReason: %s\n", j, i->first.empty() ? "<all>" : i->first.c_str(), i->second.c_str());
691 printf("\nInspIRCd is now running as '%s'[%s] with %d max open sockets\n", Config->ServerName,Config->GetSID().c_str(), SE->GetMaxFds());
696 if (kill(getppid(), SIGTERM) == -1)
698 printf("Error killing parent process: %s\n",strerror(errno));
699 Logs->Log("STARTUP", DEFAULT, "Error killing parent process: %s",strerror(errno));
703 if (isatty(0) && isatty(1) && isatty(2))
705 /* We didn't start from a TTY, we must have started from a background process -
706 * e.g. we are restarting, or being launched by cron. Dont kill parent, and dont
709 if ((!do_nofork) && (!do_testsuite))
717 Logs->Log("STARTUP", DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
721 WindowsIPC = new IPC(this);
724 WindowsForkKillOwner(this);
727 /* Set win32 service as running, if we are running as a service */
731 Logs->Log("STARTUP", DEFAULT, "Startup complete as '%s'[%s], %d max open sockets", Config->ServerName,Config->GetSID().c_str(), SE->GetMaxFds());
733 this->WritePID(Config->PID);
738 /* See if we're supposed to be running the test suite rather than entering the mainloop */
739 if (Config->TestSuite)
741 TestSuite* ts = new TestSuite(this);
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->GetExitFlag())
759 /* Rehash has completed */
760 this->Logs->Log("CONFIG",DEBUG,"Detected ConfigThread exiting, tidying up...");
762 /* IMPORTANT: This delete may hang if you fuck up your thread syncronization.
763 * It will hang waiting for the ConfigThread to 'join' to avoid race conditons,
764 * until the other thread is completed.
769 /* These are currently not known to be threadsafe, so they are executed outside
770 * of the thread. It would be pretty simple to move them to the thread Run method
771 * once they are known threadsafe with all the correct mutexes in place.
773 * XXX: The order of these is IMPORTANT, do not reorder them without testing
776 this->XLines->CheckELines();
777 this->XLines->ApplyLines();
779 this->ResetMaxBans();
780 InitializeDisabledCommands(Config->DisabledCommands, this);
781 FOREACH_MOD_I(this, I_OnRehash, OnRehash(Config->RehashUser, Config->RehashParameter));
782 this->BuildISupport();
785 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
786 * Once per loop iteration is pleanty.
791 /* Run background module timers every few seconds
792 * (the docs say modules shouldnt rely on accurate
793 * timing using this event, so we dont have to
794 * time this exactly).
798 /* Allow a buffer of two seconds drift on this so that ntpdate etc dont harass admins */
799 if (TIME < OLDTIME - 2)
801 SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %lu secs.", (unsigned long)OLDTIME-TIME);
803 else if (TIME > OLDTIME + 2)
805 SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is jumping FORWARDS! Clock skipped %lu secs.", (unsigned long)TIME - OLDTIME);
808 if ((TIME % 3600) == 0)
810 this->RehashUsersAndChans();
811 FOREACH_MOD_I(this, I_OnGarbageCollect, OnGarbageCollect());
814 Timers->TickTimers(TIME);
815 this->DoBackgroundUserStuff();
819 FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
820 SNO->FlushSnotices();
823 /* Same change as in cmd_stats.cpp, use RUSAGE_SELF rather than '0' -- Om */
824 if (!getrusage(RUSAGE_SELF, &ru))
826 gettimeofday(&this->stats->LastSampled, NULL);
827 this->stats->LastCPU = ru.ru_utime;
834 /* Call the socket engine to wait on the active
835 * file descriptors. The socket engine has everything's
836 * descriptors in its list... dns, modules, users,
837 * servers... so its nice and easy, just one call.
838 * This will cause any read or write events to be
839 * dispatched to their handlers.
841 this->SE->DispatchEvents();
843 /* if any users were quit, take them out */
844 this->GlobalCulls.Apply();
846 /* If any inspsockets closed, remove them */
847 this->BufferedSocketCull();
851 this->SignalHandler(s_signal);
859 void InspIRCd::BufferedSocketCull()
861 for (std::map<BufferedSocket*,BufferedSocket*>::iterator x = SocketCull.begin(); x != SocketCull.end(); ++x)
863 this->Logs->Log("MISC",DEBUG,"Cull socket");
864 SE->DelFd(x->second);
871 /**********************************************************************************/
874 * An ircd in five lines! bwahahaha. ahahahahaha. ahahah *cough*.
877 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
878 * (until this returns true, a user will block in the waiting state, waiting to connect up to the
879 * registration timeout maximum seconds)
881 bool InspIRCd::AllModulesReportReady(User* user)
883 for (EventHandlerIter i = Modules->EventHandlers[I_OnCheckReady].begin(); i != Modules->EventHandlers[I_OnCheckReady].end(); ++i)
885 if (!(*i)->OnCheckReady(user))
891 time_t InspIRCd::Time()
896 void InspIRCd::SetSignal(int signal)
901 /* On posix systems, the flow of the program starts right here, with
902 * ENTRYPOINT being a #define that defines main(). On Windows, ENTRYPOINT
903 * defines smain() and the real main() is in the service code under
904 * win32service.cpp. This allows the service control manager to control
905 * the process where we are running as a windows service.
909 SI = new InspIRCd(argc, argv);
910 mysig = &SI->s_signal;