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::NonBlocking;
45 using irc::sockets::Blocking;
46 using irc::sockets::insp_ntoa;
47 using irc::sockets::insp_inaddr;
48 using irc::sockets::insp_sockaddr;
54 /* Burlex: Moved from exitcodes.h -- due to duplicate symbols */
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()
77 std::vector<std::string> mymodnames;
78 int MyModCount = this->GetModuleCount();
82 for (unsigned int i = 0; i < Config->ports.size(); i++)
84 /* This calls the constructor and closes the listening socket */
85 delete Config->ports[i];
88 Config->ports.clear();
91 /* Close all client sockets, or the new process inherits them */
92 for (std::vector<userrec*>::const_iterator i = this->local_users.begin(); i != this->local_users.end(); i++)
94 (*i)->SetWriteError("Server shutdown");
98 /* We do this more than once, so that any service providers get a
99 * chance to be unhooked by the modules using them, but then get
100 * a chance to be removed themsleves.
102 for (int tries = 0; tries < 3; tries++)
104 MyModCount = this->GetModuleCount();
109 /* Unload all modules, so they get a chance to clean up their listeners */
110 for (int j = 0; j <= MyModCount; j++)
111 mymodnames.push_back(Config->module_names[j]);
113 for (int k = 0; k <= MyModCount; k++)
114 this->UnloadModule(mymodnames[k].c_str());
120 this->Logger->Close();
122 /* Cleanup Server Names */
123 for(servernamelist::iterator itr = servernames.begin(); itr != servernames.end(); ++itr)
132 void InspIRCd::Restart(const std::string &reason)
134 /* SendError flushes each client's queue,
135 * regardless of writeability state
137 this->SendError(reason);
141 /* Figure out our filename (if theyve renamed it, we're boned) */
145 char module[MAX_PATH];
146 if (GetModuleFileName(NULL, module, MAX_PATH))
149 me = Config->MyDir + "/inspircd";
152 if (execv(me.c_str(), Config->argv) == -1)
154 /* Will raise a SIGABRT if not trapped */
155 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
159 void InspIRCd::ResetMaxBans()
161 for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
162 i->second->ResetMaxBans();
165 /** Because hash_map doesnt free its buckets when we delete items (this is a 'feature')
166 * we must occasionally rehash the hash (yes really).
167 * We do this by copying the entries from the old hash to a new hash, causing all
168 * empty buckets to be weeded out of the hash. We dont do this on a timer, as its
169 * very expensive, so instead we do it when the user types /REHASH and expects a
170 * short delay anyway.
172 void InspIRCd::RehashUsersAndChans()
174 user_hash* old_users = this->clientlist;
175 chan_hash* old_chans = this->chanlist;
177 this->clientlist = new user_hash();
178 this->chanlist = new chan_hash();
180 for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
181 this->clientlist->insert(*n);
185 for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
186 this->chanlist->insert(*n);
191 void InspIRCd::CloseLog()
194 this->Logger->Close();
197 void InspIRCd::SetSignals()
200 signal(SIGALRM, SIG_IGN);
201 signal(SIGHUP, InspIRCd::SetSignal);
202 signal(SIGPIPE, SIG_IGN);
203 signal(SIGCHLD, SIG_IGN);
205 signal(SIGTERM, InspIRCd::SetSignal);
208 void InspIRCd::QuickExit(int status)
213 bool InspIRCd::DaemonSeed()
216 printf_c("InspIRCd Process ID: \033[1;32m%lu\033[0m\n", GetCurrentProcessId());
219 signal(SIGTERM, InspIRCd::QuickExit);
222 if ((childpid = fork ()) < 0)
224 else if (childpid > 0)
226 /* We wait here for the child process to kill us,
227 * so that the shell prompt doesnt come back over
229 * Sending a kill with a signal of 0 just checks
230 * if the child pid is still around. If theyre not,
231 * they threw an error and we should give up.
233 while (kill(childpid, 0) != -1)
239 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
241 signal(SIGTERM, InspIRCd::SetSignal);
244 if (getrlimit(RLIMIT_CORE, &rl) == -1)
246 this->Log(DEFAULT,"Failed to getrlimit()!");
251 rl.rlim_cur = rl.rlim_max;
252 if (setrlimit(RLIMIT_CORE, &rl) == -1)
253 this->Log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
260 void InspIRCd::WritePID(const std::string &filename)
262 std::string fname = (filename.empty() ? "inspircd.pid" : filename);
263 if (*(fname.begin()) != '/')
265 std::string::size_type pos;
266 std::string confpath = this->ConfigFileName;
267 if ((pos = confpath.rfind("/")) != std::string::npos)
269 /* Leaves us with just the path */
270 fname = confpath.substr(0, pos) + std::string("/") + fname;
273 std::ofstream outfile(fname.c_str());
274 if (outfile.is_open())
281 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
282 this->Log(DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
283 Exit(EXIT_STATUS_PID);
287 InspIRCd::InspIRCd(int argc, char** argv)
291 /* Functor initialisation. Note that the ordering here is very important. */
292 HandleProcessUser(this),
295 HandleFindDescriptor(this),
296 HandleFloodQuitUser(this),
298 /* Functor pointer initialisation. Must match the order of the list above */
299 ProcessUser(&HandleProcessUser),
300 IsNick(&HandleIsNick),
301 IsIdent(&HandleIsIdent),
302 FindDescriptor(&HandleFindDescriptor),
303 FloodQuitUser(&HandleFloodQuitUser)
309 int do_version = 0, do_nofork = 0, do_debug = 0, do_nolog = 0, do_root = 0; /* flag variables */
314 memset(&server, 0, sizeof(server));
315 memset(&client, 0, sizeof(client));
319 this->unregistered_count = 0;
321 this->clientlist = new user_hash();
322 this->chanlist = new chan_hash();
324 this->Config = new ServerConfig(this);
326 this->Config->argv = argv;
327 this->Config->argc = argc;
329 if (chdir(Config->GetFullProgDir().c_str()))
331 printf("Unable to change to my directory: %s\nAborted.", strerror(errno));
335 this->Config->opertypes.clear();
336 this->Config->operclass.clear();
337 this->SNO = new SnomaskManager(this);
338 this->TIME = this->OLDTIME = this->startup_time = time(NULL);
339 this->time_delta = 0;
340 this->next_call = this->TIME + 3;
343 *this->LogFileName = 0;
344 strlcpy(this->ConfigFileName, CONFIG_FILE, MAXBUF);
346 struct option longopts[] =
348 { "nofork", no_argument, &do_nofork, 1 },
349 { "logfile", required_argument, NULL, 'f' },
350 { "config", required_argument, NULL, 'c' },
351 { "debug", no_argument, &do_debug, 1 },
352 { "nolog", no_argument, &do_nolog, 1 },
353 { "runasroot", no_argument, &do_root, 1 },
354 { "version", no_argument, &do_version, 1 },
358 while ((c = getopt_long_only(argc, argv, ":f:", longopts, NULL)) != -1)
363 /* Log filename was set */
364 strlcpy(LogFileName, optarg, MAXBUF);
367 /* Config filename was set */
368 strlcpy(ConfigFileName, optarg, MAXBUF);
371 /* getopt_long_only() set an int variable, just keep going */
374 /* Unknown parameter! DANGER, INTRUDER.... err.... yeah. */
375 printf("Usage: %s [--nofork] [--nolog] [--debug] [--logfile <filename>] [--runasroot] [--version] [--config <config>]\n", argv[0]);
376 Exit(EXIT_STATUS_ARGV);
383 printf("\n%s r%s\n", VERSION, REVISION);
384 Exit(EXIT_STATUS_NOERROR);
392 DWORD ExitCode = WindowsForkStart(this);
399 WSAStartup(MAKEWORD(2,0), &wsadata);
401 ChangeWindowsSpecificPointers(this);
403 if (!ServerConfig::FileExists(this->ConfigFileName))
405 printf("ERROR: Cannot open config file: %s\nExiting...\n", this->ConfigFileName);
406 this->Log(DEFAULT,"Unable to open config file %s", this->ConfigFileName);
407 Exit(EXIT_STATUS_CONFIG);
410 printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
411 printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
412 printf_c("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special, pippijn, peavey, Burlex\033[0m\n");
413 printf_c("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
415 /* Set the finished argument values */
416 Config->nofork = do_nofork;
417 Config->forcedebug = do_debug;
418 Config->writelog = !do_nolog;
420 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
422 if (!this->OpenLog(argv, argc))
424 printf("ERROR: Could not open logfile %s: %s\n\n", Config->logpath.c_str(), strerror(errno));
425 Exit(EXIT_STATUS_LOG);
428 this->stats = new serverstats();
429 this->Timers = new TimerManager(this);
430 this->Parser = new CommandParser(this);
431 this->XLines = new XLineManager(this);
432 Config->ClearStack();
433 Config->Read(true, NULL);
439 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
440 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
441 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
442 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
443 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
444 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
445 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
446 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
454 if (!this->DaemonSeed())
456 printf("ERROR: could not go into daemon mode. Shutting down.\n");
457 Log(DEFAULT,"ERROR: could not go into daemon mode. Shutting down.");
458 Exit(EXIT_STATUS_FORK);
463 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
464 * initialize the socket engine.
466 SocketEngineFactory* SEF = new SocketEngineFactory();
467 SE = SEF->Create(this);
470 this->Modes = new ModeParser(this);
471 this->AddServerName(Config->ServerName);
473 int bounditems = BindPorts(true, found_ports, pl);
475 for(int t = 0; t < 255; t++)
476 Config->global_implementation[t] = 0;
478 memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
482 this->Res = new DNS(this);
484 this->LoadAllModules();
485 /* Just in case no modules were loaded - fix for bug #101 */
486 this->BuildISupport();
487 InitializeDisabledCommands(Config->DisabledCommands, this);
489 if ((Config->ports.size() == 0) && (found_ports > 0))
491 printf("\nERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?\n");
492 Log(DEFAULT,"ERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?");
493 Exit(EXIT_STATUS_BIND);
496 if (Config->ports.size() != (unsigned int)found_ports)
498 printf("\nWARNING: Not all your client ports could be bound --\nstarting anyway with %d of %d client ports bound.\n\n", bounditems, found_ports);
499 printf("The following port(s) failed to bind:\n");
501 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
503 printf("%d.\tIP: %s\tPort: %lu\n", j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
509 if (kill(getppid(), SIGTERM) == -1)
511 printf("Error killing parent process: %s\n",strerror(errno));
512 Log(DEFAULT,"Error killing parent process: %s",strerror(errno));
516 if (isatty(0) && isatty(1) && isatty(2))
518 /* We didn't start from a TTY, we must have started from a background process -
519 * e.g. we are restarting, or being launched by cron. Dont kill parent, and dont
530 Log(DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
534 WindowsIPC = new IPC(this);
537 WindowsForkKillOwner(this);
541 printf("\nInspIRCd is now running!\n");
542 Log(DEFAULT,"Startup complete.");
544 this->WritePID(Config->PID);
547 void InspIRCd::DoOneIteration(bool process_module_sockets)
552 static time_t uptime;
553 static struct tm * stime;
554 static char window_title[100];
557 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
558 * Once per loop iteration is pleanty.
563 /* Run background module timers every few seconds
564 * (the docs say modules shouldnt rely on accurate
565 * timing using this event, so we dont have to
566 * time this exactly).
571 WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
572 if ((TIME % 3600) == 0)
574 this->RehashUsersAndChans();
575 FOREACH_MOD_I(this, I_OnGarbageCollect, OnGarbageCollect());
577 Timers->TickTimers(TIME);
578 this->DoBackgroundUserStuff(TIME);
582 XLines->expire_lines();
583 FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
584 Timers->TickMissedTimers(TIME);
587 /* Same change as in cmd_stats.cpp, use RUSAGE_SELF rather than '0' -- Om */
588 if (!getrusage(RUSAGE_SELF, &ru))
590 gettimeofday(&this->stats->LastSampled, NULL);
591 this->stats->LastCPU = ru.ru_utime;
598 uptime = Time() - startup_time;
599 stime = gmtime(&uptime);
600 snprintf(window_title, 100, "InspIRCd - %u clients, %u accepted connections - Up %u days, %.2u:%.2u:%.2u",
601 LocalUserCount(), stats->statsAccept, stime->tm_yday, stime->tm_hour, stime->tm_min, stime->tm_sec);
602 SetConsoleTitle(window_title);
607 /* Call the socket engine to wait on the active
608 * file descriptors. The socket engine has everything's
609 * descriptors in its list... dns, modules, users,
610 * servers... so its nice and easy, just one call.
611 * This will cause any read or write events to be
612 * dispatched to their handlers.
614 this->SE->DispatchEvents();
616 /* if any users was quit, take them out */
617 this->GlobalCulls.Apply();
619 /* If any inspsockets closed, remove them */
620 this->InspSocketCull();
624 this->SignalHandler(s_signal);
630 void InspIRCd::InspSocketCull()
632 for (std::map<InspSocket*,InspSocket*>::iterator x = SocketCull.begin(); x != SocketCull.end(); ++x)
634 SE->DelFd(x->second);
645 DoOneIteration(true);
647 /* This is never reached -- we hope! */
651 /**********************************************************************************/
654 * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
657 int main(int argc, char** argv)
659 SI = new InspIRCd(argc, argv);
660 mysig = &SI->s_signal;
666 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
667 * (until this returns true, a user will block in the waiting state, waiting to connect up to the
668 * registration timeout maximum seconds)
670 bool InspIRCd::AllModulesReportReady(userrec* user)
672 if (!Config->global_implementation[I_OnCheckReady])
675 for (int i = 0; i <= this->GetModuleCount(); i++)
677 if (Config->implement_lists[i][I_OnCheckReady])
679 int res = modules[i]->OnCheckReady(user);
687 int InspIRCd::GetModuleCount()
689 return this->ModCount;
692 time_t InspIRCd::Time(bool delta)
695 return TIME + time_delta;
699 int InspIRCd::SetTimeDelta(int delta)
701 int old = time_delta;
703 this->Log(DEBUG, "Time delta set to %d (was %d)", time_delta, old);
707 void InspIRCd::AddLocalClone(userrec* user)
709 clonemap::iterator x = local_clones.find(user->GetIPString());
710 if (x != local_clones.end())
713 local_clones[user->GetIPString()] = 1;
716 void InspIRCd::AddGlobalClone(userrec* user)
718 clonemap::iterator y = global_clones.find(user->GetIPString());
719 if (y != global_clones.end())
722 global_clones[user->GetIPString()] = 1;
725 int InspIRCd::GetTimeDelta()
730 void InspIRCd::SetSignal(int signal)