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"
46 /* This MUST remain static and delcared outside the class, so that WriteProcessMemory can reference it properly */
47 static DWORD owner_processid = 0;
49 DWORD WindowsForkStart(InspIRCd * Instance)
51 /* Windows implementation of fork() :P */
53 char module[MAX_PATH];
54 if(!GetModuleFileName(NULL, module, MAX_PATH))
56 printf("GetModuleFileName() failed.\n");
60 STARTUPINFO startupinfo;
61 PROCESS_INFORMATION procinfo;
62 ZeroMemory(&startupinfo, sizeof(STARTUPINFO));
63 ZeroMemory(&procinfo, sizeof(PROCESS_INFORMATION));
65 // Fill in the startup info struct
66 GetStartupInfo(&startupinfo);
68 /* Default creation flags create the processes suspended */
69 DWORD startupflags = CREATE_SUSPENDED;
71 /* On windows 2003/XP and above, we can use the value
72 * CREATE_PRESERVE_CODE_AUTHZ_LEVEL which gives more access
73 * to the process which we may require on these operating systems.
76 vi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
78 if ((vi.dwMajorVersion >= 5) && (vi.dwMinorVersion > 0))
79 startupflags |= CREATE_PRESERVE_CODE_AUTHZ_LEVEL;
81 // Launch our "forked" process.
82 BOOL bSuccess = CreateProcess ( module, // Module (exe) filename
83 strdup(GetCommandLine()), // Command line (exe plus parameters from the OS)
84 // NOTE: We cannot return the direct value of the
85 // GetCommandLine function here, as the pointer is
86 // passed straight to the child process, and will be
87 // invalid once we exit as it goes out of context.
88 // strdup() seems ok, though.
89 0, // PROCESS_SECURITY_ATTRIBUTES
90 0, // THREAD_SECURITY_ATTRIBUTES
91 TRUE, // We went to inherit handles.
92 startupflags, // Allow us full access to the process and suspend it.
94 0, // CURRENT_DIRECTORY
95 &startupinfo, // startup info
96 &procinfo); // process info
100 printf("CreateProcess() error: %s\n", dlerror());
104 // Set the owner process id in the target process.
106 DWORD pid = GetCurrentProcessId();
107 if(!WriteProcessMemory(procinfo.hProcess, &owner_processid, &pid, sizeof(DWORD), &written) || written != sizeof(DWORD))
109 printf("WriteProcessMemory() failed: %s\n", dlerror());
113 // Resume the other thread (let it start)
114 ResumeThread(procinfo.hThread);
116 // Wait for the new process to kill us. If there is some error, the new process will end and we will end up at the next line.
117 WaitForSingleObject(procinfo.hProcess, INFINITE);
119 // If we hit this it means startup failed, default to 14 if this fails.
121 GetExitCodeProcess(procinfo.hProcess, &ExitCode);
122 CloseHandle(procinfo.hThread);
123 CloseHandle(procinfo.hProcess);
127 void WindowsForkKillOwner(InspIRCd * Instance)
129 HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, owner_processid);
130 if(!hProcess || !owner_processid)
132 printf("Could not open process id %u: %s.\n", owner_processid, dlerror());
137 if(!TerminateProcess(hProcess, 0))
139 printf("Could not TerminateProcess(): %s\n", dlerror());
143 CloseHandle(hProcess);
148 using irc::sockets::NonBlocking;
149 using irc::sockets::Blocking;
150 using irc::sockets::insp_ntoa;
151 using irc::sockets::insp_inaddr;
152 using irc::sockets::insp_sockaddr;
157 /* Burlex: Moved from exitcodes.h -- due to duplicate symbols */
158 const char* ExitCodes[] =
161 "DIE command", /* 1 */
162 "execv() failed", /* 2 */
163 "Internal error", /* 3 */
164 "Config file error", /* 4 */
165 "Logfile error", /* 5 */
166 "POSIX fork failed", /* 6 */
167 "Bad commandline parameters", /* 7 */
168 "No ports could be bound", /* 8 */
169 "Can't write PID file", /* 9 */
170 "SocketEngine could not initialize", /* 10 */
171 "Refusing to start up as root", /* 11 */
172 "Found a <die> tag!", /* 12 */
173 "Couldn't load module on startup", /* 13 */
174 "Could not create windows forked process", /* 14 */
175 "Received SIGTERM", /* 15 */
178 void InspIRCd::Cleanup()
180 std::vector<std::string> mymodnames;
181 int MyModCount = this->GetModuleCount();
183 for (unsigned int i = 0; i < Config->ports.size(); i++)
185 /* This calls the constructor and closes the listening socket */
186 delete Config->ports[i];
189 Config->ports.clear();
191 /* Close all client sockets, or the new process inherits them */
192 for (std::vector<userrec*>::const_iterator i = this->local_users.begin(); i != this->local_users.end(); i++)
194 (*i)->SetWriteError("Server shutdown");
198 /* We do this more than once, so that any service providers get a
199 * chance to be unhooked by the modules using them, but then get
200 * a chance to be removed themsleves.
202 for (int tries = 0; tries < 3; tries++)
204 MyModCount = this->GetModuleCount();
207 /* Unload all modules, so they get a chance to clean up their listeners */
208 for (int j = 0; j <= MyModCount; j++)
209 mymodnames.push_back(Config->module_names[j]);
211 for (int k = 0; k <= MyModCount; k++)
212 this->UnloadModule(mymodnames[k].c_str());
216 this->Logger->Close();
218 /* Cleanup Server Names */
219 for(servernamelist::iterator itr = servernames.begin(); itr != servernames.end(); ++itr)
228 void InspIRCd::Restart(const std::string &reason)
230 /* SendError flushes each client's queue,
231 * regardless of writeability state
233 this->SendError(reason);
237 /* Figure out our filename (if theyve renamed it, we're boned) */
241 char module[MAX_PATH];
242 if (GetModuleFileName(NULL, module, MAX_PATH))
245 me = Config->MyDir + "/inspircd";
248 if (execv(me.c_str(), Config->argv) == -1)
250 /* Will raise a SIGABRT if not trapped */
251 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
255 void InspIRCd::ResetMaxBans()
257 for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
258 i->second->ResetMaxBans();
261 /** Because hash_map doesnt free its buckets when we delete items (this is a 'feature')
262 * we must occasionally rehash the hash (yes really).
263 * We do this by copying the entries from the old hash to a new hash, causing all
264 * empty buckets to be weeded out of the hash. We dont do this on a timer, as its
265 * very expensive, so instead we do it when the user types /REHASH and expects a
266 * short delay anyway.
268 void InspIRCd::RehashUsersAndChans()
270 user_hash* old_users = this->clientlist;
271 chan_hash* old_chans = this->chanlist;
273 this->clientlist = new user_hash();
274 this->chanlist = new chan_hash();
276 for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
277 this->clientlist->insert(*n);
281 for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
282 this->chanlist->insert(*n);
287 void InspIRCd::CloseLog()
289 this->Logger->Close();
292 void InspIRCd::SetSignals()
295 signal(SIGALRM, SIG_IGN);
296 signal(SIGHUP, InspIRCd::SetSignal);
297 signal(SIGPIPE, SIG_IGN);
298 signal(SIGCHLD, SIG_IGN);
300 signal(SIGTERM, InspIRCd::SetSignal);
303 void InspIRCd::QuickExit(int status)
308 bool InspIRCd::DaemonSeed()
311 printf_c("InspIRCd Process ID: \033[1;32m%lu\033[0m\n", GetCurrentProcessId());
314 signal(SIGTERM, InspIRCd::QuickExit);
317 if ((childpid = fork ()) < 0)
319 else if (childpid > 0)
321 /* We wait here for the child process to kill us,
322 * so that the shell prompt doesnt come back over
324 * Sending a kill with a signal of 0 just checks
325 * if the child pid is still around. If theyre not,
326 * they threw an error and we should give up.
328 while (kill(childpid, 0) != -1)
334 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
336 signal(SIGTERM, InspIRCd::SetSignal);
339 if (getrlimit(RLIMIT_CORE, &rl) == -1)
341 this->Log(DEFAULT,"Failed to getrlimit()!");
346 rl.rlim_cur = rl.rlim_max;
347 if (setrlimit(RLIMIT_CORE, &rl) == -1)
348 this->Log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
355 void InspIRCd::WritePID(const std::string &filename)
357 std::string fname = (filename.empty() ? "inspircd.pid" : filename);
358 if (*(fname.begin()) != '/')
360 std::string::size_type pos;
361 std::string confpath = this->ConfigFileName;
362 if ((pos = confpath.rfind("/")) != std::string::npos)
364 /* Leaves us with just the path */
365 fname = confpath.substr(0, pos) + std::string("/") + fname;
368 std::ofstream outfile(fname.c_str());
369 if (outfile.is_open())
376 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
377 this->Log(DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
378 Exit(EXIT_STATUS_PID);
382 InspIRCd::InspIRCd(int argc, char** argv)
385 HandleProcessUser(this),
388 HandleFindDescriptor(this),
389 ProcessUser(&HandleProcessUser),
390 IsNick(&HandleIsNick),
391 IsIdent(&HandleIsIdent),
392 FindDescriptor(&HandleFindDescriptor)
396 int do_version = 0, do_nofork = 0, do_debug = 0, do_nolog = 0, do_root = 0; /* flag variables */
401 memset(&server, 0, sizeof(server));
402 memset(&client, 0, sizeof(client));
406 this->unregistered_count = 0;
408 this->clientlist = new user_hash();
409 this->chanlist = new chan_hash();
411 this->Config = new ServerConfig(this);
413 this->Config->argv = argv;
414 this->Config->argc = argc;
416 chdir(Config->GetFullProgDir().c_str());
418 this->Config->opertypes.clear();
419 this->Config->operclass.clear();
420 this->SNO = new SnomaskManager(this);
421 this->TIME = this->OLDTIME = this->startup_time = time(NULL);
422 this->time_delta = 0;
423 this->next_call = this->TIME + 3;
426 *this->LogFileName = 0;
427 strlcpy(this->ConfigFileName, CONFIG_FILE, MAXBUF);
429 struct option longopts[] =
431 { "nofork", no_argument, &do_nofork, 1 },
432 { "logfile", required_argument, NULL, 'f' },
433 { "config", required_argument, NULL, 'c' },
434 { "debug", no_argument, &do_debug, 1 },
435 { "nolog", no_argument, &do_nolog, 1 },
436 { "runasroot", no_argument, &do_root, 1 },
437 { "version", no_argument, &do_version, 1 },
441 while ((c = getopt_long_only(argc, argv, ":f:", longopts, NULL)) != -1)
446 /* Log filename was set */
447 strlcpy(LogFileName, optarg, MAXBUF);
450 /* Config filename was set */
451 strlcpy(ConfigFileName, optarg, MAXBUF);
454 /* getopt_long_only() set an int variable, just keep going */
457 /* Unknown parameter! DANGER, INTRUDER.... err.... yeah. */
458 printf("Usage: %s [--nofork] [--nolog] [--debug] [--logfile <filename>] [--runasroot] [--version] [--config <config>]\n", argv[0]);
459 Exit(EXIT_STATUS_ARGV);
466 printf("\n%s r%s\n", VERSION, REVISION);
467 Exit(EXIT_STATUS_NOERROR);
473 if(!do_nofork && !owner_processid)
475 DWORD ExitCode = WindowsForkStart(this);
482 WSAStartup(MAKEWORD(2,0), &wsadata);
485 if (!ServerConfig::FileExists(this->ConfigFileName))
487 printf("ERROR: Cannot open config file: %s\nExiting...\n", this->ConfigFileName);
488 this->Log(DEFAULT,"Unable to open config file %s", this->ConfigFileName);
489 Exit(EXIT_STATUS_CONFIG);
492 printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
493 printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
494 printf_c("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special, pippijn, peavey, Burlex\033[0m\n");
495 printf_c("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
497 /* Set the finished argument values */
498 Config->nofork = do_nofork;
499 Config->forcedebug = do_debug;
500 Config->writelog = !do_nolog;
502 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
504 this->OpenLog(argv, argc);
506 this->stats = new serverstats();
507 this->Timers = new TimerManager(this);
508 this->Parser = new CommandParser(this);
509 this->XLines = new XLineManager(this);
510 Config->ClearStack();
511 Config->Read(true, NULL);
517 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
518 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
519 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
520 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
521 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
522 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
523 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
524 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
532 if (!this->DaemonSeed())
534 printf("ERROR: could not go into daemon mode. Shutting down.\n");
535 Log(DEFAULT,"ERROR: could not go into daemon mode. Shutting down.");
536 Exit(EXIT_STATUS_FORK);
541 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
542 * initialize the socket engine.
544 SocketEngineFactory* SEF = new SocketEngineFactory();
545 SE = SEF->Create(this);
548 this->Modes = new ModeParser(this);
549 this->AddServerName(Config->ServerName);
551 int bounditems = BindPorts(true, found_ports, pl);
553 for(int t = 0; t < 255; t++)
554 Config->global_implementation[t] = 0;
556 memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
560 this->Res = new DNS(this);
562 this->LoadAllModules();
563 /* Just in case no modules were loaded - fix for bug #101 */
564 this->BuildISupport();
565 InitializeDisabledCommands(Config->DisabledCommands, this);
567 if ((Config->ports.size() == 0) && (found_ports > 0))
569 printf("\nERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?\n");
570 Log(DEFAULT,"ERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?");
571 Exit(EXIT_STATUS_BIND);
574 if (Config->ports.size() != (unsigned int)found_ports)
576 printf("\nWARNING: Not all your client ports could be bound --\nstarting anyway with %d of %d client ports bound.\n\n", bounditems, found_ports);
577 printf("The following port(s) failed to bind:\n");
579 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
581 printf("%d.\tIP: %s\tPort: %lu\n", j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
587 if (kill(getppid(), SIGTERM) == -1)
589 printf("Error killing parent process: %s\n",strerror(errno));
590 Log(DEFAULT,"Error killing parent process: %s",strerror(errno));
594 if (isatty(0) && isatty(1) && isatty(2))
596 /* We didn't start from a TTY, we must have started from a background process -
597 * e.g. we are restarting, or being launched by cron. Dont kill parent, and dont
608 Log(DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
615 WindowsForkKillOwner(this);
619 printf("\nInspIRCd is now running!\n");
620 Log(DEFAULT,"Startup complete.");
622 this->WritePID(Config->PID);
625 void InspIRCd::DoOneIteration(bool process_module_sockets)
630 static time_t uptime;
631 static struct tm * stime;
632 static char window_title[100];
635 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
636 * Once per loop iteration is pleanty.
641 /* Run background module timers every few seconds
642 * (the docs say modules shouldnt rely on accurate
643 * timing using this event, so we dont have to
644 * time this exactly).
649 WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
650 if ((TIME % 3600) == 0)
652 this->RehashUsersAndChans();
653 FOREACH_MOD_I(this, I_OnGarbageCollect, OnGarbageCollect());
655 Timers->TickTimers(TIME);
656 this->DoBackgroundUserStuff(TIME);
660 XLines->expire_lines();
661 FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
662 Timers->TickMissedTimers(TIME);
665 /* Same change as in cmd_stats.cpp, use RUSAGE_SELF rather than '0' -- Om */
666 if (!getrusage(RUSAGE_SELF, &ru))
668 gettimeofday(&this->stats->LastSampled, NULL);
669 this->stats->LastCPU = ru.ru_utime;
676 uptime = Time() - startup_time;
677 stime = gmtime(&uptime);
678 snprintf(window_title, 100, "InspIRCd - %u clients, %u accepted connections - Up %u days, %.2u:%.2u:%.2u",
679 LocalUserCount(), stats->statsAccept, stime->tm_yday, stime->tm_hour, stime->tm_min, stime->tm_sec);
680 SetConsoleTitle(window_title);
685 /* Call the socket engine to wait on the active
686 * file descriptors. The socket engine has everything's
687 * descriptors in its list... dns, modules, users,
688 * servers... so its nice and easy, just one call.
689 * This will cause any read or write events to be
690 * dispatched to their handlers.
692 this->SE->DispatchEvents();
694 /* if any users was quit, take them out */
695 this->GlobalCulls.Apply();
697 /* If any inspsockets closed, remove them */
698 this->InspSocketCull();
702 this->SignalHandler(s_signal);
708 void InspIRCd::InspSocketCull()
710 for (std::map<InspSocket*,InspSocket*>::iterator x = SocketCull.begin(); x != SocketCull.end(); ++x)
712 SE->DelFd(x->second);
723 DoOneIteration(true);
725 /* This is never reached -- we hope! */
729 /**********************************************************************************/
732 * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
735 int main(int argc, char** argv)
737 SI = new InspIRCd(argc, argv);
738 mysig = &SI->s_signal;
744 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
745 * (until this returns true, a user will block in the waiting state, waiting to connect up to the
746 * registration timeout maximum seconds)
748 bool InspIRCd::AllModulesReportReady(userrec* user)
750 if (!Config->global_implementation[I_OnCheckReady])
753 for (int i = 0; i <= this->GetModuleCount(); i++)
755 if (Config->implement_lists[i][I_OnCheckReady])
757 int res = modules[i]->OnCheckReady(user);
765 int InspIRCd::GetModuleCount()
767 return this->ModCount;
770 time_t InspIRCd::Time(bool delta)
773 return TIME + time_delta;
777 int InspIRCd::SetTimeDelta(int delta)
779 int old = time_delta;
781 this->Log(DEBUG, "Time delta set to %d (was %d)", time_delta, old);
785 void InspIRCd::AddLocalClone(userrec* user)
787 clonemap::iterator x = local_clones.find(user->GetIPString());
788 if (x != local_clones.end())
791 local_clones[user->GetIPString()] = 1;
794 void InspIRCd::AddGlobalClone(userrec* user)
796 clonemap::iterator y = global_clones.find(user->GetIPString());
797 if (y != global_clones.end())
800 global_clones[user->GetIPString()] = 1;
803 int InspIRCd::GetTimeDelta()
808 void InspIRCd::SetSignal(int signal)