1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 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 * ---------------------------------------------------
15 #include "configreader.h"
21 #include <sys/resource.h>
25 /* Some systems don't define RUSAGE_SELF. This should fix them. */
36 #include "socketengine.h"
37 #include "inspircd_se_config.h"
40 #include "command_parse.h"
41 #include "exitcodes.h"
44 using irc::sockets::insp_ntoa;
45 using irc::sockets::insp_inaddr;
46 using irc::sockets::insp_sockaddr;
52 /* Burlex: Moved from exitcodes.h -- due to duplicate symbols */
53 const char* ExitCodes[] =
56 "DIE command", /* 1 */
57 "execv() failed", /* 2 */
58 "Internal error", /* 3 */
59 "Config file error", /* 4 */
60 "Logfile error", /* 5 */
61 "POSIX fork failed", /* 6 */
62 "Bad commandline parameters", /* 7 */
63 "No ports could be bound", /* 8 */
64 "Can't write PID file", /* 9 */
65 "SocketEngine could not initialize", /* 10 */
66 "Refusing to start up as root", /* 11 */
67 "Found a <die> tag!", /* 12 */
68 "Couldn't load module on startup", /* 13 */
69 "Could not create windows forked process", /* 14 */
70 "Received SIGTERM", /* 15 */
73 void InspIRCd::Cleanup()
75 std::vector<std::string> mymodnames;
76 int MyModCount = this->GetModuleCount();
80 for (unsigned int i = 0; i < Config->ports.size(); i++)
82 /* This calls the constructor and closes the listening socket */
83 delete Config->ports[i];
86 Config->ports.clear();
89 /* Close all client sockets, or the new process inherits them */
90 for (std::vector<userrec*>::const_iterator i = this->local_users.begin(); i != this->local_users.end(); i++)
92 (*i)->SetWriteError("Server shutdown");
96 /* We do this more than once, so that any service providers get a
97 * chance to be unhooked by the modules using them, but then get
98 * a chance to be removed themsleves.
100 for (int tries = 0; tries < 3; tries++)
102 MyModCount = this->GetModuleCount();
107 /* Unload all modules, so they get a chance to clean up their listeners */
108 for (int j = 0; j <= MyModCount; j++)
109 mymodnames.push_back(Config->module_names[j]);
111 for (int k = 0; k <= MyModCount; k++)
112 this->UnloadModule(mymodnames[k].c_str());
118 this->Logger->Close();
120 /* Cleanup Server Names */
121 for(servernamelist::iterator itr = servernames.begin(); itr != servernames.end(); ++itr)
125 void InspIRCd::Restart(const std::string &reason)
127 /* SendError flushes each client's queue,
128 * regardless of writeability state
130 this->SendError(reason);
134 /* Figure out our filename (if theyve renamed it, we're boned) */
138 char module[MAX_PATH];
139 if (GetModuleFileName(NULL, module, MAX_PATH))
142 me = Config->MyDir + "/inspircd";
145 if (execv(me.c_str(), Config->argv) == -1)
147 /* Will raise a SIGABRT if not trapped */
148 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
152 void InspIRCd::ResetMaxBans()
154 for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
155 i->second->ResetMaxBans();
158 /** Because hash_map doesnt free its buckets when we delete items (this is a 'feature')
159 * we must occasionally rehash the hash (yes really).
160 * We do this by copying the entries from the old hash to a new hash, causing all
161 * empty buckets to be weeded out of the hash. We dont do this on a timer, as its
162 * very expensive, so instead we do it when the user types /REHASH and expects a
163 * short delay anyway.
165 void InspIRCd::RehashUsersAndChans()
167 user_hash* old_users = this->clientlist;
168 chan_hash* old_chans = this->chanlist;
170 this->clientlist = new user_hash();
171 this->chanlist = new chan_hash();
173 for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
174 this->clientlist->insert(*n);
178 for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
179 this->chanlist->insert(*n);
184 void InspIRCd::CloseLog()
187 this->Logger->Close();
190 void InspIRCd::SetSignals()
193 signal(SIGALRM, SIG_IGN);
194 signal(SIGHUP, InspIRCd::SetSignal);
195 signal(SIGPIPE, SIG_IGN);
196 signal(SIGCHLD, SIG_IGN);
198 signal(SIGTERM, InspIRCd::SetSignal);
201 void InspIRCd::QuickExit(int status)
206 bool InspIRCd::DaemonSeed()
209 printf_c("InspIRCd Process ID: \033[1;32m%lu\033[0m\n", GetCurrentProcessId());
212 signal(SIGTERM, InspIRCd::QuickExit);
215 if ((childpid = fork ()) < 0)
217 else if (childpid > 0)
219 /* We wait here for the child process to kill us,
220 * so that the shell prompt doesnt come back over
222 * Sending a kill with a signal of 0 just checks
223 * if the child pid is still around. If theyre not,
224 * they threw an error and we should give up.
226 while (kill(childpid, 0) != -1)
232 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
234 signal(SIGTERM, InspIRCd::SetSignal);
237 if (getrlimit(RLIMIT_CORE, &rl) == -1)
239 this->Log(DEFAULT,"Failed to getrlimit()!");
244 rl.rlim_cur = rl.rlim_max;
245 if (setrlimit(RLIMIT_CORE, &rl) == -1)
246 this->Log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
253 void InspIRCd::WritePID(const std::string &filename)
255 std::string fname = (filename.empty() ? "inspircd.pid" : filename);
256 if (*(fname.begin()) != '/')
258 std::string::size_type pos;
259 std::string confpath = this->ConfigFileName;
260 if ((pos = confpath.rfind("/")) != std::string::npos)
262 /* Leaves us with just the path */
263 fname = confpath.substr(0, pos) + std::string("/") + fname;
266 std::ofstream outfile(fname.c_str());
267 if (outfile.is_open())
274 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
275 this->Log(DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
276 Exit(EXIT_STATUS_PID);
280 InspIRCd::InspIRCd(int argc, char** argv)
284 /* Functor initialisation. Note that the ordering here is very important. */
285 HandleProcessUser(this),
288 HandleFindDescriptor(this),
289 HandleFloodQuitUser(this),
291 /* Functor pointer initialisation. Must match the order of the list above */
292 ProcessUser(&HandleProcessUser),
293 IsNick(&HandleIsNick),
294 IsIdent(&HandleIsIdent),
295 FindDescriptor(&HandleFindDescriptor),
296 FloodQuitUser(&HandleFloodQuitUser)
302 int do_version = 0, do_nofork = 0, do_debug = 0, do_nolog = 0, do_root = 0; /* flag variables */
307 memset(&server, 0, sizeof(server));
308 memset(&client, 0, sizeof(client));
310 SocketEngineFactory* SEF = new SocketEngineFactory();
311 SE = SEF->Create(this);
316 this->unregistered_count = 0;
318 this->clientlist = new user_hash();
319 this->chanlist = new chan_hash();
321 this->Config = new ServerConfig(this);
323 this->Config->argv = argv;
324 this->Config->argc = argc;
326 if (chdir(Config->GetFullProgDir().c_str()))
328 printf("Unable to change to my directory: %s\nAborted.", strerror(errno));
332 this->Config->opertypes.clear();
333 this->Config->operclass.clear();
334 this->SNO = new SnomaskManager(this);
335 this->TIME = this->OLDTIME = this->startup_time = time(NULL);
336 this->time_delta = 0;
337 this->next_call = this->TIME + 3;
340 *this->LogFileName = 0;
341 strlcpy(this->ConfigFileName, CONFIG_FILE, MAXBUF);
343 struct option longopts[] =
345 { "nofork", no_argument, &do_nofork, 1 },
346 { "logfile", required_argument, NULL, 'f' },
347 { "config", required_argument, NULL, 'c' },
348 { "debug", no_argument, &do_debug, 1 },
349 { "nolog", no_argument, &do_nolog, 1 },
350 { "runasroot", no_argument, &do_root, 1 },
351 { "version", no_argument, &do_version, 1 },
355 while ((c = getopt_long_only(argc, argv, ":f:", longopts, NULL)) != -1)
360 /* Log filename was set */
361 strlcpy(LogFileName, optarg, MAXBUF);
364 /* Config filename was set */
365 strlcpy(ConfigFileName, optarg, MAXBUF);
368 /* getopt_long_only() set an int variable, just keep going */
371 /* Unknown parameter! DANGER, INTRUDER.... err.... yeah. */
372 printf("Usage: %s [--nofork] [--nolog] [--debug] [--logfile <filename>] [--runasroot] [--version] [--config <config>]\n", argv[0]);
373 Exit(EXIT_STATUS_ARGV);
380 printf("\n%s r%s\n", VERSION, REVISION);
381 Exit(EXIT_STATUS_NOERROR);
389 DWORD ExitCode = WindowsForkStart(this);
396 WSAStartup(MAKEWORD(2,0), &wsadata);
398 ChangeWindowsSpecificPointers(this);
400 if (!ServerConfig::FileExists(this->ConfigFileName))
402 printf("ERROR: Cannot open config file: %s\nExiting...\n", this->ConfigFileName);
403 this->Log(DEFAULT,"Unable to open config file %s", this->ConfigFileName);
404 Exit(EXIT_STATUS_CONFIG);
407 printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
408 printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
409 printf_c("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special, pippijn, peavey, Burlex\033[0m\n");
410 printf_c("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
412 /* Set the finished argument values */
413 Config->nofork = do_nofork;
414 Config->forcedebug = do_debug;
415 Config->writelog = !do_nolog;
417 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
419 if (!this->OpenLog(argv, argc))
421 printf("ERROR: Could not open logfile %s: %s\n\n", Config->logpath.c_str(), strerror(errno));
422 Exit(EXIT_STATUS_LOG);
425 this->stats = new serverstats();
426 this->Timers = new TimerManager(this);
427 this->Parser = new CommandParser(this);
428 this->XLines = new XLineManager(this);
429 Config->ClearStack();
430 Config->Read(true, NULL);
436 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
437 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
438 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
439 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
440 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
441 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
442 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
443 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
451 if (!this->DaemonSeed())
453 printf("ERROR: could not go into daemon mode. Shutting down.\n");
454 Log(DEFAULT,"ERROR: could not go into daemon mode. Shutting down.");
455 Exit(EXIT_STATUS_FORK);
459 SE->RecoverFromFork();
461 this->Modes = new ModeParser(this);
462 this->AddServerName(Config->ServerName);
464 int bounditems = BindPorts(true, found_ports, pl);
466 for(int t = 0; t < 255; t++)
467 Config->global_implementation[t] = 0;
469 memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
473 this->Res = new DNS(this);
475 this->LoadAllModules();
476 /* Just in case no modules were loaded - fix for bug #101 */
477 this->BuildISupport();
478 InitializeDisabledCommands(Config->DisabledCommands, this);
480 if ((Config->ports.size() == 0) && (found_ports > 0))
482 printf("\nERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?\n");
483 Log(DEFAULT,"ERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?");
484 Exit(EXIT_STATUS_BIND);
487 if (Config->ports.size() != (unsigned int)found_ports)
489 printf("\nWARNING: Not all your client ports could be bound --\nstarting anyway with %d of %d client ports bound.\n\n", bounditems, found_ports);
490 printf("The following port(s) failed to bind:\n");
492 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
494 printf("%d.\tIP: %s\tPort: %lu\n", j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
500 if (kill(getppid(), SIGTERM) == -1)
502 printf("Error killing parent process: %s\n",strerror(errno));
503 Log(DEFAULT,"Error killing parent process: %s",strerror(errno));
507 if (isatty(0) && isatty(1) && isatty(2))
509 /* We didn't start from a TTY, we must have started from a background process -
510 * e.g. we are restarting, or being launched by cron. Dont kill parent, and dont
521 Log(DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
525 WindowsIPC = new IPC(this);
528 WindowsForkKillOwner(this);
535 * Initialise UID. XXX, we need to read SID from config, and use it instead of 000.
536 * For an explanation as to exactly how this works, and why it works this way, see GetUID().
541 for(i = 0; i < 3; i++)
542 current_uid[i] = '0';
544 for(i = 3; i < UUID_LENGTH - 1; i++)
545 current_uid[i] = 'A';
547 printf("\nInspIRCd is now running!\n");
548 Log(DEFAULT,"Startup complete.");
550 this->WritePID(Config->PID);
553 void InspIRCd::DoOneIteration(bool process_module_sockets)
558 static time_t uptime;
559 static struct tm * stime;
560 static char window_title[100];
563 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
564 * Once per loop iteration is pleanty.
569 /* Run background module timers every few seconds
570 * (the docs say modules shouldnt rely on accurate
571 * timing using this event, so we dont have to
572 * time this exactly).
577 WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
578 if ((TIME % 3600) == 0)
580 this->RehashUsersAndChans();
581 FOREACH_MOD_I(this, I_OnGarbageCollect, OnGarbageCollect());
583 Timers->TickTimers(TIME);
584 this->DoBackgroundUserStuff(TIME);
588 XLines->expire_lines();
589 FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
590 Timers->TickMissedTimers(TIME);
593 /* Same change as in cmd_stats.cpp, use RUSAGE_SELF rather than '0' -- Om */
594 if (!getrusage(RUSAGE_SELF, &ru))
596 gettimeofday(&this->stats->LastSampled, NULL);
597 this->stats->LastCPU = ru.ru_utime;
604 uptime = Time() - startup_time;
605 stime = gmtime(&uptime);
606 snprintf(window_title, 100, "InspIRCd - %u clients, %u accepted connections - Up %u days, %.2u:%.2u:%.2u",
607 LocalUserCount(), stats->statsAccept, stime->tm_yday, stime->tm_hour, stime->tm_min, stime->tm_sec);
608 SetConsoleTitle(window_title);
613 /* Call the socket engine to wait on the active
614 * file descriptors. The socket engine has everything's
615 * descriptors in its list... dns, modules, users,
616 * servers... so its nice and easy, just one call.
617 * This will cause any read or write events to be
618 * dispatched to their handlers.
620 this->SE->DispatchEvents();
622 /* if any users was quit, take them out */
623 this->GlobalCulls.Apply();
625 /* If any inspsockets closed, remove them */
626 this->InspSocketCull();
630 this->SignalHandler(s_signal);
636 void InspIRCd::InspSocketCull()
638 for (std::map<InspSocket*,InspSocket*>::iterator x = SocketCull.begin(); x != SocketCull.end(); ++x)
640 SE->DelFd(x->second);
651 DoOneIteration(true);
653 /* This is never reached -- we hope! */
657 /**********************************************************************************/
660 * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
663 int main(int argc, char** argv)
665 SI = new InspIRCd(argc, argv);
666 mysig = &SI->s_signal;
672 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
673 * (until this returns true, a user will block in the waiting state, waiting to connect up to the
674 * registration timeout maximum seconds)
676 bool InspIRCd::AllModulesReportReady(userrec* user)
678 if (!Config->global_implementation[I_OnCheckReady])
681 for (int i = 0; i <= this->GetModuleCount(); i++)
683 if (Config->implement_lists[i][I_OnCheckReady])
685 int res = modules[i]->OnCheckReady(user);
693 int InspIRCd::GetModuleCount()
695 return this->ModCount;
698 time_t InspIRCd::Time(bool delta)
701 return TIME + time_delta;
705 int InspIRCd::SetTimeDelta(int delta)
707 int old = time_delta;
709 this->Log(DEBUG, "Time delta set to %d (was %d)", time_delta, old);
713 void InspIRCd::AddLocalClone(userrec* user)
715 clonemap::iterator x = local_clones.find(user->GetIPString());
716 if (x != local_clones.end())
719 local_clones[user->GetIPString()] = 1;
722 void InspIRCd::AddGlobalClone(userrec* user)
724 clonemap::iterator y = global_clones.find(user->GetIPString());
725 if (y != global_clones.end())
728 global_clones[user->GetIPString()] = 1;
731 int InspIRCd::GetTimeDelta()
736 void InspIRCd::SetSignal(int signal)