2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2012 William Pitcock <nenolod@dereferenced.org>
5 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
6 * Copyright (C) 2003-2008 Craig Edwards <craigedwards@brainbox.cc>
7 * Copyright (C) 2008 Uli Schlachter <psychon@znc.in>
8 * Copyright (C) 2006-2008 Robin Burchell <robin+git@viroteck.net>
9 * Copyright (C) 2006-2007 Oliver Lupton <oliverlupton@gmail.com>
10 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
11 * Copyright (C) 2007 Burlex <???@???>
12 * Copyright (C) 2003 Craig McLure <craig@chatspike.net>
13 * Copyright (C) 2003 randomdan <???@???>
15 * This file is part of InspIRCd. InspIRCd is free software: you can
16 * redistribute it and/or modify it under the terms of the GNU General Public
17 * License as published by the Free Software Foundation, version 2.
19 * This program is distributed in the hope that it will be useful, but WITHOUT
20 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
21 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
24 * You should have received a copy of the GNU General Public License
25 * along with this program. If not, see <http://www.gnu.org/licenses/>.
34 #include <sys/resource.h>
37 #include <pwd.h> // setuid
38 #include <grp.h> // setgid
40 WORD g_wOriginalColors;
41 WORD g_wBackgroundColor;
48 #include "exitcodes.h"
50 InspIRCd* ServerInstance = NULL;
52 /** Seperate from the other casemap tables so that code *can* still exclusively rely on RFC casemapping
55 * This is provided as a pointer so that modules can change it to their custom mapping tables,
56 * e.g. for national character support.
58 unsigned const char *national_case_insensitive_map = rfc_case_insensitive_map;
61 /* Moved from exitcodes.h -- due to duplicate symbols -- Burlex
62 * XXX this is a bit ugly. -- w00t
64 const char* ExitCodes[] =
68 "Config file error", // 2
70 "POSIX fork failed", // 4
71 "Bad commandline parameters", // 5
72 "Can't write PID file", // 6
73 "SocketEngine could not initialize", // 7
74 "Refusing to start up as root", // 8
75 "Couldn't load module on startup", // 9
76 "Received SIGTERM" // 10
81 void VoidSignalHandler(int);
83 // Collects performance statistics for the STATS command.
88 if (getrusage(RUSAGE_SELF, &ru) == -1)
89 return; // Should never happen.
91 ServerInstance->stats.LastSampled.tv_sec = ServerInstance->Time();
92 ServerInstance->stats.LastSampled.tv_nsec = ServerInstance->Time_ns();
93 ServerInstance->stats.LastCPU = ru.ru_utime;
95 if (!QueryPerformanceCounter(&ServerInstance->stats.LastSampled))
96 return; // Should never happen.
98 FILETIME CreationTime;
102 GetProcessTimes(GetCurrentProcess(), &CreationTime, &ExitTime, &KernelTime, &UserTime);
104 ServerInstance->stats.LastCPU.dwHighDateTime = KernelTime.dwHighDateTime + UserTime.dwHighDateTime;
105 ServerInstance->stats.LastCPU.dwLowDateTime = KernelTime.dwLowDateTime + UserTime.dwLowDateTime;
109 // Deletes a pointer and then zeroes it.
111 void DeleteZero(T*& pr)
118 // Drops to the unprivileged user/group specified in <security:runas{user,group}>.
122 ConfigTag* security = ServerInstance->Config->ConfValue("security");
124 const std::string SetGroup = security->getString("runasgroup");
125 if (!SetGroup.empty())
128 if (setgroups(0, NULL) == -1)
130 ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "setgroups() failed (wtf?): %s", strerror(errno));
131 exit(EXIT_STATUS_CONFIG);
134 struct group* g = getgrnam(SetGroup.c_str());
137 ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "getgrnam(%s) failed (wrong group?): %s", SetGroup.c_str(), strerror(errno));
138 exit(EXIT_STATUS_CONFIG);
141 if (setgid(g->gr_gid) == -1)
143 ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "setgid(%d) failed (wrong group?): %s", g->gr_gid, strerror(errno));
144 exit(EXIT_STATUS_CONFIG);
148 const std::string SetUser = security->getString("runasuser");
149 if (!SetUser.empty())
152 struct passwd* u = getpwnam(SetUser.c_str());
155 ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "getpwnam(%s) failed (wrong user?): %s", SetUser.c_str(), strerror(errno));
156 exit(EXIT_STATUS_CONFIG);
159 if (setuid(u->pw_uid) == -1)
161 ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "setuid(%d) failed (wrong user?): %s", u->pw_uid, strerror(errno));
162 exit(EXIT_STATUS_CONFIG);
168 // Attempts to fork into the background.
169 bool ForkIntoBackground()
172 // We use VoidSignalHandler whilst forking to avoid breaking daemon scripts
173 // if the parent process exits with SIGTERM (15) instead of EXIT_STATUS_NOERROR (0).
174 signal(SIGTERM, VoidSignalHandler);
177 int childpid = fork();
180 ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "fork() failed: %s", strerror(errno));
183 else if (childpid > 0)
185 // Wait until the child process kills the parent so that the shell prompt
186 // doesnt display over the output. Sending a kill with a signal of 0 just
187 // checks that the child pid is still running. If it is not then an error
188 // happened and the parent should exit.
189 while (kill(childpid, 0) != -1)
191 exit(EXIT_STATUS_NOERROR);
196 signal(SIGTERM, InspIRCd::SetSignal);
197 SocketEngine::RecoverFromFork();
203 // Increase the size of a core dump file to improve debugging problems.
204 void IncreaseCoreDumpSize()
209 if (getrlimit(RLIMIT_CORE, &rl) == -1)
211 ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "Unable to increase core dump size: getrlimit(RLIMIT_CORE) failed: %s", strerror(errno));
215 rl.rlim_cur = rl.rlim_max;
216 if (setrlimit(RLIMIT_CORE, &rl) == -1)
217 ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "Unable to increase core dump size: setrlimit(RLIMIT_CORE) failed: %s", strerror(errno));
221 // Seeds the random number generator if applicable.
222 void SeedRng(timespec ts)
225 srand(ts.tv_nsec ^ ts.tv_sec);
226 #elif !defined HAS_ARC4RANDOM_BUF
227 srandom(ts.tv_nsec ^ ts.tv_sec);
231 // Sets handlers for various process signals.
235 signal(SIGALRM, SIG_IGN);
236 signal(SIGCHLD, SIG_IGN);
237 signal(SIGHUP, InspIRCd::SetSignal);
238 signal(SIGPIPE, SIG_IGN);
239 signal(SIGUSR1, SIG_IGN);
240 signal(SIGUSR2, SIG_IGN);
241 signal(SIGXFSZ, SIG_IGN);
243 signal(SIGTERM, InspIRCd::SetSignal);
246 // Required for returning the proper value of EXIT_SUCCESS for the parent process.
247 void VoidSignalHandler(int)
249 exit(EXIT_STATUS_NOERROR);
253 void InspIRCd::Cleanup()
255 // Close all listening sockets
256 for (unsigned int i = 0; i < ports.size(); i++)
263 // Tell modules that we're shutting down.
264 const std::string quitmsg = "Server shutting down";
265 FOREACH_MOD(OnShutdown, (quitmsg));
267 // Disconnect all local users
268 const UserManager::LocalList& list = Users.GetLocalUsers();
269 while (!list.empty())
270 ServerInstance->Users.QuitUser(list.front(), quitmsg);
273 Modules->UnloadAll();
275 /* Delete objects dynamically allocated in constructor (destructor would be more appropriate, but we're likely exiting) */
276 /* Must be deleted before modes as it decrements modelines */
279 delete FakeClient->server;
282 DeleteZero(this->FakeClient);
283 DeleteZero(this->XLines);
284 DeleteZero(this->Config);
285 SocketEngine::Deinit();
289 void InspIRCd::WritePID(const std::string& filename, bool exitonfail)
292 if (!ServerInstance->Config->cmdline.writepid)
294 this->Logs->Log("STARTUP", LOG_DEFAULT, "--nopid specified on command line; PID file not written.");
298 std::string fname = ServerInstance->Config->Paths.PrependData(filename.empty() ? "inspircd.pid" : filename);
299 std::ofstream outfile(fname.c_str());
300 if (outfile.is_open())
308 std::cout << "Failed to write PID-file '" << fname << "', exiting." << std::endl;
309 this->Logs->Log("STARTUP", LOG_DEFAULT, "Failed to write PID-file '%s'%s", fname.c_str(), (exitonfail ? ", exiting." : ""));
311 Exit(EXIT_STATUS_PID);
316 InspIRCd::InspIRCd(int argc, char** argv)
318 , ConfigFileName(INSPIRCD_CONFIG_PATH "/inspircd.conf")
322 , PI(&DefaultProtocolInterface)
323 , GenRandom(&DefaultGenRandom)
324 , IsChannel(&DefaultIsChannel)
325 , IsNick(&DefaultIsNick)
326 , IsIdent(&DefaultIsIdent)
328 ServerInstance = this;
331 this->startup_time = TIME.tv_sec;
333 IncreaseCoreDumpSize();
335 SocketEngine::Init();
337 this->Config = new ServerConfig;
338 dynamic_reference_base::reset_all();
339 this->XLines = new XLineManager;
341 this->Config->cmdline.argv = argv;
342 this->Config->cmdline.argc = argc;
345 // Initialize the console values
346 g_hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
347 CONSOLE_SCREEN_BUFFER_INFO bufinf;
348 if(GetConsoleScreenBufferInfo(g_hStdout, &bufinf))
350 g_wOriginalColors = bufinf.wAttributes & 0x00FF;
351 g_wBackgroundColor = bufinf.wAttributes & 0x00F0;
355 g_wOriginalColors = FOREGROUND_RED|FOREGROUND_BLUE|FOREGROUND_GREEN;
356 g_wBackgroundColor = 0;
361 ServiceProvider* provs[] =
363 &rfcevents.numeric, &rfcevents.join, &rfcevents.part, &rfcevents.kick, &rfcevents.quit, &rfcevents.nick,
364 &rfcevents.mode, &rfcevents.topic, &rfcevents.privmsg, &rfcevents.invite, &rfcevents.ping, &rfcevents.pong,
367 Modules.AddServices(provs, sizeof(provs)/sizeof(provs[0]));
370 // Flag variables passed to getopt_long() later
371 int do_version = 0, do_nofork = 0, do_debug = 0,
372 do_nolog = 0, do_nopid = 0, do_root = 0;
373 struct option longopts[] =
375 { "nofork", no_argument, &do_nofork, 1 },
376 { "config", required_argument, NULL, 'c' },
377 { "debug", no_argument, &do_debug, 1 },
378 { "nolog", no_argument, &do_nolog, 1 },
379 { "nopid", no_argument, &do_nopid, 1 },
380 { "runasroot", no_argument, &do_root, 1 },
381 { "version", no_argument, &do_version, 1 },
387 while ((c = getopt_long(argc, argv, ":c:", longopts, &index)) != -1)
392 /* Config filename was set */
393 ConfigFileName = optarg;
395 TCHAR configPath[MAX_PATH + 1];
396 if (GetFullPathName(optarg, MAX_PATH, configPath, NULL) > 0)
397 ConfigFileName = configPath;
399 char configPath[PATH_MAX + 1];
400 if (realpath(optarg, configPath))
401 ConfigFileName = configPath;
405 /* getopt_long_only() set an int variable, just keep going */
408 /* Unknown parameter */
410 /* Fall through to handle other weird values too */
411 std::cout << "Unknown parameter '" << argv[optind-1] << "'" << std::endl;
412 std::cout << "Usage: " << argv[0] << " [--nofork] [--nolog] [--nopid] [--debug] [--config <config>]" << std::endl <<
413 std::string(static_cast<size_t>(8+strlen(argv[0])), ' ') << "[--runasroot] [--version]" << std::endl;
414 Exit(EXIT_STATUS_ARGV);
421 std::cout << std::endl << INSPIRCD_VERSION << std::endl;
422 Exit(EXIT_STATUS_NOERROR);
428 WSAStartup(MAKEWORD(2,2), &wsadata);
431 /* Set the finished argument values */
432 Config->cmdline.nofork = (do_nofork != 0);
433 Config->cmdline.forcedebug = (do_debug != 0);
434 Config->cmdline.writelog = !do_nolog;
435 Config->cmdline.writepid = !do_nopid;
439 FileWriter* fw = new FileWriter(stdout, 1);
440 FileLogStream* fls = new FileLogStream(LOG_RAWIO, fw);
441 Logs->AddLogTypes("*", fls, true);
444 if (!FileSystem::FileExists(ConfigFileName))
447 /* Windows can (and defaults to) hide file extensions, so let's play a bit nice for windows users. */
448 std::string txtconf = this->ConfigFileName;
449 txtconf.append(".txt");
451 if (FileSystem::FileExists(txtconf))
453 ConfigFileName = txtconf;
458 std::cout << "ERROR: Cannot open config file: " << ConfigFileName << std::endl << "Exiting..." << std::endl;
459 this->Logs->Log("STARTUP", LOG_DEFAULT, "Unable to open config file %s", ConfigFileName.c_str());
460 Exit(EXIT_STATUS_CONFIG);
464 std::cout << con_green << "InspIRCd - Internet Relay Chat Daemon" << con_reset << std::endl;
465 std::cout << "For contributors & authors: " << con_green << "See /INFO Output" << con_reset << std::endl;
472 std::cout << "* WARNING * WARNING * WARNING * WARNING * WARNING *" << std::endl
473 << "YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED" << std::endl
474 << "AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED" << std::endl
475 << "OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR" << std::endl
476 << "SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN" << std::endl
477 << "TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART" << std::endl
478 << "THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!" << std::endl << std::endl
479 << "InspIRCd starting in 20 seconds, ctrl+c to abort..." << std::endl;
486 if (!Config->cmdline.nofork && !ForkIntoBackground())
488 std::cout << "ERROR: could not go into daemon mode. Shutting down." << std::endl;
489 Logs->Log("STARTUP", LOG_DEFAULT, "ERROR: could not go into daemon mode. Shutting down.");
490 Exit(EXIT_STATUS_FORK);
493 std::cout << "InspIRCd Process ID: " << con_green << getpid() << con_reset << std::endl;
495 /* During startup we read the configuration now, not in
498 this->Config->Read();
499 this->Config->Apply(NULL, "");
500 Logs->OpenFileLogs();
502 // If we don't have a SID, generate one based on the server name and the server description
503 if (Config->sid.empty())
504 Config->sid = UIDGenerator::GenerateSID(Config->ServerName, Config->ServerDesc);
506 // Initialize the UID generator with our sid
507 this->UIDGen.init(Config->sid);
509 // Create the server user for this server
510 this->FakeClient = new FakeUser(Config->sid, Config->ServerName, Config->ServerDesc);
512 // This is needed as all new XLines are marked pending until ApplyLines() is called
513 this->XLines->ApplyLines();
516 int bounditems = BindPorts(pl);
518 std::cout << std::endl;
520 this->Modules->LoadAll();
522 // Build ISupport as ModuleManager::LoadAll() does not do it
523 this->ISupport.Build();
527 std::cout << std::endl << "WARNING: Not all your client ports could be bound -- " << std::endl << "starting anyway with " << bounditems
528 << " of " << bounditems + (int)pl.size() << " client ports bound." << std::endl << std::endl;
529 std::cout << "The following port(s) failed to bind:" << std::endl << std::endl;
531 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
533 std::cout << j << ".\tAddress: " << i->first.str() << " \tReason: " << strerror(i->second) << std::endl;
536 std::cout << std::endl << "Hint: Try using a public IP instead of blank or *" << std::endl;
539 std::cout << "InspIRCd is now running as '" << Config->ServerName << "'[" << Config->GetSID() << "] with " << SocketEngine::GetMaxFds() << " max open sockets" << std::endl;
542 if (!Config->cmdline.nofork)
544 if (kill(getppid(), SIGTERM) == -1)
546 std::cout << "Error killing parent process: " << strerror(errno) << std::endl;
547 Logs->Log("STARTUP", LOG_DEFAULT, "Error killing parent process: %s",strerror(errno));
551 /* Explicitly shut down stdio's stdin/stdout/stderr.
553 * The previous logic here was to only do this if stdio was connected to a controlling
554 * terminal. However, we must do this always to avoid information leaks and other
555 * problems related to stdio.
557 * The only exception is if we are in debug mode.
561 if ((!do_nofork) && (!Config->cmdline.forcedebug))
563 int fd = open("/dev/null", O_RDWR);
569 if (dup2(fd, STDIN_FILENO) < 0)
570 Logs->Log("STARTUP", LOG_DEFAULT, "Failed to dup /dev/null to stdin.");
571 if (dup2(fd, STDOUT_FILENO) < 0)
572 Logs->Log("STARTUP", LOG_DEFAULT, "Failed to dup /dev/null to stdout.");
573 if (dup2(fd, STDERR_FILENO) < 0)
574 Logs->Log("STARTUP", LOG_DEFAULT, "Failed to dup /dev/null to stderr.");
579 Logs->Log("STARTUP", LOG_DEFAULT, "Keeping pseudo-tty open as we are running in the foreground.");
582 /* Set win32 service as running, if we are running as a service */
591 QueryPerformanceFrequency(&stats.QPFrequency);
594 WritePID(Config->PID);
597 Logs->Log("STARTUP", LOG_DEFAULT, "Startup complete as '%s'[%s], %lu max open sockets", Config->ServerName.c_str(),Config->GetSID().c_str(), SocketEngine::GetMaxFds());
600 void InspIRCd::UpdateTime()
602 #if defined HAS_CLOCK_GETTIME
603 clock_gettime(CLOCK_REALTIME, &TIME);
608 TIME.tv_sec = time(NULL);
609 TIME.tv_nsec = st.wMilliseconds;
612 gettimeofday(&tv, NULL);
614 TIME.tv_sec = tv.tv_sec;
615 TIME.tv_nsec = tv.tv_usec * 1000;
622 time_t OLDTIME = TIME.tv_sec;
626 /* Check if there is a config thread which has finished executing but has not yet been freed */
627 if (this->ConfigThread && this->ConfigThread->IsDone())
629 /* Rehash has completed */
630 this->Logs->Log("CONFIG", LOG_DEBUG, "Detected ConfigThread exiting, tidying up...");
632 this->ConfigThread->Finish();
634 ConfigThread->join();
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).
646 if (TIME.tv_sec != OLDTIME)
650 if (Config->TimeSkipWarn)
652 time_t timediff = TIME.tv_sec - OLDTIME;
654 if (timediff > Config->TimeSkipWarn)
655 SNO->WriteToSnoMask('a', "\002Performance warning!\002 Server clock jumped forwards by %lu seconds!", timediff);
657 else if (timediff < -Config->TimeSkipWarn)
658 SNO->WriteToSnoMask('a', "\002Performance warning!\002 Server clock jumped backwards by %lu seconds!", labs(timediff));
661 OLDTIME = TIME.tv_sec;
663 if ((TIME.tv_sec % 3600) == 0)
664 FOREACH_MOD(OnGarbageCollect, ());
666 Timers.TickTimers(TIME.tv_sec);
667 Users->DoBackgroundUserStuff();
669 if ((TIME.tv_sec % 5) == 0)
671 FOREACH_MOD(OnBackgroundTimer, (TIME.tv_sec));
672 SNO->FlushSnotices();
676 /* Call the socket engine to wait on the active
677 * file descriptors. The socket engine has everything's
678 * descriptors in its list... dns, modules, users,
679 * servers... so its nice and easy, just one call.
680 * This will cause any read or write events to be
681 * dispatched to their handlers.
683 SocketEngine::DispatchTrialWrites();
684 SocketEngine::DispatchEvents();
686 /* if any users were quit, take them out */
692 this->SignalHandler(s_signal);
698 sig_atomic_t InspIRCd::s_signal = 0;
700 void InspIRCd::SetSignal(int signal)
705 /* On posix systems, the flow of the program starts right here, with
706 * ENTRYPOINT being a #define that defines main(). On Windows, ENTRYPOINT
707 * defines smain() and the real main() is in the service code under
708 * win32service.cpp. This allows the service control manager to control
709 * the process where we are running as a windows service.
713 new InspIRCd(argc, argv);
714 ServerInstance->Run();
715 delete ServerInstance;