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) */
23 #include <sys/resource.h>
27 /* Some systems don't define RUSAGE_SELF. This should fix them. */
36 #include "socketengine.h"
37 #include "inspircd_se_config.h"
39 #include "command_parse.h"
40 #include "exitcodes.h"
42 #include "testsuite.h"
44 using irc::sockets::insp_ntoa;
45 using irc::sockets::insp_inaddr;
46 using irc::sockets::insp_sockaddr;
52 /* Moved from exitcodes.h -- due to duplicate symbols -- Burlex
53 * XXX this is a bit ugly. -- w00t
55 const char* ExitCodes[] =
58 "DIE command", /* 1 */
59 "execv() failed", /* 2 */
60 "Internal error", /* 3 */
61 "Config file error", /* 4 */
62 "Logfile error", /* 5 */
63 "POSIX fork failed", /* 6 */
64 "Bad commandline parameters", /* 7 */
65 "No ports could be bound", /* 8 */
66 "Can't write PID file", /* 9 */
67 "SocketEngine could not initialize", /* 10 */
68 "Refusing to start up as root", /* 11 */
69 "Found a <die> tag!", /* 12 */
70 "Couldn't load module on startup", /* 13 */
71 "Could not create windows forked process", /* 14 */
72 "Received SIGTERM", /* 15 */
75 void InspIRCd::Cleanup()
79 for (unsigned int i = 0; i < Config->ports.size(); i++)
81 /* This calls the constructor and closes the listening socket */
82 delete Config->ports[i];
85 Config->ports.clear();
88 /* Close all client sockets, or the new process inherits them */
89 for (std::vector<User*>::const_iterator i = this->Users->local_users.begin(); i != this->Users->local_users.end(); i++)
91 (*i)->SetWriteError("Server shutdown");
95 /* We do this more than once, so that any service providers get a
96 * chance to be unhooked by the modules using them, but then get
97 * a chance to be removed themsleves.
99 * XXX there may be a better way to do this with 1.2
101 for (int tries = 0; tries < 3; tries++)
103 std::vector<std::string> module_names = Modules->GetAllModuleNames(0);
104 for (std::vector<std::string>::iterator k = module_names.begin(); k != module_names.end(); ++k)
106 /* Unload all modules, so they get a chance to clean up their listeners */
107 this->Modules->Unload(k->c_str());
112 this->Logs->CloseLogs();
114 /* Cleanup Server Names */
115 for(servernamelist::iterator itr = servernames.begin(); itr != servernames.end(); ++itr)
121 void InspIRCd::Restart(const std::string &reason)
123 /* SendError flushes each client's queue,
124 * regardless of writeability state
126 this->SendError(reason);
130 /* Figure out our filename (if theyve renamed it, we're boned) */
134 char module[MAX_PATH];
135 if (GetModuleFileName(NULL, module, MAX_PATH))
138 me = Config->MyDir + "/inspircd";
141 if (execv(me.c_str(), Config->argv) == -1)
143 /* Will raise a SIGABRT if not trapped */
144 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
148 void InspIRCd::ResetMaxBans()
150 for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
151 i->second->ResetMaxBans();
154 /** Because hash_map doesnt free its buckets when we delete items (this is a 'feature')
155 * we must occasionally rehash the hash (yes really).
156 * We do this by copying the entries from the old hash to a new hash, causing all
157 * empty buckets to be weeded out of the hash. We dont do this on a timer, as its
158 * very expensive, so instead we do it when the user types /REHASH and expects a
159 * short delay anyway.
161 void InspIRCd::RehashUsersAndChans()
163 user_hash* old_users = this->Users->clientlist;
164 user_hash* old_uuid = this->Users->uuidlist;
165 chan_hash* old_chans = this->chanlist;
167 this->Users->clientlist = new user_hash();
168 this->Users->uuidlist = new user_hash();
169 this->chanlist = new chan_hash();
171 for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
172 this->Users->clientlist->insert(*n);
176 for (user_hash::const_iterator n = old_uuid->begin(); n != old_uuid->end(); n++)
177 this->Users->uuidlist->insert(*n);
181 for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
182 this->chanlist->insert(*n);
187 void InspIRCd::SetSignals()
190 signal(SIGALRM, SIG_IGN);
191 signal(SIGHUP, InspIRCd::SetSignal);
192 signal(SIGPIPE, SIG_IGN);
193 signal(SIGCHLD, SIG_IGN);
195 signal(SIGTERM, InspIRCd::SetSignal);
198 void InspIRCd::QuickExit(int status)
203 bool InspIRCd::DaemonSeed()
206 printf_c("InspIRCd Process ID: \033[1;32m%lu\033[0m\n", GetCurrentProcessId());
209 signal(SIGTERM, InspIRCd::QuickExit);
212 if ((childpid = fork ()) < 0)
214 else if (childpid > 0)
216 /* We wait here for the child process to kill us,
217 * so that the shell prompt doesnt come back over
219 * Sending a kill with a signal of 0 just checks
220 * if the child pid is still around. If theyre not,
221 * they threw an error and we should give up.
223 while (kill(childpid, 0) != -1)
229 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
231 signal(SIGTERM, InspIRCd::SetSignal);
234 if (getrlimit(RLIMIT_CORE, &rl) == -1)
236 this->Logs->Log("STARTUP",DEFAULT,"Failed to getrlimit()!");
241 rl.rlim_cur = rl.rlim_max;
242 if (setrlimit(RLIMIT_CORE, &rl) == -1)
243 this->Logs->Log("STARTUP",DEFAULT,"setrlimit() failed, cannot increase coredump size.");
250 void InspIRCd::WritePID(const std::string &filename)
252 std::string fname = (filename.empty() ? "inspircd.pid" : filename);
253 if (*(fname.begin()) != '/')
255 std::string::size_type pos;
256 std::string confpath = this->ConfigFileName;
257 if ((pos = confpath.rfind("/")) != std::string::npos)
259 /* Leaves us with just the path */
260 fname = confpath.substr(0, pos) + std::string("/") + fname;
263 std::ofstream outfile(fname.c_str());
264 if (outfile.is_open())
271 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
272 this->Logs->Log("STARTUP",DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
273 Exit(EXIT_STATUS_PID);
277 InspIRCd::InspIRCd(int argc, char** argv)
280 /* Functor initialisation. Note that the ordering here is very important. */
281 HandleProcessUser(this),
284 HandleFindDescriptor(this),
285 HandleFloodQuitUser(this),
287 /* Functor pointer initialisation. Must match the order of the list above */
288 ProcessUser(&HandleProcessUser),
289 IsNick(&HandleIsNick),
290 IsIdent(&HandleIsIdent),
291 FindDescriptor(&HandleFindDescriptor),
292 FloodQuitUser(&HandleFloodQuitUser)
298 int do_version = 0, do_nofork = 0, do_debug = 0,
299 do_nolog = 0, do_root = 0, do_testsuite = 0; /* flag variables */
302 memset(&server, 0, sizeof(server));
303 memset(&client, 0, sizeof(client));
305 // This must be created first, so other parts of Insp can use it while starting up
306 this->Logs = new LogManager(this);
308 SocketEngineFactory* SEF = new SocketEngineFactory();
309 SE = SEF->Create(this);
313 ThreadEngineFactory* tef = new ThreadEngineFactory();
314 this->Threads = tef->Create(this);
319 // Create base manager classes early, so nothing breaks
320 this->Users = new UserManager(this);
322 this->Users->unregistered_count = 0;
324 this->Users->clientlist = new user_hash();
325 this->Users->uuidlist = new user_hash();
326 this->chanlist = new chan_hash();
330 this->Config = new ServerConfig(this);
331 this->SNO = new SnomaskManager(this);
332 this->BanCache = new BanCacheManager(this);
333 this->Modules = new ModuleManager(this);
334 this->stats = new serverstats();
335 this->Timers = new TimerManager(this);
336 this->Parser = new CommandParser(this);
337 this->XLines = new XLineManager(this);
339 this->Config->argv = argv;
340 this->Config->argc = argc;
342 if (chdir(Config->GetFullProgDir().c_str()))
344 printf("Unable to change to my directory: %s\nAborted.", strerror(errno));
348 this->Config->opertypes.clear();
349 this->Config->operclass.clear();
351 this->TIME = this->OLDTIME = this->startup_time = time(NULL);
354 *this->LogFileName = 0;
355 strlcpy(this->ConfigFileName, CONFIG_FILE, MAXBUF);
357 struct option longopts[] =
359 { "nofork", no_argument, &do_nofork, 1 },
360 { "logfile", required_argument, NULL, 'f' },
361 { "config", required_argument, NULL, 'c' },
362 { "debug", no_argument, &do_debug, 1 },
363 { "nolog", no_argument, &do_nolog, 1 },
364 { "runasroot", no_argument, &do_root, 1 },
365 { "version", no_argument, &do_version, 1 },
366 { "testsuite", no_argument, &do_testsuite, 1 },
370 while ((c = getopt_long_only(argc, argv, ":f:", longopts, NULL)) != -1)
375 /* Log filename was set */
376 strlcpy(LogFileName, optarg, MAXBUF);
379 /* Config filename was set */
380 strlcpy(ConfigFileName, optarg, MAXBUF);
383 /* getopt_long_only() set an int variable, just keep going */
386 /* Unknown parameter! DANGER, INTRUDER.... err.... yeah. */
387 printf("Usage: %s [--nofork] [--nolog] [--debug] [--logfile <filename>]\n\
388 [--runasroot] [--version] [--config <config>] [--testsuite]\n", argv[0]);
389 Exit(EXIT_STATUS_ARGV);
395 do_nofork = do_debug = true;
399 printf("\n%s r%s\n", VERSION, REVISION);
400 Exit(EXIT_STATUS_NOERROR);
408 DWORD ExitCode = WindowsForkStart(this);
415 WSAStartup(MAKEWORD(2,0), &wsadata);
416 ChangeWindowsSpecificPointers(this);
418 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
420 /* Set the finished argument values */
421 Config->nofork = do_nofork;
422 Config->forcedebug = do_debug;
423 Config->writelog = !do_nolog;
424 Config->TestSuite = do_testsuite;
426 if (!this->OpenLog(argv, argc))
428 printf("ERROR: Could not open logfile %s: %s\n\n", Config->logpath.c_str(), strerror(errno));
429 Exit(EXIT_STATUS_LOG);
432 if (!ServerConfig::FileExists(this->ConfigFileName))
434 printf("ERROR: Cannot open config file: %s\nExiting...\n", this->ConfigFileName);
435 this->Logs->Log("STARTUP",DEFAULT,"Unable to open config file %s", this->ConfigFileName);
436 Exit(EXIT_STATUS_CONFIG);
439 printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
440 printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
441 printf_c("Developers:\n");
442 printf_c("\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special\n");
443 printf_c("\t\033[1;32mpippijn, peavey, aquanight, fez\033[0m\n\n");
444 printf_c("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
446 Config->ClearStack();
448 this->Modes = new ModeParser(this);
450 /* set up fake client (uid is incorrect at this point,
451 * until after config is read. we set up the user again
454 this->FakeClient = new User(this);
455 this->FakeClient->SetFd(FD_MAGIC_NUMBER);
461 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
462 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
463 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
464 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
465 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
466 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
467 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
468 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
476 if (!this->DaemonSeed())
478 printf("ERROR: could not go into daemon mode. Shutting down.\n");
479 Logs->Log("STARTUP", DEFAULT, "ERROR: could not go into daemon mode. Shutting down.");
480 Exit(EXIT_STATUS_FORK);
484 SE->RecoverFromFork();
486 /* During startup we don't actually initialize this
487 * in the thread engine.
489 this->ConfigThread = new ConfigReaderThread(this, true, NULL);
492 this->ConfigThread = NULL;
494 this->Res = new DNS(this);
496 this->AddServerName(Config->ServerName);
499 * Initialise SID/UID.
500 * For an explanation as to exactly how this works, and why it works this way, see GetUID().
508 for (const char* x = Config->ServerName; *x; ++x)
510 for (const char* y = Config->ServerDesc; *y; ++y)
514 Config->sid[0] = (char)(sid / 100 + 48);
515 Config->sid[1] = (char)(((sid / 10) % 10) + 48);
516 Config->sid[2] = (char)(sid % 10 + 48);
519 this->InitialiseUID();
521 /* set up fake client again this time with the correct uid */
523 this->FakeClient = new User(this);
524 this->FakeClient->SetFd(FD_MAGIC_NUMBER);
526 // Get XLine to do it's thing.
527 this->XLines->CheckELines();
528 this->XLines->ApplyLines();
532 int bounditems = BindPorts(true, found_ports, pl);
536 this->Modules->LoadAll();
538 /* Just in case no modules were loaded - fix for bug #101 */
539 this->BuildISupport();
540 InitializeDisabledCommands(Config->DisabledCommands, this);
542 /*if ((Config->ports.size() == 0) && (found_ports > 0))
544 printf("\nERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?\n");
545 Logs->Log("STARTUP", DEFAULT,"ERROR: I couldn't bind any ports! Something else is bound to those ports!");
546 Exit(EXIT_STATUS_BIND);
549 if (Config->ports.size() != (unsigned int)found_ports)
551 printf("\nWARNING: Not all your client ports could be bound --\nstarting anyway with %d of %d client ports bound.\n\n", bounditems, found_ports);
552 printf("The following port(s) failed to bind:\n");
554 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
556 printf("%d.\tIP: %s\tPort: %lu\n", j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
562 if (kill(getppid(), SIGTERM) == -1)
564 printf("Error killing parent process: %s\n",strerror(errno));
565 Logs->Log("STARTUP", DEFAULT, "Error killing parent process: %s",strerror(errno));
569 if (isatty(0) && isatty(1) && isatty(2))
571 /* We didn't start from a TTY, we must have started from a background process -
572 * e.g. we are restarting, or being launched by cron. Dont kill parent, and dont
583 Logs->Log("STARTUP", DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
587 WindowsIPC = new IPC(this);
590 WindowsForkKillOwner(this);
595 printf("\nInspIRCd is now running as '%s'[%s]\n", Config->ServerName,Config->GetSID().c_str());
596 Logs->Log("STARTUP", DEFAULT, "Startup complete as '%s'[%s]", Config->ServerName,Config->GetSID().c_str());
598 this->WritePID(Config->PID);
601 /* moved to a function, as UID generation can call this also */
602 void InspIRCd::InitialiseUID()
606 current_uid[0] = Config->sid[0];
607 current_uid[1] = Config->sid[1];
608 current_uid[2] = Config->sid[2];
611 for(i = 3; i < UUID_LENGTH - 1; i++)
612 current_uid[i] = 'A';
614 current_uid[UUID_LENGTH] = '\0';
619 /* See if we're supposed to be running the test suite rather than entering the mainloop */
620 if (Config->TestSuite)
622 TestSuite* ts = new TestSuite(this);
632 static time_t uptime;
633 static struct tm * stime;
634 static char window_title[100];
637 /* Check if there is a config thread which has finished executing but has not yet been freed */
638 if (this->ConfigThread && this->ConfigThread->GetExitFlag())
640 /* Rehash has completed */
641 this->Logs->Log("CONFIG",DEBUG,"Detected ConfigThread exiting, tidying up...");
643 /* IMPORTANT: This delete may hang if you fuck up your thread syncronization.
644 * It will hang waiting for the ConfigThread to 'join' to avoid race conditons,
645 * until the other thread is completed.
650 /* These are currently not known to be threadsafe, so they are executed outside
651 * of the thread. It would be pretty simple to move them to the thread Run method
652 * once they are known threadsafe with all the correct mutexes in place.
654 * XXX: The order of these is IMPORTANT, do not reorder them without testing
657 this->XLines->CheckELines();
658 this->XLines->ApplyLines();
660 this->ResetMaxBans();
661 InitializeDisabledCommands(Config->DisabledCommands, this);
662 FOREACH_MOD_I(this, I_OnRehash, OnRehash(Config->RehashUser, Config->RehashParameter));
663 this->BuildISupport();
666 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
667 * Once per loop iteration is pleanty.
672 /* Run background module timers every few seconds
673 * (the docs say modules shouldnt rely on accurate
674 * timing using this event, so we dont have to
675 * time this exactly).
681 SNO->WriteToSnoMask('A', "\002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %ld secs.",OLDTIME-TIME);
684 if ((TIME % 3600) == 0)
686 this->RehashUsersAndChans();
687 FOREACH_MOD_I(this, I_OnGarbageCollect, OnGarbageCollect());
690 Timers->TickTimers(TIME);
691 this->DoBackgroundUserStuff();
695 FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
696 SNO->FlushSnotices();
699 /* Same change as in cmd_stats.cpp, use RUSAGE_SELF rather than '0' -- Om */
700 if (!getrusage(RUSAGE_SELF, &ru))
702 gettimeofday(&this->stats->LastSampled, NULL);
703 this->stats->LastCPU = ru.ru_utime;
710 /* Call the socket engine to wait on the active
711 * file descriptors. The socket engine has everything's
712 * descriptors in its list... dns, modules, users,
713 * servers... so its nice and easy, just one call.
714 * This will cause any read or write events to be
715 * dispatched to their handlers.
717 this->SE->DispatchEvents();
719 /* if any users were quit, take them out */
720 this->GlobalCulls.Apply();
722 /* If any inspsockets closed, remove them */
723 this->BufferedSocketCull();
727 this->SignalHandler(s_signal);
735 void InspIRCd::BufferedSocketCull()
737 for (std::map<BufferedSocket*,BufferedSocket*>::iterator x = SocketCull.begin(); x != SocketCull.end(); ++x)
739 this->Logs->Log("MISC",DEBUG,"Cull socket");
740 SE->DelFd(x->second);
747 /**********************************************************************************/
750 * An ircd in five lines! bwahahaha. ahahahahaha. ahahah *cough*.
753 int main(int argc, char ** argv)
755 SI = new InspIRCd(argc, argv);
756 mysig = &SI->s_signal;
762 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
763 * (until this returns true, a user will block in the waiting state, waiting to connect up to the
764 * registration timeout maximum seconds)
766 bool InspIRCd::AllModulesReportReady(User* user)
768 for (EventHandlerIter i = Modules->EventHandlers[I_OnCheckReady].begin(); i != Modules->EventHandlers[I_OnCheckReady].end(); ++i)
770 if (!(*i)->OnCheckReady(user))
776 time_t InspIRCd::Time()
781 void InspIRCd::SetSignal(int signal)