2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2012 William Pitcock <nenolod@dereferenced.org>
5 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
6 * Copyright (C) 2003-2008 Craig Edwards <craigedwards@brainbox.cc>
7 * Copyright (C) 2008 Uli Schlachter <psychon@znc.in>
8 * Copyright (C) 2006-2008 Robin Burchell <robin+git@viroteck.net>
9 * Copyright (C) 2006-2007 Oliver Lupton <oliverlupton@gmail.com>
10 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
11 * Copyright (C) 2007 Burlex <???@???>
12 * Copyright (C) 2003 Craig McLure <craig@chatspike.net>
13 * Copyright (C) 2003 randomdan <???@???>
15 * This file is part of InspIRCd. InspIRCd is free software: you can
16 * redistribute it and/or modify it under the terms of the GNU General Public
17 * License as published by the Free Software Foundation, version 2.
19 * This program is distributed in the hope that it will be useful, but WITHOUT
20 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
21 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
24 * You should have received a copy of the GNU General Public License
25 * along with this program. If not, see <http://www.gnu.org/licenses/>.
31 #include "inspircd_version.h"
37 #include <sys/resource.h>
41 /* Some systems don't define RUSAGE_SELF. This should fix them. */
46 #include <pwd.h> // setuid
47 #include <grp.h> // setgid
53 #include "socketengine.h"
55 #include "command_parse.h"
56 #include "exitcodes.h"
58 #include "testsuite.h"
60 InspIRCd* ServerInstance = NULL;
63 /** Seperate from the other casemap tables so that code *can* still exclusively rely on RFC casemapping
66 * This is provided as a pointer so that modules can change it to their custom mapping tables,
67 * e.g. for national character support.
69 unsigned const char *national_case_insensitive_map = rfc_case_insensitive_map;
72 /* Moved from exitcodes.h -- due to duplicate symbols -- Burlex
73 * XXX this is a bit ugly. -- w00t
75 const char* ExitCodes[] =
78 "DIE command", /* 1 */
79 "execv() failed", /* 2 */
80 "Internal error", /* 3 */
81 "Config file error", /* 4 */
82 "Logfile error", /* 5 */
83 "POSIX fork failed", /* 6 */
84 "Bad commandline parameters", /* 7 */
85 "No ports could be bound", /* 8 */
86 "Can't write PID file", /* 9 */
87 "SocketEngine could not initialize", /* 10 */
88 "Refusing to start up as root", /* 11 */
89 "Found a <die> tag!", /* 12 */
90 "Couldn't load module on startup", /* 13 */
91 "Could not create windows forked process", /* 14 */
92 "Received SIGTERM", /* 15 */
93 "Bad command handler loaded", /* 16 */
94 "RegisterServiceCtrlHandler failed", /* 17 */
95 "UpdateSCMStatus failed", /* 18 */
96 "CreateEvent failed" /* 19 */
99 template<typename T> static void DeleteZero(T*&n)
106 void InspIRCd::Cleanup()
108 for (unsigned int i = 0; i < ports.size(); i++)
110 /* This calls the constructor and closes the listening socket */
116 /* Close all client sockets, or the new process inherits them */
117 std::vector<LocalUser*>::reverse_iterator i = Users->local_users.rbegin();
118 while (i != this->Users->local_users.rend())
121 Users->QuitUser(u, "Server shutdown");
125 Modules->UnloadAll();
127 /* Delete objects dynamically allocated in constructor (destructor would be more appropriate, but we're likely exiting) */
128 /* 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) */
164 char** argv = Config->cmdline.argv;
167 char module[MAX_PATH];
168 if (GetModuleFileName(NULL, module, MAX_PATH))
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 doesn't free its buckets when we delete items, we occasionally
190 * recreate the hash to free them up.
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.
193 * Since this is quite expensive, it's not done very often.
195 void InspIRCd::RehashUsersAndChans()
197 user_hash* old_users = Users->clientlist;
198 Users->clientlist = new user_hash;
199 for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
200 Users->clientlist->insert(*n);
203 user_hash* old_uuid = Users->uuidlist;
204 Users->uuidlist = new user_hash;
205 for (user_hash::const_iterator n = old_uuid->begin(); n != old_uuid->end(); n++)
206 Users->uuidlist->insert(*n);
209 chan_hash* old_chans = chanlist;
210 chanlist = new chan_hash;
211 for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
212 chanlist->insert(*n);
215 // Reset the already_sent IDs so we don't wrap it around and drop a message
216 LocalUser::already_sent_id = 0;
217 for (std::vector<LocalUser*>::const_iterator i = Users->local_users.begin(); i != Users->local_users.end(); i++)
219 (**i).already_sent = 0;
220 (**i).RemoveExpiredInvites();
224 void InspIRCd::SetSignals()
227 signal(SIGALRM, SIG_IGN);
228 signal(SIGHUP, InspIRCd::SetSignal);
229 signal(SIGPIPE, SIG_IGN);
230 signal(SIGCHLD, SIG_IGN);
231 /* We want E2BIG not a signal! */
232 signal(SIGXFSZ, SIG_IGN);
234 signal(SIGTERM, InspIRCd::SetSignal);
237 void InspIRCd::QuickExit(int status)
242 bool InspIRCd::DaemonSeed()
245 printf_c("InspIRCd Process ID: \033[1;32m%lu\033[0m\n", GetCurrentProcessId());
248 signal(SIGTERM, InspIRCd::QuickExit);
251 if ((childpid = fork ()) < 0)
253 else if (childpid > 0)
255 /* We wait here for the child process to kill us,
256 * so that the shell prompt doesnt come back over
258 * Sending a kill with a signal of 0 just checks
259 * if the child pid is still around. If theyre not,
260 * they threw an error and we should give up.
262 while (kill(childpid, 0) != -1)
267 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
269 signal(SIGTERM, InspIRCd::SetSignal);
272 if (getrlimit(RLIMIT_CORE, &rl) == -1)
274 this->Logs->Log("STARTUP",DEFAULT,"Failed to getrlimit()!");
277 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.");
286 void InspIRCd::WritePID(const std::string &filename)
288 std::string fname(filename);
290 fname = DATA_PATH "/inspircd.pid";
291 std::ofstream outfile(fname.c_str());
292 if (outfile.is_open())
299 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
300 this->Logs->Log("STARTUP",DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
301 Exit(EXIT_STATUS_PID);
305 InspIRCd::InspIRCd(int argc, char** argv) :
306 ConfigFileName(CONFIG_PATH "/inspircd.conf"),
308 /* Functor pointer initialisation.
310 * THIS MUST MATCH THE ORDER OF DECLARATION OF THE FUNCTORS, e.g. the methods
311 * themselves within the class.
313 NICKForced("NICKForced", NULL),
314 OperQuit("OperQuit", NULL),
315 GenRandom(&HandleGenRandom),
316 IsChannel(&HandleIsChannel),
318 Rehash(&HandleRehash),
319 IsNick(&HandleIsNick),
320 IsIdent(&HandleIsIdent),
321 FloodQuitUser(&HandleFloodQuitUser),
322 OnCheckExemption(&HandleOnCheckExemption)
325 // Strict, frequent checking of memory on debug builds
326 _CrtSetDbgFlag ( _CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
328 // Avoid erroneous frees on early exit
332 ServerInstance = this;
334 Extensions.Register(&NICKForced);
335 Extensions.Register(&OperQuit);
338 int do_version = 0, do_nofork = 0, do_debug = 0,
339 do_nolog = 0, do_root = 0, do_testsuite = 0; /* flag variables */
342 // Initialize so that if we exit before proper initialization they're not deleted
358 this->ConfigThread = NULL;
361 this->startup_time = TIME.tv_sec;
363 // This must be created first, so other parts of Insp can use it while starting up
364 this->Logs = new LogManager;
366 SE = CreateSocketEngine();
368 this->Threads = new ThreadEngine;
370 /* Default implementation does nothing */
371 this->PI = new ProtocolInterface;
375 // Create base manager classes early, so nothing breaks
376 this->Users = new UserManager;
378 this->Users->unregistered_count = 0;
380 this->Users->clientlist = new user_hash();
381 this->Users->uuidlist = new user_hash();
382 this->chanlist = new chan_hash();
384 this->Config = new ServerConfig;
385 this->SNO = new SnomaskManager;
386 this->BanCache = new BanCacheManager;
387 this->Modules = new ModuleManager();
388 this->stats = new serverstats();
389 this->Timers = new TimerManager;
390 this->Parser = new CommandParser;
391 this->XLines = new XLineManager;
393 this->Config->cmdline.argv = argv;
394 this->Config->cmdline.argc = argc;
396 srandom(TIME.tv_nsec ^ TIME.tv_sec);
398 struct option longopts[] =
400 { "nofork", no_argument, &do_nofork, 1 },
401 { "logfile", required_argument, NULL, 'f' },
402 { "config", required_argument, NULL, 'c' },
403 { "debug", no_argument, &do_debug, 1 },
404 { "nolog", no_argument, &do_nolog, 1 },
405 { "runasroot", no_argument, &do_root, 1 },
406 { "version", no_argument, &do_version, 1 },
407 { "testsuite", no_argument, &do_testsuite, 1 },
412 while ((c = getopt_long(argc, argv, ":f:", longopts, &index)) != -1)
417 /* Log filename was set */
418 Config->cmdline.startup_log = optarg;
421 /* Config filename was set */
422 ConfigFileName = optarg;
425 /* getopt_long_only() set an int variable, just keep going */
428 /* Unknown parameter */
430 /* Fall through to handle other weird values too */
431 printf("Unknown parameter '%s'\n", argv[optind-1]);
432 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])), " ");
433 Exit(EXIT_STATUS_ARGV);
439 do_nofork = do_debug = true;
443 printf("\n%s r%s\n", VERSION, REVISION);
444 Exit(EXIT_STATUS_NOERROR);
452 DWORD ExitCode = WindowsForkStart();
459 WSAStartup(MAKEWORD(2,0), &wsadata);
460 ChangeWindowsSpecificPointers();
463 /* Set the finished argument values */
464 Config->cmdline.nofork = do_nofork;
465 Config->cmdline.forcedebug = do_debug;
466 Config->cmdline.writelog = !do_nolog;
467 Config->cmdline.TestSuite = do_testsuite;
471 FileWriter* fw = new FileWriter(stdout);
472 FileLogStream* fls = new FileLogStream(RAWIO, fw);
473 Logs->AddLogTypes("*", fls, true);
475 else if (!this->OpenLog(argv, argc))
477 printf("ERROR: Could not open initial logfile %s: %s\n\n", Config->cmdline.startup_log.c_str(), strerror(errno));
478 Exit(EXIT_STATUS_LOG);
481 if (!ServerConfig::FileExists(ConfigFileName.c_str()))
484 /* Windows can (and defaults to) hide file extensions, so let's play a bit nice for windows users. */
485 std::string txtconf = this->ConfigFileName;
486 txtconf.append(".txt");
488 if (ServerConfig::FileExists(txtconf.c_str()))
490 ConfigFileName = txtconf;
495 printf("ERROR: Cannot open config file: %s\nExiting...\n", ConfigFileName.c_str());
496 this->Logs->Log("STARTUP",DEFAULT,"Unable to open config file %s", ConfigFileName.c_str());
497 Exit(EXIT_STATUS_CONFIG);
501 printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
502 printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
503 printf_c("Developers:\n");
504 printf_c("\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special, peavey\n");
505 printf_c("\t\033[1;32maquanight, psychon, dz, danieldg, jackmcbarn\033[0m\n\n");
506 printf_c("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
508 this->Modes = new ModeParser;
514 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
515 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
516 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
517 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
518 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
519 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
520 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
521 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
527 if (!Config->cmdline.nofork)
529 if (!this->DaemonSeed())
531 printf("ERROR: could not go into daemon mode. Shutting down.\n");
532 Logs->Log("STARTUP", DEFAULT, "ERROR: could not go into daemon mode. Shutting down.");
533 Exit(EXIT_STATUS_FORK);
537 SE->RecoverFromFork();
539 /* During startup we don't actually initialize this
540 * in the thread engine.
542 this->Config->Read();
543 this->Config->Apply(NULL, "");
544 Logs->OpenFileLogs();
546 this->Res = new DNS();
549 * Initialise SID/UID.
550 * For an explanation as to exactly how this works, and why it works this way, see GetUID().
553 if (Config->sid.empty())
556 unsigned int sid = 0;
559 for (const char* x = Config->ServerName.c_str(); *x; ++x)
561 for (const char* y = Config->ServerDesc.c_str(); *y; ++y)
563 sprintf(sidstr, "%03d", sid % 1000);
565 Config->sid = sidstr;
568 /* set up fake client again this time with the correct uid */
569 this->FakeClient = new FakeUser(Config->sid, Config->ServerName);
571 // Get XLine to do it's thing.
572 this->XLines->CheckELines();
573 this->XLines->ApplyLines();
575 int bounditems = BindPorts(pl);
579 this->Modules->LoadAll();
581 /* Just in case no modules were loaded - fix for bug #101 */
582 this->BuildISupport();
583 Config->ApplyDisabledCommands(Config->DisabledCommands);
587 printf("\nWARNING: Not all your client ports could be bound --\nstarting anyway with %d of %d client ports bound.\n\n",
588 bounditems, bounditems + (int)pl.size());
589 printf("The following port(s) failed to bind:\n");
590 printf("Hint: Try using a public IP instead of blank or *\n\n");
592 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
594 printf("%d.\tAddress: %s\tReason: %s\n", j, i->first.empty() ? "<all>" : i->first.c_str(), i->second.c_str());
598 printf("\nInspIRCd is now running as '%s'[%s] with %d max open sockets\n",
599 Config->ServerName.c_str(),Config->GetSID().c_str(), SE->GetMaxFds());
602 if (!Config->cmdline.nofork)
604 if (kill(getppid(), SIGTERM) == -1)
606 printf("Error killing parent process: %s\n",strerror(errno));
607 Logs->Log("STARTUP", DEFAULT, "Error killing parent process: %s",strerror(errno));
611 /* Explicitly shut down stdio's stdin/stdout/stderr.
613 * The previous logic here was to only do this if stdio was connected to a controlling
614 * terminal. However, we must do this always to avoid information leaks and other
615 * problems related to stdio.
617 * The only exception is if we are in debug mode.
621 if ((!do_nofork) && (!do_testsuite) && (!Config->cmdline.forcedebug))
629 fd = open("/dev/null", O_RDWR);
631 Logs->Log("STARTUP", DEFAULT, "Failed to dup /dev/null to stdin.");
633 Logs->Log("STARTUP", DEFAULT, "Failed to dup /dev/null to stdout.");
635 Logs->Log("STARTUP", DEFAULT, "Failed to dup /dev/null to stderr.");
640 Logs->Log("STARTUP", DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
643 WindowsIPC = new IPC;
644 if(!Config->cmdline.nofork)
646 WindowsForkKillOwner();
649 /* Set win32 service as running, if we are running as a service */
653 Logs->Log("STARTUP", DEFAULT, "Startup complete as '%s'[%s], %d max open sockets", Config->ServerName.c_str(),Config->GetSID().c_str(), SE->GetMaxFds());
656 std::string SetUser = Config->ConfValue("security")->getString("runasuser");
657 std::string SetGroup = Config->ConfValue("security")->getString("runasgroup");
658 if (!SetGroup.empty())
663 ret = setgroups(0, NULL);
667 this->Logs->Log("SETGROUPS", DEFAULT, "setgroups() failed (wtf?): %s", strerror(errno));
675 g = getgrnam(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 (!SetUser.empty())
698 u = getpwnam(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);
719 void InspIRCd::UpdateTime()
721 #ifdef HAS_CLOCK_GETTIME
722 clock_gettime(CLOCK_REALTIME, &TIME);
725 gettimeofday(&tv, NULL);
726 TIME.tv_sec = tv.tv_sec;
727 TIME.tv_nsec = tv.tv_usec * 1000;
733 /* See if we're supposed to be running the test suite rather than entering the mainloop */
734 if (Config->cmdline.TestSuite)
736 TestSuite* ts = new TestSuite;
742 time_t OLDTIME = TIME.tv_sec;
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->IsDone())
757 /* Rehash has completed */
758 this->Logs->Log("CONFIG",DEBUG,"Detected ConfigThread exiting, tidying up...");
760 this->ConfigThread->Finish();
762 ConfigThread->join();
769 /* Run background module timers every few seconds
770 * (the docs say modules shouldnt rely on accurate
771 * timing using this event, so we dont have to
772 * time this exactly).
774 if (TIME.tv_sec != OLDTIME)
776 OLDTIME = TIME.tv_sec;
778 getrusage(RUSAGE_SELF, &ru);
779 stats->LastSampled = TIME;
780 stats->LastCPU = ru.ru_utime;
785 /* Allow a buffer of two seconds drift on this so that ntpdate etc dont harass admins */
786 if (TIME.tv_sec < OLDTIME - 2)
788 SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %lu secs.", (unsigned long)OLDTIME-TIME.tv_sec);
790 else if (TIME.tv_sec > OLDTIME + 2)
792 SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is jumping FORWARDS! Clock skipped %lu secs.", (unsigned long)TIME.tv_sec - OLDTIME);
795 if ((TIME.tv_sec % 3600) == 0)
797 this->RehashUsersAndChans();
798 FOREACH_MOD(I_OnGarbageCollect, OnGarbageCollect());
801 Timers->TickTimers(TIME.tv_sec);
802 this->DoBackgroundUserStuff();
804 if ((TIME.tv_sec % 5) == 0)
806 FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME.tv_sec));
807 SNO->FlushSnotices();
811 /* Call the socket engine to wait on the active
812 * file descriptors. The socket engine has everything's
813 * descriptors in its list... dns, modules, users,
814 * servers... so its nice and easy, just one call.
815 * This will cause any read or write events to be
816 * dispatched to their handlers.
818 this->SE->DispatchTrialWrites();
819 this->SE->DispatchEvents();
821 /* if any users were quit, take them out */
827 this->SignalHandler(s_signal);
835 /**********************************************************************************/
838 * An ircd in five lines! bwahahaha. ahahahahaha. ahahah *cough*.
841 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
842 * (until this returns true, a user will block in the waiting state, waiting to connect up to the
843 * registration timeout maximum seconds)
845 bool InspIRCd::AllModulesReportReady(LocalUser* user)
848 FIRST_MOD_RESULT(OnCheckReady, res, (user));
849 return (res == MOD_RES_PASSTHRU);
852 void InspIRCd::SetSignal(int signal)
857 /* On posix systems, the flow of the program starts right here, with
858 * ENTRYPOINT being a #define that defines main(). On Windows, ENTRYPOINT
859 * defines smain() and the real main() is in the service code under
860 * win32service.cpp. This allows the service control manager to control
861 * the process where we are running as a windows service.
865 new InspIRCd(argc, argv);
866 mysig = &ServerInstance->s_signal;
867 ServerInstance->Run();
868 delete ServerInstance;