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 * ---------------------------------------------------
14 /* $Install: src/inspircd $(BINPATH) */
22 #include <sys/resource.h>
26 /* Some systems don't define RUSAGE_SELF. This should fix them. */
34 #include "socketengine.h"
35 #include "inspircd_se_config.h"
37 #include "command_parse.h"
38 #include "exitcodes.h"
41 using irc::sockets::insp_ntoa;
42 using irc::sockets::insp_inaddr;
43 using irc::sockets::insp_sockaddr;
49 /* Burlex: Moved from exitcodes.h -- due to duplicate symbols */
50 const char* ExitCodes[] =
53 "DIE command", /* 1 */
54 "execv() failed", /* 2 */
55 "Internal error", /* 3 */
56 "Config file error", /* 4 */
57 "Logfile error", /* 5 */
58 "POSIX fork failed", /* 6 */
59 "Bad commandline parameters", /* 7 */
60 "No ports could be bound", /* 8 */
61 "Can't write PID file", /* 9 */
62 "SocketEngine could not initialize", /* 10 */
63 "Refusing to start up as root", /* 11 */
64 "Found a <die> tag!", /* 12 */
65 "Couldn't load module on startup", /* 13 */
66 "Could not create windows forked process", /* 14 */
67 "Received SIGTERM", /* 15 */
70 void InspIRCd::Cleanup()
72 std::vector<std::string> mymodnames;
73 int MyModCount = this->Modules->GetCount();
77 for (unsigned int i = 0; i < Config->ports.size(); i++)
79 /* This calls the constructor and closes the listening socket */
80 delete Config->ports[i];
83 Config->ports.clear();
86 /* Close all client sockets, or the new process inherits them */
87 for (std::vector<User*>::const_iterator i = this->local_users.begin(); i != this->local_users.end(); i++)
89 (*i)->SetWriteError("Server shutdown");
93 /* We do this more than once, so that any service providers get a
94 * chance to be unhooked by the modules using them, but then get
95 * a chance to be removed themsleves.
97 for (int tries = 0; tries < 3; tries++)
99 MyModCount = this->Modules->GetCount();
104 /* Unload all modules, so they get a chance to clean up their listeners */
105 for (int j = 0; j <= MyModCount; j++)
106 mymodnames.push_back(Config->module_names[j]);
108 for (int k = 0; k <= MyModCount; k++)
109 this->Modules->Unload(mymodnames[k].c_str());
116 this->Logger->Close();
119 /* Cleanup Server Names */
120 for(servernamelist::iterator itr = servernames.begin(); itr != servernames.end(); ++itr)
126 void InspIRCd::Restart(const std::string &reason)
128 /* SendError flushes each client's queue,
129 * regardless of writeability state
131 this->SendError(reason);
135 /* Figure out our filename (if theyve renamed it, we're boned) */
139 char module[MAX_PATH];
140 if (GetModuleFileName(NULL, module, MAX_PATH))
143 me = Config->MyDir + "/inspircd";
146 if (execv(me.c_str(), Config->argv) == -1)
148 /* Will raise a SIGABRT if not trapped */
149 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
153 void InspIRCd::ResetMaxBans()
155 for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
156 i->second->ResetMaxBans();
159 /** Because hash_map doesnt free its buckets when we delete items (this is a 'feature')
160 * we must occasionally rehash the hash (yes really).
161 * We do this by copying the entries from the old hash to a new hash, causing all
162 * empty buckets to be weeded out of the hash. We dont do this on a timer, as its
163 * very expensive, so instead we do it when the user types /REHASH and expects a
164 * short delay anyway.
166 void InspIRCd::RehashUsersAndChans()
168 user_hash* old_users = this->clientlist;
169 user_hash* old_uuid = this->uuidlist;
170 chan_hash* old_chans = this->chanlist;
172 this->clientlist = new user_hash();
173 this->uuidlist = new user_hash();
174 this->chanlist = new chan_hash();
176 for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
177 this->clientlist->insert(*n);
181 for (user_hash::const_iterator n = old_uuid->begin(); n != old_uuid->end(); n++)
182 this->uuidlist->insert(*n);
186 for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
187 this->chanlist->insert(*n);
192 void InspIRCd::CloseLog()
195 this->Logger->Close();
198 void InspIRCd::SetSignals()
201 signal(SIGALRM, SIG_IGN);
202 signal(SIGHUP, InspIRCd::SetSignal);
203 signal(SIGPIPE, SIG_IGN);
204 signal(SIGCHLD, SIG_IGN);
206 signal(SIGTERM, InspIRCd::SetSignal);
209 void InspIRCd::QuickExit(int status)
214 bool InspIRCd::DaemonSeed()
217 printf_c("InspIRCd Process ID: \033[1;32m%lu\033[0m\n", GetCurrentProcessId());
220 signal(SIGTERM, InspIRCd::QuickExit);
223 if ((childpid = fork ()) < 0)
225 else if (childpid > 0)
227 /* We wait here for the child process to kill us,
228 * so that the shell prompt doesnt come back over
230 * Sending a kill with a signal of 0 just checks
231 * if the child pid is still around. If theyre not,
232 * they threw an error and we should give up.
234 while (kill(childpid, 0) != -1)
240 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
242 signal(SIGTERM, InspIRCd::SetSignal);
245 if (getrlimit(RLIMIT_CORE, &rl) == -1)
247 this->Log(DEFAULT,"Failed to getrlimit()!");
252 rl.rlim_cur = rl.rlim_max;
253 if (setrlimit(RLIMIT_CORE, &rl) == -1)
254 this->Log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
261 void InspIRCd::WritePID(const std::string &filename)
263 std::string fname = (filename.empty() ? "inspircd.pid" : filename);
264 if (*(fname.begin()) != '/')
266 std::string::size_type pos;
267 std::string confpath = this->ConfigFileName;
268 if ((pos = confpath.rfind("/")) != std::string::npos)
270 /* Leaves us with just the path */
271 fname = confpath.substr(0, pos) + std::string("/") + fname;
274 std::ofstream outfile(fname.c_str());
275 if (outfile.is_open())
282 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
283 this->Log(DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
284 Exit(EXIT_STATUS_PID);
288 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 */
312 memset(&server, 0, sizeof(server));
313 memset(&client, 0, sizeof(client));
315 SocketEngineFactory* SEF = new SocketEngineFactory();
316 SE = SEF->Create(this);
321 this->unregistered_count = 0;
323 this->clientlist = new user_hash();
324 this->uuidlist = new user_hash();
325 this->chanlist = new chan_hash();
328 this->Config = new ServerConfig(this);
329 this->SNO = new SnomaskManager(this);
330 this->Modules = new ModuleManager(this);
331 this->stats = new serverstats();
332 this->Timers = new TimerManager(this);
333 this->Parser = new CommandParser(this);
334 this->XLines = new XLineManager(this);
336 this->Config->argv = argv;
337 this->Config->argc = argc;
339 if (chdir(Config->GetFullProgDir().c_str()))
341 printf("Unable to change to my directory: %s\nAborted.", strerror(errno));
345 this->Config->opertypes.clear();
346 this->Config->operclass.clear();
348 this->TIME = this->OLDTIME = this->startup_time = time(NULL);
349 this->time_delta = 0;
352 *this->LogFileName = 0;
353 strlcpy(this->ConfigFileName, CONFIG_FILE, MAXBUF);
355 struct option longopts[] =
357 { "nofork", no_argument, &do_nofork, 1 },
358 { "logfile", required_argument, NULL, 'f' },
359 { "config", required_argument, NULL, 'c' },
360 { "debug", no_argument, &do_debug, 1 },
361 { "nolog", no_argument, &do_nolog, 1 },
362 { "runasroot", no_argument, &do_root, 1 },
363 { "version", no_argument, &do_version, 1 },
367 while ((c = getopt_long_only(argc, argv, ":f:", longopts, NULL)) != -1)
372 /* Log filename was set */
373 strlcpy(LogFileName, optarg, MAXBUF);
376 /* Config filename was set */
377 strlcpy(ConfigFileName, optarg, MAXBUF);
380 /* getopt_long_only() set an int variable, just keep going */
383 /* Unknown parameter! DANGER, INTRUDER.... err.... yeah. */
384 printf("Usage: %s [--nofork] [--nolog] [--debug] [--logfile <filename>] [--runasroot] [--version] [--config <config>]\n", argv[0]);
385 Exit(EXIT_STATUS_ARGV);
392 printf("\n%s r%s\n", VERSION, REVISION);
393 Exit(EXIT_STATUS_NOERROR);
401 DWORD ExitCode = WindowsForkStart(this);
408 WSAStartup(MAKEWORD(2,0), &wsadata);
410 ChangeWindowsSpecificPointers(this);
412 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
414 if (!this->OpenLog(argv, argc))
416 printf("ERROR: Could not open logfile %s: %s\n\n", Config->logpath.c_str(), strerror(errno));
417 Exit(EXIT_STATUS_LOG);
420 if (!ServerConfig::FileExists(this->ConfigFileName))
422 printf("ERROR: Cannot open config file: %s\nExiting...\n", this->ConfigFileName);
423 this->Log(DEFAULT,"Unable to open config file %s", this->ConfigFileName);
424 Exit(EXIT_STATUS_CONFIG);
427 printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
428 printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
429 printf_c("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special, pippijn, peavey, Burlex\033[0m\n");
430 printf_c("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
432 /* Set the finished argument values */
433 Config->nofork = do_nofork;
434 Config->forcedebug = do_debug;
435 Config->writelog = !do_nolog;
436 Config->ClearStack();
437 Config->Read(true, NULL);
439 // Get XLine to do it's thing.
440 this->XLines->CheckELines();
441 this->XLines->ApplyLines();
443 this->Modules->modules.resize(255);
444 this->Modules->handles.resize(255);
447 * Initialise SID/UID.
448 * For an explanation as to exactly how this works, and why it works this way, see GetUID().
459 for (const char* x = Config->ServerName; *x; ++x)
461 for (const char* y = Config->ServerDesc; *y; ++y)
468 this->InitialiseUID();
470 /* set up fake client */
471 this->FakeClient = new User(this);
472 this->FakeClient->SetFd(FD_MAGIC_NUMBER);
478 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
479 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
480 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
481 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
482 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
483 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
484 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
485 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
493 if (!this->DaemonSeed())
495 printf("ERROR: could not go into daemon mode. Shutting down.\n");
496 Log(DEFAULT,"ERROR: could not go into daemon mode. Shutting down.");
497 Exit(EXIT_STATUS_FORK);
501 SE->RecoverFromFork();
503 this->Modes = new ModeParser(this);
504 this->AddServerName(Config->ServerName);
506 int bounditems = BindPorts(true, found_ports, pl);
508 for(int t = 0; t < 255; t++)
509 Config->global_implementation[t] = 0;
511 memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
515 this->Res = new DNS(this);
517 this->Modules->LoadAll();
519 /* Just in case no modules were loaded - fix for bug #101 */
520 this->BuildISupport();
521 InitializeDisabledCommands(Config->DisabledCommands, this);
523 if ((Config->ports.size() == 0) && (found_ports > 0))
525 printf("\nERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?\n");
526 Log(DEFAULT,"ERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?");
527 Exit(EXIT_STATUS_BIND);
530 if (Config->ports.size() != (unsigned int)found_ports)
532 printf("\nWARNING: Not all your client ports could be bound --\nstarting anyway with %d of %d client ports bound.\n\n", bounditems, found_ports);
533 printf("The following port(s) failed to bind:\n");
535 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
537 printf("%d.\tIP: %s\tPort: %lu\n", j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
543 if (kill(getppid(), SIGTERM) == -1)
545 printf("Error killing parent process: %s\n",strerror(errno));
546 Log(DEFAULT,"Error killing parent process: %s",strerror(errno));
550 if (isatty(0) && isatty(1) && isatty(2))
552 /* We didn't start from a TTY, we must have started from a background process -
553 * e.g. we are restarting, or being launched by cron. Dont kill parent, and dont
564 Log(DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
568 WindowsIPC = new IPC(this);
571 WindowsForkKillOwner(this);
576 printf("\nInspIRCd is now running!\n");
577 Log(DEFAULT,"Startup complete.");
579 this->WritePID(Config->PID);
582 /* moved to a function, as UID generation can call this also */
583 void InspIRCd::InitialiseUID()
586 size_t sid = Config->sid;
588 current_uid[0] = sid / 100 + 48;
589 current_uid[1] = ((sid / 10) % 10) + 48;
590 current_uid[2] = sid % 10 + 48;
593 for(i = 3; i < UUID_LENGTH - 1; i++)
594 current_uid[i] = 'A';
604 static time_t uptime;
605 static struct tm * stime;
606 static char window_title[100];
609 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
610 * Once per loop iteration is pleanty.
615 /* Run background module timers every few seconds
616 * (the docs say modules shouldnt rely on accurate
617 * timing using this event, so we dont have to
618 * time this exactly).
624 WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
627 if ((TIME % 3600) == 0)
629 this->RehashUsersAndChans();
630 FOREACH_MOD_I(this, I_OnGarbageCollect, OnGarbageCollect());
633 Timers->TickTimers(TIME);
634 this->DoBackgroundUserStuff();
638 FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
639 Timers->TickMissedTimers(TIME);
642 /* Same change as in cmd_stats.cpp, use RUSAGE_SELF rather than '0' -- Om */
643 if (!getrusage(RUSAGE_SELF, &ru))
645 gettimeofday(&this->stats->LastSampled, NULL);
646 this->stats->LastCPU = ru.ru_utime;
653 uptime = Time() - startup_time;
654 stime = gmtime(&uptime);
655 snprintf(window_title, 100, "InspIRCd - %u clients, %u accepted connections - Up %u days, %.2u:%.2u:%.2u",
656 LocalUserCount(), stats->statsAccept, stime->tm_yday, stime->tm_hour, stime->tm_min, stime->tm_sec);
657 SetConsoleTitle(window_title);
662 /* Call the socket engine to wait on the active
663 * file descriptors. The socket engine has everything's
664 * descriptors in its list... dns, modules, users,
665 * servers... so its nice and easy, just one call.
666 * This will cause any read or write events to be
667 * dispatched to their handlers.
669 this->SE->DispatchEvents();
671 /* if any users was quit, take them out */
672 this->GlobalCulls.Apply();
674 /* If any inspsockets closed, remove them */
675 this->BufferedSocketCull();
679 this->SignalHandler(s_signal);
687 void InspIRCd::BufferedSocketCull()
689 for (std::map<BufferedSocket*,BufferedSocket*>::iterator x = SocketCull.begin(); x != SocketCull.end(); ++x)
691 SE->DelFd(x->second);
698 /**********************************************************************************/
701 * An ircd in five lines! bwahahaha. ahahahahaha. ahahah *cough*.
704 int main(int argc, char ** argv)
706 SI = new InspIRCd(argc, argv);
707 mysig = &SI->s_signal;
713 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
714 * (until this returns true, a user will block in the waiting state, waiting to connect up to the
715 * registration timeout maximum seconds)
717 bool InspIRCd::AllModulesReportReady(User* user)
719 if (!Config->global_implementation[I_OnCheckReady])
722 for (int i = 0; i <= this->Modules->GetCount(); i++)
724 if (Config->implement_lists[i][I_OnCheckReady])
726 int res = this->Modules->modules[i]->OnCheckReady(user);
734 time_t InspIRCd::Time(bool delta)
737 return TIME + time_delta;
741 int InspIRCd::SetTimeDelta(int delta)
743 int old = time_delta;
745 this->Log(DEBUG, "Time delta set to %d (was %d)", time_delta, old);
749 void InspIRCd::AddLocalClone(User* user)
751 clonemap::iterator x = local_clones.find(user->GetIPString());
752 if (x != local_clones.end())
755 local_clones[user->GetIPString()] = 1;
758 void InspIRCd::AddGlobalClone(User* user)
760 clonemap::iterator y = global_clones.find(user->GetIPString());
761 if (y != global_clones.end())
764 global_clones[user->GetIPString()] = 1;
767 int InspIRCd::GetTimeDelta()
772 void InspIRCd::SetSignal(int signal)