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 /* $Install: src/inspircd $(BINPATH) */
21 #include <sys/resource.h>
25 /* Some systems don't define RUSAGE_SELF. This should fix them. */
30 /* CRT memory debugging */
32 #define _CRTDBG_MAP_ALLOC
41 #include "socketengine.h"
42 #include "inspircd_se_config.h"
44 #include "command_parse.h"
45 #include "exitcodes.h"
47 #include "testsuite.h"
49 using irc::sockets::insp_ntoa;
50 using irc::sockets::insp_inaddr;
51 using irc::sockets::insp_sockaddr;
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 */
80 void InspIRCd::Cleanup()
84 for (unsigned int i = 0; i < Config->ports.size(); i++)
86 /* This calls the constructor and closes the listening socket */
87 delete Config->ports[i];
90 Config->ports.clear();
93 /* Close all client sockets, or the new process inherits them */
94 for (std::vector<User*>::const_iterator i = this->Users->local_users.begin(); i != this->Users->local_users.end(); i++)
96 (*i)->SetWriteError("Server shutdown");
100 /* We do this more than once, so that any service providers get a
101 * chance to be unhooked by the modules using them, but then get
102 * a chance to be removed themsleves.
104 * XXX there may be a better way to do this with 1.2
106 for (int tries = 0; tries < 3; tries++)
108 std::vector<std::string> module_names = Modules->GetAllModuleNames(0);
109 for (std::vector<std::string>::iterator k = module_names.begin(); k != module_names.end(); ++k)
111 /* Unload all modules, so they get a chance to clean up their listeners */
112 this->Modules->Unload(k->c_str());
115 /* Remove core commands */
116 Parser->RemoveCommands("<core>");
118 /* Cleanup Server Names */
119 for(servernamelist::iterator itr = servernames.begin(); itr != servernames.end(); ++itr)
122 /* Delete objects dynamically allocated in constructor
123 * (destructor would be more appropriate, but we're likely exiting)
126 // Must be deleted before modes as it decrements modelines
158 delete this->Modules;
163 delete this->BanCache;
199 delete this->Threads;
203 /* Needs to be deleted after Res, DNS has a timer */
211 this->Logs->CloseLogs();
220 void InspIRCd::Restart(const std::string &reason)
222 /* SendError flushes each client's queue,
223 * regardless of writeability state
225 this->SendError(reason);
227 /* Figure out our filename (if theyve renamed it, we're boned) */
231 char module[MAX_PATH];
232 if (GetModuleFileName(NULL, module, MAX_PATH))
235 me = Config->MyDir + "/inspircd";
238 char** argv = Config->argv;
242 if (execv(me.c_str(), argv) == -1)
244 /* Will raise a SIGABRT if not trapped */
245 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
249 void InspIRCd::ResetMaxBans()
251 for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
252 i->second->ResetMaxBans();
255 /** Because hash_map doesnt free its buckets when we delete items (this is a 'feature')
256 * we must occasionally rehash the hash (yes really).
257 * We do this by copying the entries from the old hash to a new hash, causing all
258 * empty buckets to be weeded out of the hash. We dont do this on a timer, as its
259 * very expensive, so instead we do it when the user types /REHASH and expects a
260 * short delay anyway.
262 void InspIRCd::RehashUsersAndChans()
264 user_hash* old_users = this->Users->clientlist;
265 user_hash* old_uuid = this->Users->uuidlist;
266 chan_hash* old_chans = this->chanlist;
268 this->Users->clientlist = new user_hash();
269 this->Users->uuidlist = new user_hash();
270 this->chanlist = new chan_hash();
272 for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
273 this->Users->clientlist->insert(*n);
277 for (user_hash::const_iterator n = old_uuid->begin(); n != old_uuid->end(); n++)
278 this->Users->uuidlist->insert(*n);
282 for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
283 this->chanlist->insert(*n);
288 void InspIRCd::SetSignals()
291 signal(SIGALRM, SIG_IGN);
292 signal(SIGHUP, InspIRCd::SetSignal);
293 signal(SIGPIPE, SIG_IGN);
294 signal(SIGCHLD, SIG_IGN);
296 signal(SIGTERM, InspIRCd::SetSignal);
299 void InspIRCd::QuickExit(int status)
304 bool InspIRCd::DaemonSeed()
307 printf_c("InspIRCd Process ID: \033[1;32m%lu\033[0m\n", GetCurrentProcessId());
310 signal(SIGTERM, InspIRCd::QuickExit);
313 if ((childpid = fork ()) < 0)
315 else if (childpid > 0)
317 /* We wait here for the child process to kill us,
318 * so that the shell prompt doesnt come back over
320 * Sending a kill with a signal of 0 just checks
321 * if the child pid is still around. If theyre not,
322 * they threw an error and we should give up.
324 while (kill(childpid, 0) != -1)
330 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
332 signal(SIGTERM, InspIRCd::SetSignal);
335 if (getrlimit(RLIMIT_CORE, &rl) == -1)
337 this->Logs->Log("STARTUP",DEFAULT,"Failed to getrlimit()!");
342 rl.rlim_cur = rl.rlim_max;
343 if (setrlimit(RLIMIT_CORE, &rl) == -1)
344 this->Logs->Log("STARTUP",DEFAULT,"setrlimit() failed, cannot increase coredump size.");
351 void InspIRCd::WritePID(const std::string &filename)
353 std::string fname = (filename.empty() ? "inspircd.pid" : filename);
354 std::replace(fname.begin(), fname.end(), '\\', '/');
355 if ((fname[0] != '/') && (!Config->StartsWithWindowsDriveLetter(filename)))
357 std::string::size_type pos;
358 std::string confpath = this->ConfigFileName;
359 if ((pos = confpath.rfind("/")) != std::string::npos)
361 /* Leaves us with just the path */
362 fname = confpath.substr(0, pos) + std::string("/") + fname;
365 std::ofstream outfile(fname.c_str());
366 if (outfile.is_open())
373 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
374 this->Logs->Log("STARTUP",DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
375 Exit(EXIT_STATUS_PID);
379 InspIRCd::InspIRCd(int argc, char** argv)
382 /* Functor initialisation. Note that the ordering here is very important.
384 * THIS MUST MATCH ORDER OF DECLARATION OF THE HandleWhateverFunc classes
385 * within class InspIRCd.
387 HandleProcessUser(this),
390 HandleFindDescriptor(this),
391 HandleFloodQuitUser(this),
392 HandleIsChannel(this),
396 /* Functor pointer initialisation. Must match the order of the list above
398 * THIS MUST MATCH THE ORDER OF DECLARATION OF THE FUNCTORS, e.g. the methods
399 * themselves within the class.
401 ProcessUser(&HandleProcessUser),
402 IsChannel(&HandleIsChannel),
404 Rehash(&HandleRehash),
405 IsNick(&HandleIsNick),
406 IsIdent(&HandleIsIdent),
407 FindDescriptor(&HandleFindDescriptor),
408 FloodQuitUser(&HandleFloodQuitUser)
412 // Strict, frequent checking of memory on debug builds
413 _CrtSetDbgFlag ( _CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
415 // Avoid erroneous frees on early exit
420 int do_version = 0, do_nofork = 0, do_debug = 0,
421 do_nolog = 0, do_root = 0, do_testsuite = 0; /* flag variables */
424 // Initialize so that if we exit before proper initialization they're not deleted
442 memset(&server, 0, sizeof(server));
443 memset(&client, 0, sizeof(client));
445 // This must be created first, so other parts of Insp can use it while starting up
446 this->Logs = new LogManager(this);
448 SocketEngineFactory* SEF = new SocketEngineFactory();
449 SE = SEF->Create(this);
452 ThreadEngineFactory* tef = new ThreadEngineFactory();
453 this->Threads = tef->Create(this);
456 /* Default implementation does nothing */
457 this->PI = new ProtocolInterface(this);
461 // Create base manager classes early, so nothing breaks
462 this->Users = new UserManager(this);
464 this->Users->unregistered_count = 0;
466 this->Users->clientlist = new user_hash();
467 this->Users->uuidlist = new user_hash();
468 this->chanlist = new chan_hash();
470 this->Config = new ServerConfig(this);
471 this->SNO = new SnomaskManager(this);
472 this->BanCache = new BanCacheManager(this);
473 this->Modules = new ModuleManager(this);
474 this->stats = new serverstats();
475 this->Timers = new TimerManager(this);
476 this->Parser = new CommandParser(this);
477 this->XLines = new XLineManager(this);
479 this->Config->argv = argv;
480 this->Config->argc = argc;
482 if (chdir(Config->GetFullProgDir().c_str()))
484 printf("Unable to change to my directory: %s\nAborted.", strerror(errno));
488 this->Config->opertypes.clear();
489 this->Config->operclass.clear();
491 this->TIME = this->OLDTIME = this->startup_time = time(NULL);
494 *this->LogFileName = 0;
495 strlcpy(this->ConfigFileName, CONFIG_FILE, MAXBUF);
497 struct option longopts[] =
499 { "nofork", no_argument, &do_nofork, 1 },
500 { "logfile", required_argument, NULL, 'f' },
501 { "config", required_argument, NULL, 'c' },
502 { "debug", no_argument, &do_debug, 1 },
503 { "nolog", no_argument, &do_nolog, 1 },
504 { "runasroot", no_argument, &do_root, 1 },
505 { "version", no_argument, &do_version, 1 },
506 { "testsuite", no_argument, &do_testsuite, 1 },
510 while ((c = getopt_long_only(argc, argv, ":f:", longopts, NULL)) != -1)
515 /* Log filename was set */
516 strlcpy(LogFileName, optarg, MAXBUF);
519 /* Config filename was set */
520 strlcpy(ConfigFileName, optarg, MAXBUF);
523 /* getopt_long_only() set an int variable, just keep going */
526 /* Unknown parameter! DANGER, INTRUDER.... err.... yeah. */
527 printf("Usage: %s [--nofork] [--nolog] [--debug] [--logfile <filename>]\n\
528 [--runasroot] [--version] [--config <config>] [--testsuite]\n", argv[0]);
529 Exit(EXIT_STATUS_ARGV);
535 do_nofork = do_debug = true;
539 printf("\n%s r%s\n", VERSION, REVISION);
540 Exit(EXIT_STATUS_NOERROR);
548 DWORD ExitCode = WindowsForkStart(this);
555 WSAStartup(MAKEWORD(2,0), &wsadata);
556 ChangeWindowsSpecificPointers(this);
558 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
560 /* Set the finished argument values */
561 Config->nofork = do_nofork;
562 Config->forcedebug = do_debug;
563 Config->writelog = !do_nolog;
564 Config->TestSuite = do_testsuite;
566 if (!this->OpenLog(argv, argc))
568 printf("ERROR: Could not open logfile %s: %s\n\n", Config->logpath.c_str(), strerror(errno));
569 Exit(EXIT_STATUS_LOG);
572 if (!ServerConfig::FileExists(this->ConfigFileName))
574 printf("ERROR: Cannot open config file: %s\nExiting...\n", this->ConfigFileName);
575 this->Logs->Log("STARTUP",DEFAULT,"Unable to open config file %s", this->ConfigFileName);
576 Exit(EXIT_STATUS_CONFIG);
579 printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
580 printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
581 printf_c("Developers:\n");
582 printf_c("\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special\n");
583 printf_c("\t\033[1;32mpippijn, peavey, aquanight, fez\033[0m\n\n");
584 printf_c("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
586 Config->ClearStack();
588 this->Modes = new ModeParser(this);
594 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
595 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
596 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
597 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
598 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
599 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
600 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
601 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
609 if (!this->DaemonSeed())
611 printf("ERROR: could not go into daemon mode. Shutting down.\n");
612 Logs->Log("STARTUP", DEFAULT, "ERROR: could not go into daemon mode. Shutting down.");
613 Exit(EXIT_STATUS_FORK);
617 SE->RecoverFromFork();
619 /* During startup we don't actually initialize this
620 * in the thread engine.
622 this->ConfigThread = new ConfigReaderThread(this, true, NULL);
625 this->ConfigThread = NULL;
627 this->Res = new DNS(this);
629 this->AddServerName(Config->ServerName);
632 * Initialise SID/UID.
633 * For an explanation as to exactly how this works, and why it works this way, see GetUID().
641 for (const char* x = Config->ServerName; *x; ++x)
643 for (const char* y = Config->ServerDesc; *y; ++y)
647 Config->sid[0] = (char)(sid / 100 + 48);
648 Config->sid[1] = (char)(((sid / 10) % 10) + 48);
649 Config->sid[2] = (char)(sid % 10 + 48);
650 Config->sid[3] = '\0';
653 /* set up fake client again this time with the correct uid */
654 this->FakeClient = new User(this, "#INVALID");
655 this->FakeClient->SetFd(FD_MAGIC_NUMBER);
657 // Get XLine to do it's thing.
658 this->XLines->CheckELines();
659 this->XLines->ApplyLines();
662 int bounditems = BindPorts(true, found_ports, pl);
666 this->Modules->LoadAll();
668 /* Just in case no modules were loaded - fix for bug #101 */
669 this->BuildISupport();
670 InitializeDisabledCommands(Config->DisabledCommands, this);
672 /*if ((Config->ports.size() == 0) && (found_ports > 0))
674 printf("\nERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?\n");
675 Logs->Log("STARTUP", DEFAULT,"ERROR: I couldn't bind any ports! Something else is bound to those ports!");
676 Exit(EXIT_STATUS_BIND);
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.\tIP: %s\tPort: %lu\n", j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
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);
729 Logs->Log("STARTUP", DEFAULT, "Startup complete as '%s'[%s], %d max open sockets", Config->ServerName,Config->GetSID().c_str(), SE->GetMaxFds());
731 this->WritePID(Config->PID);
736 /* See if we're supposed to be running the test suite rather than entering the mainloop */
737 if (Config->TestSuite)
739 TestSuite* ts = new TestSuite(this);
749 static time_t uptime;
750 static struct tm * stime;
751 static char window_title[100];
754 /* Check if there is a config thread which has finished executing but has not yet been freed */
755 if (this->ConfigThread && this->ConfigThread->GetExitFlag())
757 /* Rehash has completed */
758 this->Logs->Log("CONFIG",DEBUG,"Detected ConfigThread exiting, tidying up...");
760 /* IMPORTANT: This delete may hang if you fuck up your thread syncronization.
761 * It will hang waiting for the ConfigThread to 'join' to avoid race conditons,
762 * until the other thread is completed.
767 /* These are currently not known to be threadsafe, so they are executed outside
768 * of the thread. It would be pretty simple to move them to the thread Run method
769 * once they are known threadsafe with all the correct mutexes in place.
771 * XXX: The order of these is IMPORTANT, do not reorder them without testing
774 this->XLines->CheckELines();
775 this->XLines->ApplyLines();
777 this->ResetMaxBans();
778 InitializeDisabledCommands(Config->DisabledCommands, this);
779 FOREACH_MOD_I(this, I_OnRehash, OnRehash(Config->RehashUser, Config->RehashParameter));
780 this->BuildISupport();
783 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
784 * Once per loop iteration is pleanty.
789 /* Run background module timers every few seconds
790 * (the docs say modules shouldnt rely on accurate
791 * timing using this event, so we dont have to
792 * time this exactly).
798 SNO->WriteToSnoMask('A', "\002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %lu secs.", (unsigned long)OLDTIME-TIME);
801 if ((TIME % 3600) == 0)
803 this->RehashUsersAndChans();
804 FOREACH_MOD_I(this, I_OnGarbageCollect, OnGarbageCollect());
807 Timers->TickTimers(TIME);
808 this->DoBackgroundUserStuff();
812 FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
813 SNO->FlushSnotices();
816 /* Same change as in cmd_stats.cpp, use RUSAGE_SELF rather than '0' -- Om */
817 if (!getrusage(RUSAGE_SELF, &ru))
819 gettimeofday(&this->stats->LastSampled, NULL);
820 this->stats->LastCPU = ru.ru_utime;
827 /* Call the socket engine to wait on the active
828 * file descriptors. The socket engine has everything's
829 * descriptors in its list... dns, modules, users,
830 * servers... so its nice and easy, just one call.
831 * This will cause any read or write events to be
832 * dispatched to their handlers.
834 this->SE->DispatchEvents();
836 /* if any users were quit, take them out */
837 this->GlobalCulls.Apply();
839 /* If any inspsockets closed, remove them */
840 this->BufferedSocketCull();
844 this->SignalHandler(s_signal);
852 void InspIRCd::BufferedSocketCull()
854 for (std::map<BufferedSocket*,BufferedSocket*>::iterator x = SocketCull.begin(); x != SocketCull.end(); ++x)
856 this->Logs->Log("MISC",DEBUG,"Cull socket");
857 SE->DelFd(x->second);
864 /**********************************************************************************/
867 * An ircd in five lines! bwahahaha. ahahahahaha. ahahah *cough*.
870 int main(int argc, char ** argv)
872 SI = new InspIRCd(argc, argv);
873 mysig = &SI->s_signal;
879 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
880 * (until this returns true, a user will block in the waiting state, waiting to connect up to the
881 * registration timeout maximum seconds)
883 bool InspIRCd::AllModulesReportReady(User* user)
885 for (EventHandlerIter i = Modules->EventHandlers[I_OnCheckReady].begin(); i != Modules->EventHandlers[I_OnCheckReady].end(); ++i)
887 if (!(*i)->OnCheckReady(user))
893 time_t InspIRCd::Time()
898 void InspIRCd::SetSignal(int signal)