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 * ---------------------------------------------------
15 /* $Install: src/inspircd $(BINPATH) */
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"
39 #include "inspircd_se_config.h"
41 #include "command_parse.h"
42 #include "exitcodes.h"
44 #include "testsuite.h"
49 /** Seperate from the other casemap tables so that code *can* still exclusively rely on RFC casemapping
52 * This is provided as a pointer so that modules can change it to their custom mapping tables,
53 * e.g. for national character support.
55 unsigned const char *national_case_insensitive_map = rfc_case_insensitive_map;
58 /* Moved from exitcodes.h -- due to duplicate symbols -- Burlex
59 * XXX this is a bit ugly. -- w00t
61 const char* ExitCodes[] =
64 "DIE command", /* 1 */
65 "execv() failed", /* 2 */
66 "Internal error", /* 3 */
67 "Config file error", /* 4 */
68 "Logfile error", /* 5 */
69 "POSIX fork failed", /* 6 */
70 "Bad commandline parameters", /* 7 */
71 "No ports could be bound", /* 8 */
72 "Can't write PID file", /* 9 */
73 "SocketEngine could not initialize", /* 10 */
74 "Refusing to start up as root", /* 11 */
75 "Found a <die> tag!", /* 12 */
76 "Couldn't load module on startup", /* 13 */
77 "Could not create windows forked process", /* 14 */
78 "Received SIGTERM", /* 15 */
79 "Bad command handler loaded", /* 16 */
80 "RegisterServiceCtrlHandler failed", /* 17 */
81 "UpdateSCMStatus failed", /* 18 */
82 "CreateEvent failed" /* 19 */
85 template<typename T> static void DeleteZero(T* n)
94 void InspIRCd::Cleanup()
98 for (unsigned int i = 0; i < ports.size(); i++)
100 /* This calls the constructor and closes the listening socket */
107 /* Close all client sockets, or the new process inherits them */
108 for (std::vector<User*>::const_iterator i = this->Users->local_users.begin(); i != this->Users->local_users.end(); i++)
110 this->Users->QuitUser((*i), "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 with 1.2
120 for (int tries = 0; tries < 3; 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());
129 /* Remove core commands */
130 Parser->RemoveCommands("<core>");
132 /* Cleanup Server Names */
133 for(servernamelist::iterator itr = servernames.begin(); itr != servernames.end(); ++itr)
136 /* Delete objects dynamically allocated in constructor (destructor would be more appropriate, but we're likely exiting) */
137 /* Must be deleted before modes as it decrements modelines */
138 DeleteZero(this->Users);
139 DeleteZero(this->Modes);
140 DeleteZero(this->XLines);
141 DeleteZero(this->Parser);
142 DeleteZero(this->stats);
143 DeleteZero(this->Modules);
144 DeleteZero(this->BanCache);
145 DeleteZero(this->SNO);
146 DeleteZero(this->Config);
147 DeleteZero(this->Res);
148 DeleteZero(this->chanlist);
149 DeleteZero(this->PI);
150 DeleteZero(this->Threads);
151 DeleteZero(this->Timers);
153 this->Logs->CloseLogs();
154 DeleteZero(this->Logs);
157 void InspIRCd::Restart(const std::string &reason)
159 /* SendError flushes each client's queue,
160 * regardless of writeability state
162 this->SendError(reason);
164 /* Figure out our filename (if theyve renamed it, we're boned) */
168 char module[MAX_PATH];
169 if (GetModuleFileName(NULL, module, MAX_PATH))
172 me = Config->MyDir + "/inspircd";
175 char** argv = Config->argv;
179 if (execv(me.c_str(), argv) == -1)
181 /* Will raise a SIGABRT if not trapped */
182 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
186 void InspIRCd::ResetMaxBans()
188 for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
189 i->second->ResetMaxBans();
192 /** Because hash_map doesnt free its buckets when we delete items (this is a 'feature')
193 * we must occasionally rehash the hash (yes really).
194 * We do this by copying the entries from the old hash to a new hash, causing all
195 * empty buckets to be weeded out of the hash. We dont do this on a timer, as its
196 * very expensive, so instead we do it when the user types /REHASH and expects a
197 * short delay anyway.
199 void InspIRCd::RehashUsersAndChans()
201 user_hash* old_users = this->Users->clientlist;
202 user_hash* old_uuid = this->Users->uuidlist;
203 chan_hash* old_chans = this->chanlist;
205 this->Users->clientlist = new user_hash();
206 this->Users->uuidlist = new user_hash();
207 this->chanlist = new chan_hash();
209 for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
210 this->Users->clientlist->insert(*n);
214 for (user_hash::const_iterator n = old_uuid->begin(); n != old_uuid->end(); n++)
215 this->Users->uuidlist->insert(*n);
219 for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
220 this->chanlist->insert(*n);
225 void InspIRCd::SetSignals()
228 signal(SIGALRM, SIG_IGN);
229 signal(SIGHUP, InspIRCd::SetSignal);
230 signal(SIGPIPE, SIG_IGN);
231 signal(SIGCHLD, SIG_IGN);
232 /* We want E2BIG not a signal! */
233 signal(SIGXFSZ, SIG_IGN);
235 signal(SIGTERM, InspIRCd::SetSignal);
238 void InspIRCd::QuickExit(int status)
243 bool InspIRCd::DaemonSeed()
246 printf_c("InspIRCd Process ID: \033[1;32m%lu\033[0m\n", GetCurrentProcessId());
249 signal(SIGTERM, InspIRCd::QuickExit);
252 if ((childpid = fork ()) < 0)
254 else if (childpid > 0)
256 /* We wait here for the child process to kill us,
257 * so that the shell prompt doesnt come back over
259 * Sending a kill with a signal of 0 just checks
260 * if the child pid is still around. If theyre not,
261 * they threw an error and we should give up.
263 while (kill(childpid, 0) != -1)
269 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
271 signal(SIGTERM, InspIRCd::SetSignal);
274 if (getrlimit(RLIMIT_CORE, &rl) == -1)
276 this->Logs->Log("STARTUP",DEFAULT,"Failed to getrlimit()!");
281 rl.rlim_cur = rl.rlim_max;
282 if (setrlimit(RLIMIT_CORE, &rl) == -1)
283 this->Logs->Log("STARTUP",DEFAULT,"setrlimit() failed, cannot increase coredump size.");
290 void InspIRCd::WritePID(const std::string &filename)
292 std::string fname = (filename.empty() ? "inspircd.pid" : filename);
293 std::replace(fname.begin(), fname.end(), '\\', '/');
294 if ((fname[0] != '/') && (!Config->StartsWithWindowsDriveLetter(filename)))
296 std::string::size_type pos;
297 std::string confpath = this->ConfigFileName;
298 if ((pos = confpath.rfind("/")) != std::string::npos)
300 /* Leaves us with just the path */
301 fname = confpath.substr(0, pos) + std::string("/") + fname;
304 std::ofstream outfile(fname.c_str());
305 if (outfile.is_open())
312 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
313 this->Logs->Log("STARTUP",DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
314 Exit(EXIT_STATUS_PID);
318 InspIRCd::InspIRCd(int argc, char** argv)
321 /* Functor initialisation. Note that the ordering here is very important.
323 * THIS MUST MATCH ORDER OF DECLARATION OF THE HandleWhateverFunc classes
324 * within class InspIRCd.
326 HandleProcessUser(this),
329 HandleFloodQuitUser(this),
330 HandleIsChannel(this),
334 /* Functor pointer initialisation. Must match the order of the list above
336 * THIS MUST MATCH THE ORDER OF DECLARATION OF THE FUNCTORS, e.g. the methods
337 * themselves within the class.
339 ProcessUser(&HandleProcessUser),
340 IsChannel(&HandleIsChannel),
342 Rehash(&HandleRehash),
343 IsNick(&HandleIsNick),
344 IsIdent(&HandleIsIdent),
345 FloodQuitUser(&HandleFloodQuitUser)
349 // Strict, frequent checking of memory on debug builds
350 _CrtSetDbgFlag ( _CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
352 // Avoid erroneous frees on early exit
357 int do_version = 0, do_nofork = 0, do_debug = 0,
358 do_nolog = 0, do_root = 0, do_testsuite = 0; /* flag variables */
361 // Initialize so that if we exit before proper initialization they're not deleted
379 this->TIME = time(NULL);
381 memset(&server, 0, sizeof(server));
382 memset(&client, 0, sizeof(client));
384 // This must be created first, so other parts of Insp can use it while starting up
385 this->Logs = new LogManager(this);
387 SocketEngineFactory* SEF = new SocketEngineFactory();
388 SE = SEF->Create(this);
391 this->Threads = new ThreadEngine(this);
393 /* Default implementation does nothing */
394 this->PI = new ProtocolInterface(this);
398 // Create base manager classes early, so nothing breaks
399 this->Users = new UserManager(this);
401 this->Users->unregistered_count = 0;
403 this->Users->clientlist = new user_hash();
404 this->Users->uuidlist = new user_hash();
405 this->chanlist = new chan_hash();
407 this->Config = new ServerConfig(this);
408 this->SNO = new SnomaskManager(this);
409 this->BanCache = new BanCacheManager(this);
410 this->Modules = new ModuleManager(this);
411 this->stats = new serverstats();
412 this->Timers = new TimerManager(this);
413 this->Parser = new CommandParser(this);
414 this->XLines = new XLineManager(this);
416 this->Config->argv = argv;
417 this->Config->argc = argc;
419 if (chdir(Config->GetFullProgDir().c_str()))
421 printf("Unable to change to my directory: %s\nAborted.", strerror(errno));
425 this->Config->opertypes.clear();
426 this->Config->operclass.clear();
428 this->TIME = this->OLDTIME = this->startup_time = time(NULL);
431 *this->LogFileName = 0;
432 strlcpy(this->ConfigFileName, CONFIG_FILE, MAXBUF);
434 struct option longopts[] =
436 { "nofork", no_argument, &do_nofork, 1 },
437 { "logfile", required_argument, NULL, 'f' },
438 { "config", required_argument, NULL, 'c' },
439 { "debug", no_argument, &do_debug, 1 },
440 { "nolog", no_argument, &do_nolog, 1 },
441 { "runasroot", no_argument, &do_root, 1 },
442 { "version", no_argument, &do_version, 1 },
443 { "testsuite", no_argument, &do_testsuite, 1 },
448 while ((c = getopt_long_only(argc, argv, ":f:", longopts, &index)) != -1)
453 /* Log filename was set */
454 strlcpy(LogFileName, optarg, MAXBUF);
457 /* Config filename was set */
458 strlcpy(ConfigFileName, optarg, MAXBUF);
461 /* getopt_long_only() set an int variable, just keep going */
464 /* Unknown parameter */
466 /* Fall through to handle other weird values too */
467 printf("Unknown parameter '%s'\n", argv[index]);
468 printf("Usage: %s [--nofork] [--nolog] [--debug] [--logfile <filename>]\n\
469 [--runasroot] [--version] [--config <config>] [--testsuite]\n", argv[0]);
470 Exit(EXIT_STATUS_ARGV);
476 do_nofork = do_debug = true;
480 printf("\n%s r%s\n", VERSION, REVISION);
481 Exit(EXIT_STATUS_NOERROR);
489 DWORD ExitCode = WindowsForkStart(this);
496 WSAStartup(MAKEWORD(2,0), &wsadata);
497 ChangeWindowsSpecificPointers(this);
499 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
501 /* Set the finished argument values */
502 Config->nofork = do_nofork;
503 Config->forcedebug = do_debug;
504 Config->writelog = !do_nolog;
505 Config->TestSuite = do_testsuite;
507 if (!this->OpenLog(argv, argc))
509 printf("ERROR: Could not open logfile %s: %s\n\n", Config->logpath.c_str(), strerror(errno));
510 Exit(EXIT_STATUS_LOG);
513 if (!ServerConfig::FileExists(this->ConfigFileName))
516 /* Windows can (and defaults to) hide file extensions, so let's play a bit nice for windows users. */
517 std::string txtconf = this->ConfigFileName;
518 txtconf.append(".txt");
520 if (ServerConfig::FileExists(txtconf.c_str()))
522 strlcat(this->ConfigFileName, ".txt", MAXBUF);
527 printf("ERROR: Cannot open config file: %s\nExiting...\n", this->ConfigFileName);
528 this->Logs->Log("STARTUP",DEFAULT,"Unable to open config file %s", this->ConfigFileName);
529 Exit(EXIT_STATUS_CONFIG);
533 printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
534 printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
535 printf_c("Developers:\n");
536 printf_c("\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special\n");
537 printf_c("\t\033[1;32mpeavey, aquanight, psychon, dz, danieldg\033[0m\n\n");
538 printf_c("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
540 Config->ClearStack();
542 this->Modes = new ModeParser(this);
548 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
549 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
550 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
551 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
552 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
553 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
554 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
555 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
563 if (!this->DaemonSeed())
565 printf("ERROR: could not go into daemon mode. Shutting down.\n");
566 Logs->Log("STARTUP", DEFAULT, "ERROR: could not go into daemon mode. Shutting down.");
567 Exit(EXIT_STATUS_FORK);
571 SE->RecoverFromFork();
573 /* During startup we don't actually initialize this
574 * in the thread engine.
576 this->ConfigThread = new ConfigReaderThread(this, true, "");
579 this->ConfigThread = NULL;
580 /* Switch over logfiles */
581 Logs->OpenFileLogs();
583 /** Note: This is safe, the method checks for user == NULL */
584 this->Parser->SetupCommandTable();
586 this->Res = new DNS(this);
588 this->AddServerName(Config->ServerName);
591 * Initialise SID/UID.
592 * For an explanation as to exactly how this works, and why it works this way, see GetUID().
600 for (const char* x = Config->ServerName; *x; ++x)
602 for (const char* y = Config->ServerDesc; *y; ++y)
606 Config->sid[0] = (char)(sid / 100 + 48);
607 Config->sid[1] = (char)(((sid / 10) % 10) + 48);
608 Config->sid[2] = (char)(sid % 10 + 48);
609 Config->sid[3] = '\0';
612 /* set up fake client again this time with the correct uid */
613 this->FakeClient = new FakeUser(this, "!");
614 this->FakeClient->SetFakeServer(Config->ServerName);
616 // Get XLine to do it's thing.
617 this->XLines->CheckELines();
618 this->XLines->ApplyLines();
621 int bounditems = BindPorts(true, found_ports, pl);
625 this->Modules->LoadAll();
627 /* Just in case no modules were loaded - fix for bug #101 */
628 this->BuildISupport();
629 InitializeDisabledCommands(Config->DisabledCommands, this);
631 if (ports.size() != (unsigned int)found_ports)
633 printf("\nWARNING: Not all your client ports could be bound --\nstarting anyway with %d of %d client ports bound.\n\n", bounditems, found_ports);
634 printf("The following port(s) failed to bind:\n");
635 printf("Hint: Try using a public IP instead of blank or *\n\n");
637 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
639 printf("%d.\tAddress: %s\tReason: %s\n", j, i->first.empty() ? "<all>" : i->first.c_str(), i->second.c_str());
643 printf("\nInspIRCd is now running as '%s'[%s] with %d max open sockets\n", Config->ServerName,Config->GetSID().c_str(), SE->GetMaxFds());
648 if (kill(getppid(), SIGTERM) == -1)
650 printf("Error killing parent process: %s\n",strerror(errno));
651 Logs->Log("STARTUP", DEFAULT, "Error killing parent process: %s",strerror(errno));
655 if (isatty(0) && isatty(1) && isatty(2))
657 /* We didn't start from a TTY, we must have started from a background process -
658 * e.g. we are restarting, or being launched by cron. Dont kill parent, and dont
661 if ((!do_nofork) && (!do_testsuite))
669 Logs->Log("STARTUP", DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
673 WindowsIPC = new IPC(this);
676 WindowsForkKillOwner(this);
679 /* Set win32 service as running, if we are running as a service */
683 Logs->Log("STARTUP", DEFAULT, "Startup complete as '%s'[%s], %d max open sockets", Config->ServerName,Config->GetSID().c_str(), SE->GetMaxFds());
686 if (*(this->Config->SetGroup))
691 ret = setgroups(0, NULL);
695 this->Logs->Log("SETGROUPS", DEFAULT, "setgroups() failed (wtf?): %s", strerror(errno));
703 g = getgrnam(this->Config->SetGroup);
707 this->Logs->Log("SETGUID", DEFAULT, "getgrnam() failed (bad user?): %s", strerror(errno));
711 ret = setgid(g->gr_gid);
715 this->Logs->Log("SETGUID", DEFAULT, "setgid() failed (bad user?): %s", strerror(errno));
720 if (*(this->Config->SetUser))
726 u = getpwnam(this->Config->SetUser);
730 this->Logs->Log("SETGUID", DEFAULT, "getpwnam() failed (bad user?): %s", strerror(errno));
734 int ret = setuid(u->pw_uid);
738 this->Logs->Log("SETGUID", DEFAULT, "setuid() failed (bad user?): %s", strerror(errno));
744 this->WritePID(Config->PID);
749 /* See if we're supposed to be running the test suite rather than entering the mainloop */
750 if (Config->TestSuite)
752 TestSuite* ts = new TestSuite(this);
762 static time_t uptime;
763 static struct tm * stime;
764 static char window_title[100];
767 /* Check if there is a config thread which has finished executing but has not yet been freed */
768 if (this->ConfigThread && this->ConfigThread->IsDone())
770 /* Rehash has completed */
772 /* Switch over logfiles */
774 Logs->OpenFileLogs();
776 this->Logs->Log("CONFIG",DEBUG,"Detected ConfigThread exiting, tidying up...");
779 * Apply the changed configuration from the rehash. This is not done within the
780 * configuration thread becasuse they may invoke functions that are not threadsafe.
782 * XXX: The order of these is IMPORTANT, do not reorder them without testing
785 this->XLines->CheckELines();
786 this->XLines->ApplyLines();
788 this->ResetMaxBans();
789 InitializeDisabledCommands(Config->DisabledCommands, this);
790 User* user = !Config->RehashUserUID.empty() ? FindNick(Config->RehashUserUID) : NULL;
791 FOREACH_MOD_I(this, I_OnRehash, OnRehash(user));
792 this->BuildISupport();
798 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
799 * Once per loop iteration is pleanty.
804 /* Run background module timers every few seconds
805 * (the docs say modules shouldnt rely on accurate
806 * timing using this event, so we dont have to
807 * time this exactly).
811 /* Allow a buffer of two seconds drift on this so that ntpdate etc dont harass admins */
812 if (TIME < OLDTIME - 2)
814 SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %lu secs.", (unsigned long)OLDTIME-TIME);
816 else if (TIME > OLDTIME + 2)
818 SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is jumping FORWARDS! Clock skipped %lu secs.", (unsigned long)TIME - OLDTIME);
821 if ((TIME % 3600) == 0)
823 this->RehashUsersAndChans();
824 FOREACH_MOD_I(this, I_OnGarbageCollect, OnGarbageCollect());
827 Timers->TickTimers(TIME);
828 this->DoBackgroundUserStuff();
832 FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
833 SNO->FlushSnotices();
836 /* Same change as in cmd_stats.cpp, use RUSAGE_SELF rather than '0' -- Om */
837 if (!getrusage(RUSAGE_SELF, &ru))
839 gettimeofday(&this->stats->LastSampled, NULL);
840 this->stats->LastCPU = ru.ru_utime;
847 /* Call the socket engine to wait on the active
848 * file descriptors. The socket engine has everything's
849 * descriptors in its list... dns, modules, users,
850 * servers... so its nice and easy, just one call.
851 * This will cause any read or write events to be
852 * dispatched to their handlers.
854 this->SE->DispatchEvents();
856 /* if any users were quit, take them out */
857 this->GlobalCulls.Apply();
859 /* If any inspsockets closed, remove them */
860 this->BufferedSocketCull();
864 this->SignalHandler(s_signal);
872 void InspIRCd::BufferedSocketCull()
874 for (std::map<BufferedSocket*,BufferedSocket*>::iterator x = SocketCull.begin(); x != SocketCull.end(); ++x)
876 this->Logs->Log("MISC",DEBUG,"Cull socket");
877 SE->DelFd(x->second);
884 /**********************************************************************************/
887 * An ircd in five lines! bwahahaha. ahahahahaha. ahahah *cough*.
890 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
891 * (until this returns true, a user will block in the waiting state, waiting to connect up to the
892 * registration timeout maximum seconds)
894 bool InspIRCd::AllModulesReportReady(User* user)
896 for (EventHandlerIter i = Modules->EventHandlers[I_OnCheckReady].begin(); i != Modules->EventHandlers[I_OnCheckReady].end(); ++i)
898 if (!(*i)->OnCheckReady(user))
904 time_t InspIRCd::Time()
909 void InspIRCd::SetSignal(int signal)
914 /* On posix systems, the flow of the program starts right here, with
915 * ENTRYPOINT being a #define that defines main(). On Windows, ENTRYPOINT
916 * defines smain() and the real main() is in the service code under
917 * win32service.cpp. This allows the service control manager to control
918 * the process where we are running as a windows service.
922 SI = new InspIRCd(argc, argv);
923 mysig = &SI->s_signal;