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"
42 using irc::sockets::insp_ntoa;
43 using irc::sockets::insp_inaddr;
44 using irc::sockets::insp_sockaddr;
50 /* Burlex: Moved from exitcodes.h -- due to duplicate symbols */
51 const char* ExitCodes[] =
54 "DIE command", /* 1 */
55 "execv() failed", /* 2 */
56 "Internal error", /* 3 */
57 "Config file error", /* 4 */
58 "Logfile error", /* 5 */
59 "POSIX fork failed", /* 6 */
60 "Bad commandline parameters", /* 7 */
61 "No ports could be bound", /* 8 */
62 "Can't write PID file", /* 9 */
63 "SocketEngine could not initialize", /* 10 */
64 "Refusing to start up as root", /* 11 */
65 "Found a <die> tag!", /* 12 */
66 "Couldn't load module on startup", /* 13 */
67 "Could not create windows forked process", /* 14 */
68 "Received SIGTERM", /* 15 */
71 void InspIRCd::Cleanup()
75 for (unsigned int i = 0; i < Config->ports.size(); i++)
77 /* This calls the constructor and closes the listening socket */
78 delete Config->ports[i];
81 Config->ports.clear();
84 /* Close all client sockets, or the new process inherits them */
85 for (std::vector<User*>::const_iterator i = this->Users->local_users.begin(); i != this->Users->local_users.end(); i++)
87 (*i)->SetWriteError("Server shutdown");
91 /* We do this more than once, so that any service providers get a
92 * chance to be unhooked by the modules using them, but then get
93 * a chance to be removed themsleves.
95 for (int tries = 0; tries < 3; tries++)
97 std::vector<std::string> module_names = Modules->GetAllModuleNames(0);
98 for (std::vector<std::string>::iterator k = module_names.begin(); k != module_names.end(); ++k)
100 /* Unload all modules, so they get a chance to clean up their listeners */
101 this->Modules->Unload(k->c_str());
107 this->Logger->Close();
110 /* Cleanup Server Names */
111 for(servernamelist::iterator itr = servernames.begin(); itr != servernames.end(); ++itr)
117 void InspIRCd::Restart(const std::string &reason)
119 /* SendError flushes each client's queue,
120 * regardless of writeability state
122 this->SendError(reason);
126 /* Figure out our filename (if theyve renamed it, we're boned) */
130 char module[MAX_PATH];
131 if (GetModuleFileName(NULL, module, MAX_PATH))
134 me = Config->MyDir + "/inspircd";
137 if (execv(me.c_str(), Config->argv) == -1)
139 /* Will raise a SIGABRT if not trapped */
140 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
144 void InspIRCd::ResetMaxBans()
146 for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
147 i->second->ResetMaxBans();
150 /** Because hash_map doesnt free its buckets when we delete items (this is a 'feature')
151 * we must occasionally rehash the hash (yes really).
152 * We do this by copying the entries from the old hash to a new hash, causing all
153 * empty buckets to be weeded out of the hash. We dont do this on a timer, as its
154 * very expensive, so instead we do it when the user types /REHASH and expects a
155 * short delay anyway.
157 void InspIRCd::RehashUsersAndChans()
159 user_hash* old_users = this->Users->clientlist;
160 user_hash* old_uuid = this->Users->uuidlist;
161 chan_hash* old_chans = this->chanlist;
163 this->Users->clientlist = new user_hash();
164 this->Users->uuidlist = new user_hash();
165 this->chanlist = new chan_hash();
167 for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
168 this->Users->clientlist->insert(*n);
172 for (user_hash::const_iterator n = old_uuid->begin(); n != old_uuid->end(); n++)
173 this->Users->uuidlist->insert(*n);
177 for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
178 this->chanlist->insert(*n);
183 void InspIRCd::CloseLog()
186 this->Logger->Close();
189 void InspIRCd::SetSignals()
192 signal(SIGALRM, SIG_IGN);
193 signal(SIGHUP, InspIRCd::SetSignal);
194 signal(SIGPIPE, SIG_IGN);
195 signal(SIGCHLD, SIG_IGN);
197 signal(SIGTERM, InspIRCd::SetSignal);
200 void InspIRCd::QuickExit(int status)
205 bool InspIRCd::DaemonSeed()
208 printf_c("InspIRCd Process ID: \033[1;32m%lu\033[0m\n", GetCurrentProcessId());
211 signal(SIGTERM, InspIRCd::QuickExit);
214 if ((childpid = fork ()) < 0)
216 else if (childpid > 0)
218 /* We wait here for the child process to kill us,
219 * so that the shell prompt doesnt come back over
221 * Sending a kill with a signal of 0 just checks
222 * if the child pid is still around. If theyre not,
223 * they threw an error and we should give up.
225 while (kill(childpid, 0) != -1)
231 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
233 signal(SIGTERM, InspIRCd::SetSignal);
236 if (getrlimit(RLIMIT_CORE, &rl) == -1)
238 this->Log(DEFAULT,"Failed to getrlimit()!");
243 rl.rlim_cur = rl.rlim_max;
244 if (setrlimit(RLIMIT_CORE, &rl) == -1)
245 this->Log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
252 void InspIRCd::WritePID(const std::string &filename)
254 std::string fname = (filename.empty() ? "inspircd.pid" : filename);
255 if (*(fname.begin()) != '/')
257 std::string::size_type pos;
258 std::string confpath = this->ConfigFileName;
259 if ((pos = confpath.rfind("/")) != std::string::npos)
261 /* Leaves us with just the path */
262 fname = confpath.substr(0, pos) + std::string("/") + fname;
265 std::ofstream outfile(fname.c_str());
266 if (outfile.is_open())
273 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
274 this->Log(DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
275 Exit(EXIT_STATUS_PID);
279 InspIRCd::InspIRCd(int argc, char** argv)
282 /* Functor initialisation. Note that the ordering here is very important. */
283 HandleProcessUser(this),
286 HandleFindDescriptor(this),
287 HandleFloodQuitUser(this),
289 /* Functor pointer initialisation. Must match the order of the list above */
290 ProcessUser(&HandleProcessUser),
291 IsNick(&HandleIsNick),
292 IsIdent(&HandleIsIdent),
293 FindDescriptor(&HandleFindDescriptor),
294 FloodQuitUser(&HandleFloodQuitUser)
300 int do_version = 0, do_nofork = 0, do_debug = 0, do_nolog = 0, do_root = 0; /* flag variables */
303 memset(&server, 0, sizeof(server));
304 memset(&client, 0, sizeof(client));
306 // This must be created first, so other parts of Insp can use it while starting up
307 this->Logs = new LogManager(this);
309 SocketEngineFactory* SEF = new SocketEngineFactory();
310 SE = SEF->Create(this);
315 // Create base manager classes early, so nothing breaks
316 this->Users = new UserManager(this);
318 this->Users->unregistered_count = 0;
320 this->Users->clientlist = new user_hash();
321 this->Users->uuidlist = new user_hash();
322 this->chanlist = new chan_hash();
326 this->Config = new ServerConfig(this);
327 this->SNO = new SnomaskManager(this);
328 this->BanCache = new BanCacheManager(this);
329 this->Modules = new ModuleManager(this);
330 this->stats = new serverstats();
331 this->Timers = new TimerManager(this);
332 this->Parser = new CommandParser(this);
333 this->XLines = new XLineManager(this);
335 this->Config->argv = argv;
336 this->Config->argc = argc;
338 if (chdir(Config->GetFullProgDir().c_str()))
340 printf("Unable to change to my directory: %s\nAborted.", strerror(errno));
344 this->Config->opertypes.clear();
345 this->Config->operclass.clear();
347 this->TIME = this->OLDTIME = this->startup_time = time(NULL);
348 this->time_delta = 0;
351 *this->LogFileName = 0;
352 strlcpy(this->ConfigFileName, CONFIG_FILE, MAXBUF);
354 struct option longopts[] =
356 { "nofork", no_argument, &do_nofork, 1 },
357 { "logfile", required_argument, NULL, 'f' },
358 { "config", required_argument, NULL, 'c' },
359 { "debug", no_argument, &do_debug, 1 },
360 { "nolog", no_argument, &do_nolog, 1 },
361 { "runasroot", no_argument, &do_root, 1 },
362 { "version", no_argument, &do_version, 1 },
366 while ((c = getopt_long_only(argc, argv, ":f:", longopts, NULL)) != -1)
371 /* Log filename was set */
372 strlcpy(LogFileName, optarg, MAXBUF);
375 /* Config filename was set */
376 strlcpy(ConfigFileName, optarg, MAXBUF);
379 /* getopt_long_only() set an int variable, just keep going */
382 /* Unknown parameter! DANGER, INTRUDER.... err.... yeah. */
383 printf("Usage: %s [--nofork] [--nolog] [--debug] [--logfile <filename>] [--runasroot] [--version] [--config <config>]\n", argv[0]);
384 Exit(EXIT_STATUS_ARGV);
391 printf("\n%s r%s\n", VERSION, REVISION);
392 Exit(EXIT_STATUS_NOERROR);
400 DWORD ExitCode = WindowsForkStart(this);
407 WSAStartup(MAKEWORD(2,0), &wsadata);
408 ChangeWindowsSpecificPointers(this);
410 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
412 if (!this->OpenLog(argv, argc))
414 printf("ERROR: Could not open logfile %s: %s\n\n", Config->logpath.c_str(), strerror(errno));
415 Exit(EXIT_STATUS_LOG);
418 if (!ServerConfig::FileExists(this->ConfigFileName))
420 printf("ERROR: Cannot open config file: %s\nExiting...\n", this->ConfigFileName);
421 this->Log(DEFAULT,"Unable to open config file %s", this->ConfigFileName);
422 Exit(EXIT_STATUS_CONFIG);
425 printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
426 printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
427 printf_c("Developers:\n");
428 printf_c("\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special\n");
429 printf_c("\t\033[1;32mpippijn, peavey, aquanight, fez\033[0m\n\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();
438 this->Modes = new ModeParser(this);
440 /* set up fake client (uid is incorrect at this point,
441 * until after config is read. we set up the user again
444 this->FakeClient = new User(this);
445 this->FakeClient->SetFd(FD_MAGIC_NUMBER);
451 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
452 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
453 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
454 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
455 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
456 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
457 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
458 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
466 if (!this->DaemonSeed())
468 printf("ERROR: could not go into daemon mode. Shutting down.\n");
469 Log(DEFAULT,"ERROR: could not go into daemon mode. Shutting down.");
470 Exit(EXIT_STATUS_FORK);
474 SE->RecoverFromFork();
476 /* Read config, pass 0. At the end if this pass,
477 * the Config->IncludeFiles is populated, we call
478 * Config->StartDownloads to initialize the downlaods of all
481 Config->Read(true, NULL, 0);
482 Config->DoDownloads();
483 /* We have all the files we can get, initiate pass 1 */
484 Config->Read(true, NULL, 1);
486 this->AddServerName(Config->ServerName);
489 * Initialise SID/UID.
490 * For an explanation as to exactly how this works, and why it works this way, see GetUID().
501 for (const char* x = Config->ServerName; *x; ++x)
503 for (const char* y = Config->ServerDesc; *y; ++y)
507 Config->sid[0] = (char)(sid / 100 + 48);
508 Config->sid[1] = (char)(((sid / 10) % 10) + 48);
509 Config->sid[2] = (char)(sid % 10 + 48);
512 this->InitialiseUID();
514 /* set up fake client again this time with the correct uid */
516 this->FakeClient = new User(this);
517 this->FakeClient->SetFd(FD_MAGIC_NUMBER);
519 // Get XLine to do it's thing.
520 this->XLines->CheckELines();
521 this->XLines->ApplyLines();
525 int bounditems = BindPorts(true, found_ports, pl);
529 /*this->Modules->LoadAll();*/
531 /* Just in case no modules were loaded - fix for bug #101 */
532 this->BuildISupport();
533 InitializeDisabledCommands(Config->DisabledCommands, this);
535 if ((Config->ports.size() == 0) && (found_ports > 0))
537 printf("\nERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?\n");
538 Log(DEFAULT,"ERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?");
539 Exit(EXIT_STATUS_BIND);
542 if (Config->ports.size() != (unsigned int)found_ports)
544 printf("\nWARNING: Not all your client ports could be bound --\nstarting anyway with %d of %d client ports bound.\n\n", bounditems, found_ports);
545 printf("The following port(s) failed to bind:\n");
547 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
549 printf("%d.\tIP: %s\tPort: %lu\n", j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
555 if (kill(getppid(), SIGTERM) == -1)
557 printf("Error killing parent process: %s\n",strerror(errno));
558 Log(DEFAULT,"Error killing parent process: %s",strerror(errno));
562 if (isatty(0) && isatty(1) && isatty(2))
564 /* We didn't start from a TTY, we must have started from a background process -
565 * e.g. we are restarting, or being launched by cron. Dont kill parent, and dont
576 Log(DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
580 WindowsIPC = new IPC(this);
583 WindowsForkKillOwner(this);
588 printf("\nInspIRCd is now running as '%s'[%s]\n", Config->ServerName,Config->GetSID().c_str());
589 Log(DEFAULT,"Startup complete as '%s'[%s]", Config->ServerName,Config->GetSID().c_str());
591 this->WritePID(Config->PID);
594 /* moved to a function, as UID generation can call this also */
595 void InspIRCd::InitialiseUID()
599 current_uid[0] = Config->sid[0];
600 current_uid[1] = Config->sid[1];
601 current_uid[2] = Config->sid[2];
604 for(i = 3; i < UUID_LENGTH - 1; i++)
605 current_uid[i] = 'A';
607 current_uid[UUID_LENGTH] = '\0';
617 static time_t uptime;
618 static struct tm * stime;
619 static char window_title[100];
622 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
623 * Once per loop iteration is pleanty.
628 /* Run background module timers every few seconds
629 * (the docs say modules shouldnt rely on accurate
630 * timing using this event, so we dont have to
631 * time this exactly).
637 SNO->WriteToSnoMask('A', "\002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
640 if ((TIME % 3600) == 0)
642 this->RehashUsersAndChans();
643 FOREACH_MOD_I(this, I_OnGarbageCollect, OnGarbageCollect());
646 Timers->TickTimers(TIME);
647 this->DoBackgroundUserStuff();
651 FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
652 SNO->FlushSnotices();
655 /* Same change as in cmd_stats.cpp, use RUSAGE_SELF rather than '0' -- Om */
656 if (!getrusage(RUSAGE_SELF, &ru))
658 gettimeofday(&this->stats->LastSampled, NULL);
659 this->stats->LastCPU = ru.ru_utime;
666 /* Call the socket engine to wait on the active
667 * file descriptors. The socket engine has everything's
668 * descriptors in its list... dns, modules, users,
669 * servers... so its nice and easy, just one call.
670 * This will cause any read or write events to be
671 * dispatched to their handlers.
673 this->SE->DispatchEvents();
675 /* if any users were quit, take them out */
676 this->GlobalCulls.Apply();
678 /* If any inspsockets closed, remove them */
679 this->BufferedSocketCull();
683 this->SignalHandler(s_signal);
691 void InspIRCd::BufferedSocketCull()
693 for (std::map<BufferedSocket*,BufferedSocket*>::iterator x = SocketCull.begin(); x != SocketCull.end(); ++x)
695 Log(DEBUG,"Cull socket");
696 SE->DelFd(x->second);
703 /**********************************************************************************/
706 * An ircd in five lines! bwahahaha. ahahahahaha. ahahah *cough*.
709 int main(int argc, char ** argv)
711 SI = new InspIRCd(argc, argv);
712 mysig = &SI->s_signal;
718 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
719 * (until this returns true, a user will block in the waiting state, waiting to connect up to the
720 * registration timeout maximum seconds)
722 bool InspIRCd::AllModulesReportReady(User* user)
724 for (EventHandlerIter i = Modules->EventHandlers[I_OnCheckReady].begin(); i != Modules->EventHandlers[I_OnCheckReady].end(); ++i)
726 int res = (*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 int InspIRCd::GetTimeDelta()
754 void InspIRCd::SetSignal(int signal)