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) */
22 #include <sys/resource.h>
26 /* Some systems don't define RUSAGE_SELF. This should fix them. */
35 #include "socketengine.h"
36 #include "inspircd_se_config.h"
38 #include "command_parse.h"
39 #include "exitcodes.h"
41 #include "testsuite.h"
43 using irc::sockets::insp_ntoa;
44 using irc::sockets::insp_inaddr;
45 using irc::sockets::insp_sockaddr;
51 /* Moved from exitcodes.h -- due to duplicate symbols -- Burlex
52 * XXX this is a bit ugly. -- w00t
54 const char* ExitCodes[] =
57 "DIE command", /* 1 */
58 "execv() failed", /* 2 */
59 "Internal error", /* 3 */
60 "Config file error", /* 4 */
61 "Logfile error", /* 5 */
62 "POSIX fork failed", /* 6 */
63 "Bad commandline parameters", /* 7 */
64 "No ports could be bound", /* 8 */
65 "Can't write PID file", /* 9 */
66 "SocketEngine could not initialize", /* 10 */
67 "Refusing to start up as root", /* 11 */
68 "Found a <die> tag!", /* 12 */
69 "Couldn't load module on startup", /* 13 */
70 "Could not create windows forked process", /* 14 */
71 "Received SIGTERM", /* 15 */
74 void InspIRCd::Cleanup()
78 for (unsigned int i = 0; i < Config->ports.size(); i++)
80 /* This calls the constructor and closes the listening socket */
81 delete Config->ports[i];
84 Config->ports.clear();
87 /* Close all client sockets, or the new process inherits them */
88 for (std::vector<User*>::const_iterator i = this->Users->local_users.begin(); i != this->Users->local_users.end(); i++)
90 (*i)->SetWriteError("Server shutdown");
94 /* We do this more than once, so that any service providers get a
95 * chance to be unhooked by the modules using them, but then get
96 * a chance to be removed themsleves.
98 * XXX there may be a better way to do this with 1.2
100 for (int tries = 0; tries < 3; tries++)
102 std::vector<std::string> module_names = Modules->GetAllModuleNames(0);
103 for (std::vector<std::string>::iterator k = module_names.begin(); k != module_names.end(); ++k)
105 /* Unload all modules, so they get a chance to clean up their listeners */
106 this->Modules->Unload(k->c_str());
111 this->Logs->CloseLogs();
113 /* Cleanup Server Names */
114 for(servernamelist::iterator itr = servernames.begin(); itr != servernames.end(); ++itr)
120 void InspIRCd::Restart(const std::string &reason)
122 /* SendError flushes each client's queue,
123 * regardless of writeability state
125 this->SendError(reason);
129 /* Figure out our filename (if theyve renamed it, we're boned) */
133 char module[MAX_PATH];
134 if (GetModuleFileName(NULL, module, MAX_PATH))
137 me = Config->MyDir + "/inspircd";
140 if (execv(me.c_str(), Config->argv) == -1)
142 /* Will raise a SIGABRT if not trapped */
143 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
147 void InspIRCd::ResetMaxBans()
149 for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
150 i->second->ResetMaxBans();
153 /** Because hash_map doesnt free its buckets when we delete items (this is a 'feature')
154 * we must occasionally rehash the hash (yes really).
155 * We do this by copying the entries from the old hash to a new hash, causing all
156 * empty buckets to be weeded out of the hash. We dont do this on a timer, as its
157 * very expensive, so instead we do it when the user types /REHASH and expects a
158 * short delay anyway.
160 void InspIRCd::RehashUsersAndChans()
162 user_hash* old_users = this->Users->clientlist;
163 user_hash* old_uuid = this->Users->uuidlist;
164 chan_hash* old_chans = this->chanlist;
166 this->Users->clientlist = new user_hash();
167 this->Users->uuidlist = new user_hash();
168 this->chanlist = new chan_hash();
170 for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
171 this->Users->clientlist->insert(*n);
175 for (user_hash::const_iterator n = old_uuid->begin(); n != old_uuid->end(); n++)
176 this->Users->uuidlist->insert(*n);
180 for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
181 this->chanlist->insert(*n);
186 void InspIRCd::SetSignals()
189 signal(SIGALRM, SIG_IGN);
190 signal(SIGHUP, InspIRCd::SetSignal);
191 signal(SIGPIPE, SIG_IGN);
192 signal(SIGCHLD, SIG_IGN);
194 signal(SIGTERM, InspIRCd::SetSignal);
197 void InspIRCd::QuickExit(int status)
202 bool InspIRCd::DaemonSeed()
205 printf_c("InspIRCd Process ID: \033[1;32m%lu\033[0m\n", GetCurrentProcessId());
208 signal(SIGTERM, InspIRCd::QuickExit);
211 if ((childpid = fork ()) < 0)
213 else if (childpid > 0)
215 /* We wait here for the child process to kill us,
216 * so that the shell prompt doesnt come back over
218 * Sending a kill with a signal of 0 just checks
219 * if the child pid is still around. If theyre not,
220 * they threw an error and we should give up.
222 while (kill(childpid, 0) != -1)
228 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
230 signal(SIGTERM, InspIRCd::SetSignal);
233 if (getrlimit(RLIMIT_CORE, &rl) == -1)
235 this->Logs->Log("STARTUP",DEFAULT,"Failed to getrlimit()!");
240 rl.rlim_cur = rl.rlim_max;
241 if (setrlimit(RLIMIT_CORE, &rl) == -1)
242 this->Logs->Log("STARTUP",DEFAULT,"setrlimit() failed, cannot increase coredump size.");
249 void InspIRCd::WritePID(const std::string &filename)
251 std::string fname = (filename.empty() ? "inspircd.pid" : filename);
252 if (*(fname.begin()) != '/')
254 std::string::size_type pos;
255 std::string confpath = this->ConfigFileName;
256 if ((pos = confpath.rfind("/")) != std::string::npos)
258 /* Leaves us with just the path */
259 fname = confpath.substr(0, pos) + std::string("/") + fname;
262 std::ofstream outfile(fname.c_str());
263 if (outfile.is_open())
270 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
271 this->Logs->Log("STARTUP",DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
272 Exit(EXIT_STATUS_PID);
276 InspIRCd::InspIRCd(int argc, char** argv)
279 /* Functor initialisation. Note that the ordering here is very important. */
280 HandleProcessUser(this),
283 HandleFindDescriptor(this),
284 HandleFloodQuitUser(this),
286 /* Functor pointer initialisation. Must match the order of the list above */
287 ProcessUser(&HandleProcessUser),
288 IsNick(&HandleIsNick),
289 IsIdent(&HandleIsIdent),
290 FindDescriptor(&HandleFindDescriptor),
291 FloodQuitUser(&HandleFloodQuitUser)
297 int do_version = 0, do_nofork = 0, do_debug = 0,
298 do_nolog = 0, do_root = 0, do_testsuite = 0; /* flag variables */
301 memset(&server, 0, sizeof(server));
302 memset(&client, 0, sizeof(client));
304 // This must be created first, so other parts of Insp can use it while starting up
305 this->Logs = new LogManager(this);
307 SocketEngineFactory* SEF = new SocketEngineFactory();
308 SE = SEF->Create(this);
312 ThreadEngineFactory* tef = new ThreadEngineFactory();
313 this->Threads = tef->Create(this);
318 // Create base manager classes early, so nothing breaks
319 this->Users = new UserManager(this);
321 this->Users->unregistered_count = 0;
323 this->Users->clientlist = new user_hash();
324 this->Users->uuidlist = new user_hash();
325 this->chanlist = new chan_hash();
329 this->Config = new ServerConfig(this);
330 this->SNO = new SnomaskManager(this);
331 this->BanCache = new BanCacheManager(this);
332 this->Modules = new ModuleManager(this);
333 this->stats = new serverstats();
334 this->Timers = new TimerManager(this);
335 this->Parser = new CommandParser(this);
336 this->XLines = new XLineManager(this);
338 this->Config->argv = argv;
339 this->Config->argc = argc;
341 if (chdir(Config->GetFullProgDir().c_str()))
343 printf("Unable to change to my directory: %s\nAborted.", strerror(errno));
347 this->Config->opertypes.clear();
348 this->Config->operclass.clear();
350 this->TIME = this->OLDTIME = this->startup_time = time(NULL);
353 *this->LogFileName = 0;
354 strlcpy(this->ConfigFileName, CONFIG_FILE, MAXBUF);
356 struct option longopts[] =
358 { "nofork", no_argument, &do_nofork, 1 },
359 { "logfile", required_argument, NULL, 'f' },
360 { "config", required_argument, NULL, 'c' },
361 { "debug", no_argument, &do_debug, 1 },
362 { "nolog", no_argument, &do_nolog, 1 },
363 { "runasroot", no_argument, &do_root, 1 },
364 { "version", no_argument, &do_version, 1 },
365 { "testsuite", no_argument, &do_testsuite, 1 },
369 while ((c = getopt_long_only(argc, argv, ":f:", longopts, NULL)) != -1)
374 /* Log filename was set */
375 strlcpy(LogFileName, optarg, MAXBUF);
378 /* Config filename was set */
379 strlcpy(ConfigFileName, optarg, MAXBUF);
382 /* getopt_long_only() set an int variable, just keep going */
385 /* Unknown parameter! DANGER, INTRUDER.... err.... yeah. */
386 printf("Usage: %s [--nofork] [--nolog] [--debug] [--logfile <filename>]\n\
387 [--runasroot] [--version] [--config <config>] [--testsuite]\n", argv[0]);
388 Exit(EXIT_STATUS_ARGV);
394 do_nofork = do_debug = true;
398 printf("\n%s r%s\n", VERSION, REVISION);
399 Exit(EXIT_STATUS_NOERROR);
407 DWORD ExitCode = WindowsForkStart(this);
414 WSAStartup(MAKEWORD(2,0), &wsadata);
415 ChangeWindowsSpecificPointers(this);
417 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
419 /* Set the finished argument values */
420 Config->nofork = do_nofork;
421 Config->forcedebug = do_debug;
422 Config->writelog = !do_nolog;
423 Config->TestSuite = do_testsuite;
425 if (!this->OpenLog(argv, argc))
427 printf("ERROR: Could not open logfile %s: %s\n\n", Config->logpath.c_str(), strerror(errno));
428 Exit(EXIT_STATUS_LOG);
431 if (!ServerConfig::FileExists(this->ConfigFileName))
433 printf("ERROR: Cannot open config file: %s\nExiting...\n", this->ConfigFileName);
434 this->Logs->Log("STARTUP",DEFAULT,"Unable to open config file %s", this->ConfigFileName);
435 Exit(EXIT_STATUS_CONFIG);
438 printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
439 printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
440 printf_c("Developers:\n");
441 printf_c("\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special\n");
442 printf_c("\t\033[1;32mpippijn, peavey, aquanight, fez\033[0m\n\n");
443 printf_c("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
445 Config->ClearStack();
447 this->Modes = new ModeParser(this);
449 /* set up fake client (uid is incorrect at this point,
450 * until after config is read. we set up the user again
453 this->FakeClient = new User(this);
454 this->FakeClient->SetFd(FD_MAGIC_NUMBER);
460 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
461 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
462 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
463 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
464 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
465 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
466 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
467 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
475 if (!this->DaemonSeed())
477 printf("ERROR: could not go into daemon mode. Shutting down.\n");
478 Logs->Log("STARTUP", DEFAULT, "ERROR: could not go into daemon mode. Shutting down.");
479 Exit(EXIT_STATUS_FORK);
483 SE->RecoverFromFork();
485 /* During startup we don't actually initialize this
486 * in the thread engine.
488 this->ConfigThread = new ConfigReaderThread(this);
491 this->ConfigThread = NULL;
493 this->AddServerName(Config->ServerName);
496 * Initialise SID/UID.
497 * 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 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
638 * Once per loop iteration is pleanty.
643 /* Run background module timers every few seconds
644 * (the docs say modules shouldnt rely on accurate
645 * timing using this event, so we dont have to
646 * time this exactly).
652 SNO->WriteToSnoMask('A', "\002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
655 if ((TIME % 3600) == 0)
657 this->RehashUsersAndChans();
658 FOREACH_MOD_I(this, I_OnGarbageCollect, OnGarbageCollect());
661 Timers->TickTimers(TIME);
662 this->DoBackgroundUserStuff();
666 FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
667 SNO->FlushSnotices();
670 /* Same change as in cmd_stats.cpp, use RUSAGE_SELF rather than '0' -- Om */
671 if (!getrusage(RUSAGE_SELF, &ru))
673 gettimeofday(&this->stats->LastSampled, NULL);
674 this->stats->LastCPU = ru.ru_utime;
681 /* Call the socket engine to wait on the active
682 * file descriptors. The socket engine has everything's
683 * descriptors in its list... dns, modules, users,
684 * servers... so its nice and easy, just one call.
685 * This will cause any read or write events to be
686 * dispatched to their handlers.
688 this->SE->DispatchEvents();
690 /* if any users were quit, take them out */
691 this->GlobalCulls.Apply();
693 /* If any inspsockets closed, remove them */
694 this->BufferedSocketCull();
698 this->SignalHandler(s_signal);
706 void InspIRCd::BufferedSocketCull()
708 for (std::map<BufferedSocket*,BufferedSocket*>::iterator x = SocketCull.begin(); x != SocketCull.end(); ++x)
710 this->Logs->Log("MISC",DEBUG,"Cull socket");
711 SE->DelFd(x->second);
718 /**********************************************************************************/
721 * An ircd in five lines! bwahahaha. ahahahahaha. ahahah *cough*.
724 int main(int argc, char ** argv)
726 SI = new InspIRCd(argc, argv);
727 mysig = &SI->s_signal;
733 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
734 * (until this returns true, a user will block in the waiting state, waiting to connect up to the
735 * registration timeout maximum seconds)
737 bool InspIRCd::AllModulesReportReady(User* user)
739 for (EventHandlerIter i = Modules->EventHandlers[I_OnCheckReady].begin(); i != Modules->EventHandlers[I_OnCheckReady].end(); ++i)
741 int res = (*i)->OnCheckReady(user);
749 time_t InspIRCd::Time()
754 void InspIRCd::SetSignal(int signal)