]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
Extract time skip warning code to a static function.
[user/henk/code/inspircd.git] / src / inspircd.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2018 Chris Novakovic <chrisnovakovic@users.noreply.github.com>
5  *   Copyright (C) 2013, 2017-2020 Sadie Powell <sadie@witchery.services>
6  *   Copyright (C) 2013 Adam <Adam@anope.org>
7  *   Copyright (C) 2012-2014, 2016, 2018 Attila Molnar <attilamolnar@hush.com>
8  *   Copyright (C) 2012 William Pitcock <nenolod@dereferenced.org>
9  *   Copyright (C) 2012 Robby <robby@chatbelgie.be>
10  *   Copyright (C) 2012 ChrisTX <xpipe@hotmail.de>
11  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
12  *   Copyright (C) 2009 Uli Schlachter <psychon@inspircd.org>
13  *   Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
14  *   Copyright (C) 2007-2008, 2010 Craig Edwards <brain@inspircd.org>
15  *   Copyright (C) 2007-2008 Robin Burchell <robin+git@viroteck.net>
16  *   Copyright (C) 2007 Oliver Lupton <om@inspircd.org>
17  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
18  *
19  * This file is part of InspIRCd.  InspIRCd is free software: you can
20  * redistribute it and/or modify it under the terms of the GNU General Public
21  * License as published by the Free Software Foundation, version 2.
22  *
23  * This program is distributed in the hope that it will be useful, but WITHOUT
24  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
25  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
26  * details.
27  *
28  * You should have received a copy of the GNU General Public License
29  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
30  */
31
32
33 #include "inspircd.h"
34 #include <signal.h>
35
36 #ifndef _WIN32
37         #include <unistd.h>
38         #include <sys/resource.h>
39         #include <getopt.h>
40         #include <pwd.h> // setuid
41         #include <grp.h> // setgid
42 #else
43         WORD g_wOriginalColors;
44         WORD g_wBackgroundColor;
45         HANDLE g_hStdout;
46 #endif
47
48 #include <fstream>
49 #include <iostream>
50 #include "xline.h"
51 #include "exitcodes.h"
52
53 InspIRCd* ServerInstance = NULL;
54
55 /** Seperate from the other casemap tables so that code *can* still exclusively rely on RFC casemapping
56  * if it must.
57  *
58  * This is provided as a pointer so that modules can change it to their custom mapping tables,
59  * e.g. for national character support.
60  */
61 unsigned const char *national_case_insensitive_map = rfc_case_insensitive_map;
62
63
64 /* Moved from exitcodes.h -- due to duplicate symbols -- Burlex
65  * XXX this is a bit ugly. -- w00t
66  */
67 const char* ExitCodes[] =
68 {
69                 "No error",                                                             // 0
70                 "DIE command",                                                  // 1
71                 "Config file error",                                    // 2
72                 "Logfile error",                                                // 3
73                 "POSIX fork failed",                                    // 4
74                 "Bad commandline parameters",                   // 5
75                 "Can't write PID file",                                 // 6
76                 "SocketEngine could not initialize",    // 7
77                 "Refusing to start up as root",                 // 8
78                 "Couldn't load module on startup",              // 9
79                 "Received SIGTERM"                                              // 10
80 };
81
82 namespace
83 {
84         void VoidSignalHandler(int);
85
86         // Warns a user running as root that they probably shouldn't.
87         void CheckRoot()
88         {
89 #ifndef _WIN32
90                 if (getegid() != 0 && geteuid() != 0)
91                         return;
92
93                 std::cout << con_red << "Warning!" << con_reset << " You have started as root. Running as root is generally not required" << std::endl
94                         << "and may allow an attacker to gain access to your system if they find a way to" << std::endl
95                         << "exploit your IRC server." << std::endl
96                         << std::endl;
97                 if (isatty(fileno(stdout)))
98                 {
99                         std::cout << "InspIRCd will start in 30 seconds. If you are sure that you need to run as root" << std::endl
100                                 << "then you can pass the " << con_bright << "--runasroot" << con_reset << " option to disable this wait." << std::endl;
101                         sleep(30);
102                 }
103                 else
104                 {
105                         std::cout << "If you are sure that you need to run as root then you can pass the " << con_bright << "--runasroot" << con_reset << std::endl
106                                 << "option to disable this error." << std::endl;
107                                 ServerInstance->Exit(EXIT_STATUS_ROOT);
108                 }
109 #endif
110         }
111
112         // Collects performance statistics for the STATS command.
113         void CollectStats()
114         {
115 #ifndef _WIN32
116                 static rusage ru;
117                 if (getrusage(RUSAGE_SELF, &ru) == -1)
118                         return; // Should never happen.
119
120                 ServerInstance->stats.LastSampled.tv_sec = ServerInstance->Time();
121                 ServerInstance->stats.LastSampled.tv_nsec = ServerInstance->Time_ns();
122                 ServerInstance->stats.LastCPU = ru.ru_utime;
123 #else
124                 if (!QueryPerformanceCounter(&ServerInstance->stats.LastSampled))
125                         return; // Should never happen.
126
127                 FILETIME CreationTime;
128                 FILETIME ExitTime;
129                 FILETIME KernelTime;
130                 FILETIME UserTime;
131                 GetProcessTimes(GetCurrentProcess(), &CreationTime, &ExitTime, &KernelTime, &UserTime);
132
133                 ServerInstance->stats.LastCPU.dwHighDateTime = KernelTime.dwHighDateTime + UserTime.dwHighDateTime;
134                 ServerInstance->stats.LastCPU.dwLowDateTime = KernelTime.dwLowDateTime + UserTime.dwLowDateTime;
135 #endif
136         }
137
138         // Checks whether the server clock has skipped too much and warn about it if it has.
139         void CheckTimeSkip(time_t oldtime, time_t newtime)
140         {
141                 if (!ServerInstance->Config->TimeSkipWarn)
142                         return;
143
144                 time_t timediff = oldtime - newtime;
145
146                 if (timediff > ServerInstance->Config->TimeSkipWarn)
147                         ServerInstance->SNO->WriteToSnoMask('a', "\002Performance warning!\002 Server clock jumped forwards by %lu seconds!", timediff);
148
149                 else if (timediff < -ServerInstance->Config->TimeSkipWarn)
150                         ServerInstance->SNO->WriteToSnoMask('a', "\002Performance warning!\002 Server clock jumped backwards by %lu seconds!", labs(timediff));
151         }
152
153         // Drops to the unprivileged user/group specified in <security:runas{user,group}>.
154         void DropRoot()
155         {
156 #ifndef _WIN32
157                 ConfigTag* security = ServerInstance->Config->ConfValue("security");
158
159                 const std::string SetGroup = security->getString("runasgroup");
160                 if (!SetGroup.empty())
161                 {
162                         errno = 0;
163                         if (setgroups(0, NULL) == -1)
164                         {
165                                 ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "setgroups() failed (wtf?): %s", strerror(errno));
166                                 exit(EXIT_STATUS_CONFIG);
167                         }
168
169                         struct group* g = getgrnam(SetGroup.c_str());
170                         if (!g)
171                         {
172                                 ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "getgrnam(%s) failed (wrong group?): %s", SetGroup.c_str(), strerror(errno));
173                                 exit(EXIT_STATUS_CONFIG);
174                         }
175
176                         if (setgid(g->gr_gid) == -1)
177                         {
178                                 ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "setgid(%d) failed (wrong group?): %s", g->gr_gid, strerror(errno));
179                                 exit(EXIT_STATUS_CONFIG);
180                         }
181                 }
182
183                 const std::string SetUser = security->getString("runasuser");
184                 if (!SetUser.empty())
185                 {
186                         errno = 0;
187                         struct passwd* u = getpwnam(SetUser.c_str());
188                         if (!u)
189                         {
190                                 ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "getpwnam(%s) failed (wrong user?): %s", SetUser.c_str(), strerror(errno));
191                                 exit(EXIT_STATUS_CONFIG);
192                         }
193
194                         if (setuid(u->pw_uid) == -1)
195                         {
196                                 ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "setuid(%d) failed (wrong user?): %s", u->pw_uid, strerror(errno));
197                                 exit(EXIT_STATUS_CONFIG);
198                         }
199                 }
200 #endif
201         }
202
203         // Expands a path relative to the current working directory.
204         std::string ExpandPath(const char* path)
205         {
206 #ifdef _WIN32
207                 TCHAR configPath[MAX_PATH + 1];
208                 if (GetFullPathName(path, MAX_PATH, configPath, NULL) > 0)
209                         return configPath;
210 #else
211                 char configPath[PATH_MAX + 1];
212                 if (realpath(path, configPath))
213                         return configPath;
214 #endif
215                 return path;
216         }
217
218         // Locates a config file on the file system.
219         bool FindConfigFile(std::string& path)
220         {
221                 if (FileSystem::FileExists(path))
222                         return true;
223
224 #ifdef _WIN32
225                 // Windows hides file extensions by default so try appending .txt to the path
226                 // to help users who have that feature enabled and can't create .conf files.
227                 const std::string txtpath = path + ".txt";
228                 if (FileSystem::FileExists(txtpath))
229                 {
230                         path.assign(txtpath);
231                         return true;
232                 }
233 #endif
234                 return false;
235         }
236
237         // Attempts to fork into the background.
238         void ForkIntoBackground()
239         {
240 #ifndef _WIN32
241                 // We use VoidSignalHandler whilst forking to avoid breaking daemon scripts
242                 // if the parent process exits with SIGTERM (15) instead of EXIT_STATUS_NOERROR (0).
243                 signal(SIGTERM, VoidSignalHandler);
244
245                 errno = 0;
246                 int childpid = fork();
247                 if (childpid < 0)
248                 {
249                         ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "fork() failed: %s", strerror(errno));
250                         std::cout << con_red << "Error:" << con_reset << " unable to fork into background: " << strerror(errno);
251                         ServerInstance->Exit(EXIT_STATUS_FORK);
252                 }
253                 else if (childpid > 0)
254                 {
255                         // Wait until the child process kills the parent so that the shell prompt
256                         // doesnt display over the output. Sending a kill with a signal of 0 just
257                         // checks that the child pid is still running. If it is not then an error
258                         // happened and the parent should exit.
259                         while (kill(childpid, 0) != -1)
260                                 sleep(1);
261                         exit(EXIT_STATUS_NOERROR);
262                 }
263                 else
264                 {
265                         setsid();
266                         signal(SIGTERM, InspIRCd::SetSignal);
267                         SocketEngine::RecoverFromFork();
268                 }
269 #endif
270         }
271
272         // Increase the size of a core dump file to improve debugging problems.
273         void IncreaseCoreDumpSize()
274         {
275 #ifndef _WIN32
276                 errno = 0;
277                 rlimit rl;
278                 if (getrlimit(RLIMIT_CORE, &rl) == -1)
279                 {
280                         ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "Unable to increase core dump size: getrlimit(RLIMIT_CORE) failed: %s", strerror(errno));
281                         return;
282                 }
283
284                 rl.rlim_cur = rl.rlim_max;
285                 if (setrlimit(RLIMIT_CORE, &rl) == -1)
286                         ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "Unable to increase core dump size: setrlimit(RLIMIT_CORE) failed: %s", strerror(errno));
287 #endif
288         }
289
290         // Parses the command line options.
291         void ParseOptions()
292         {
293                 int do_debug = 0, do_nofork = 0,    do_nolog = 0;
294                 int do_nopid = 0, do_runasroot = 0, do_version = 0;
295                 struct option longopts[] =
296                 {
297                         { "config",    required_argument, NULL,          'c' },
298                         { "debug",     no_argument,       &do_debug,     1 },
299                         { "nofork",    no_argument,       &do_nofork,    1 },
300                         { "nolog",     no_argument,       &do_nolog,     1 },
301                         { "nopid",     no_argument,       &do_nopid,     1 },
302                         { "runasroot", no_argument,       &do_runasroot, 1 },
303                         { "version",   no_argument,       &do_version,   1 },
304                         { 0, 0, 0, 0 }
305                 };
306
307                 char** argv = ServerInstance->Config->cmdline.argv;
308                 int ret;
309                 while ((ret = getopt_long(ServerInstance->Config->cmdline.argc, argv, ":c:", longopts, NULL)) != -1)
310                 {
311                         switch (ret)
312                         {
313                                 case 0:
314                                         // A long option was specified.
315                                         break;
316
317                                 case 'c':
318                                         // The -c option was specified.
319                                         ServerInstance->ConfigFileName = ExpandPath(optarg);
320                                         break;
321
322                                 default:
323                                         // An unknown option was specified.
324                                         std::cout << con_red << "Error:" <<  con_reset << " unknown option '" << argv[optind - 1] << "'." << std::endl
325                                                 << con_bright << "Usage: " << con_reset << argv[0] << " [--config <file>] [--debug] [--nofork] [--nolog]" << std::endl
326                                                 << std::string(strlen(argv[0]) + 8, ' ') << "[--nopid] [--runasroot] [--version]" << std::endl;
327                                         ServerInstance->Exit(EXIT_STATUS_ARGV);
328                                         break;
329                         }
330                 }
331
332                 if (do_version)
333                 {
334                         std::cout << std::endl << INSPIRCD_VERSION << std::endl;
335                         ServerInstance->Exit(EXIT_STATUS_NOERROR);
336                 }
337
338                 // Store the relevant parsed arguments
339                 ServerInstance->Config->cmdline.forcedebug = !!do_debug;
340                 ServerInstance->Config->cmdline.nofork = !!do_nofork;
341                 ServerInstance->Config->cmdline.runasroot = !!do_runasroot;
342                 ServerInstance->Config->cmdline.writelog = !do_nolog;
343                 ServerInstance->Config->cmdline.writepid = !do_nopid;
344         }
345         // Seeds the random number generator if applicable.
346         void SeedRng(timespec ts)
347         {
348 #if defined _WIN32
349                 srand(ts.tv_nsec ^ ts.tv_sec);
350 #elif !defined HAS_ARC4RANDOM_BUF
351                 srandom(ts.tv_nsec ^ ts.tv_sec);
352 #endif
353         }
354
355         // Sets handlers for various process signals.
356         void SetSignals()
357         {
358 #ifndef _WIN32
359                 signal(SIGALRM, SIG_IGN);
360                 signal(SIGCHLD, SIG_IGN);
361                 signal(SIGHUP, InspIRCd::SetSignal);
362                 signal(SIGPIPE, SIG_IGN);
363                 signal(SIGUSR1, SIG_IGN);
364                 signal(SIGUSR2, SIG_IGN);
365                 signal(SIGXFSZ, SIG_IGN);
366 #endif
367                 signal(SIGTERM, InspIRCd::SetSignal);
368         }
369
370         void TryBindPorts()
371         {
372                 FailedPortList pl;
373                 ServerInstance->BindPorts(pl);
374
375                 if (!pl.empty())
376                 {
377                         std::cout << con_red << "Warning!" << con_reset << " Some of your listener" << (pl.size() == 1 ? "s" : "") << " failed to bind:" << std::endl
378                                 << std::endl;
379
380                         for (FailedPortList::const_iterator iter = pl.begin(); iter != pl.end(); ++iter)
381                         {
382                                 const FailedPort& fp = *iter;
383                                 std::cout << "  " << con_bright << fp.sa.str() << con_reset << ": " << strerror(fp.error) << '.' << std::endl
384                                         << "  " << "Created from <bind> tag at " << fp.tag->getTagLocation() << std::endl
385                                         << std::endl;
386                         }
387
388                         std::cout << con_bright << "Hints:" << con_reset << std::endl
389                                 << "- For TCP/IP listeners try using a public IP address in <bind:address> instead" << std::endl
390                                 << "  of * of leaving it blank." << std::endl
391                                 << "- For UNIX socket listeners try enabling <bind:rewrite> to replace old sockets." << std::endl;
392                 }
393         }
394
395         // Required for returning the proper value of EXIT_SUCCESS for the parent process.
396         void VoidSignalHandler(int)
397         {
398                 exit(EXIT_STATUS_NOERROR);
399         }
400 }
401
402 void InspIRCd::Cleanup()
403 {
404         // Close all listening sockets
405         for (unsigned int i = 0; i < ports.size(); i++)
406         {
407                 ports[i]->cull();
408                 delete ports[i];
409         }
410         ports.clear();
411
412         // Tell modules that we're shutting down.
413         const std::string quitmsg = "Server shutting down";
414         FOREACH_MOD(OnShutdown, (quitmsg));
415
416         // Disconnect all local users
417         const UserManager::LocalList& list = Users.GetLocalUsers();
418         while (!list.empty())
419                 ServerInstance->Users.QuitUser(list.front(), quitmsg);
420
421         GlobalCulls.Apply();
422         Modules->UnloadAll();
423
424         /* Delete objects dynamically allocated in constructor (destructor would be more appropriate, but we're likely exiting) */
425         /* Must be deleted before modes as it decrements modelines */
426         if (FakeClient)
427         {
428                 delete FakeClient->server;
429                 FakeClient->cull();
430         }
431         stdalgo::delete_zero(this->FakeClient);
432         stdalgo::delete_zero(this->XLines);
433         stdalgo::delete_zero(this->Config);
434         SocketEngine::Deinit();
435         Logs->CloseLogs();
436 }
437
438 void InspIRCd::WritePID(const std::string& filename, bool exitonfail)
439 {
440 #ifndef _WIN32
441         if (!ServerInstance->Config->cmdline.writepid)
442         {
443                 this->Logs->Log("STARTUP", LOG_DEFAULT, "--nopid specified on command line; PID file not written.");
444                 return;
445         }
446
447         std::string fname = ServerInstance->Config->Paths.PrependData(filename.empty() ? "inspircd.pid" : filename);
448         std::ofstream outfile(fname.c_str());
449         if (outfile.is_open())
450         {
451                 outfile << getpid();
452                 outfile.close();
453         }
454         else
455         {
456                 if (exitonfail)
457                         std::cout << "Failed to write PID-file '" << fname << "', exiting." << std::endl;
458                 this->Logs->Log("STARTUP", LOG_DEFAULT, "Failed to write PID-file '%s'%s", fname.c_str(), (exitonfail ? ", exiting." : ""));
459                 if (exitonfail)
460                         Exit(EXIT_STATUS_PID);
461         }
462 #endif
463 }
464
465 InspIRCd::InspIRCd(int argc, char** argv)
466         : FakeClient(NULL)
467         , ConfigFileName(INSPIRCD_CONFIG_PATH "/inspircd.conf")
468         , ConfigThread(NULL)
469         , Config(NULL)
470         , XLines(NULL)
471         , PI(&DefaultProtocolInterface)
472         , GenRandom(&DefaultGenRandom)
473         , IsChannel(&DefaultIsChannel)
474         , IsNick(&DefaultIsNick)
475         , IsIdent(&DefaultIsIdent)
476 {
477         ServerInstance = this;
478
479         UpdateTime();
480         this->startup_time = TIME.tv_sec;
481
482         IncreaseCoreDumpSize();
483         SeedRng(TIME);
484         SocketEngine::Init();
485
486         this->Config = new ServerConfig;
487         dynamic_reference_base::reset_all();
488         this->XLines = new XLineManager;
489
490         this->Config->cmdline.argv = argv;
491         this->Config->cmdline.argc = argc;
492
493 #ifdef _WIN32
494         // Initialize the console values
495         g_hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
496         CONSOLE_SCREEN_BUFFER_INFO bufinf;
497         if(GetConsoleScreenBufferInfo(g_hStdout, &bufinf))
498         {
499                 g_wOriginalColors = bufinf.wAttributes & 0x00FF;
500                 g_wBackgroundColor = bufinf.wAttributes & 0x00F0;
501         }
502         else
503         {
504                 g_wOriginalColors = FOREGROUND_RED|FOREGROUND_BLUE|FOREGROUND_GREEN;
505                 g_wBackgroundColor = 0;
506         }
507 #endif
508
509         {
510                 ServiceProvider* provs[] =
511                 {
512                         &rfcevents.numeric, &rfcevents.join, &rfcevents.part, &rfcevents.kick, &rfcevents.quit, &rfcevents.nick,
513                         &rfcevents.mode, &rfcevents.topic, &rfcevents.privmsg, &rfcevents.invite, &rfcevents.ping, &rfcevents.pong,
514                         &rfcevents.error
515                 };
516                 Modules.AddServices(provs, sizeof(provs)/sizeof(provs[0]));
517         }
518
519         std::cout << con_green << "InspIRCd - Internet Relay Chat Daemon" << con_reset << std::endl
520                 << "See " << con_green << "/INFO" << con_reset << " for contributors & authors" << std::endl
521                 << std::endl;
522
523         ParseOptions();
524         if (Config->cmdline.forcedebug)
525         {
526                 FileWriter* fw = new FileWriter(stdout, 1);
527                 FileLogStream* fls = new FileLogStream(LOG_RAWIO, fw);
528                 Logs->AddLogTypes("*", fls, true);
529         }
530
531         if (!FindConfigFile(ConfigFileName))
532         {
533                 this->Logs->Log("STARTUP", LOG_DEFAULT, "Unable to open config file %s", ConfigFileName.c_str());
534                 std::cout << "ERROR: Cannot open config file: " << ConfigFileName << std::endl << "Exiting..." << std::endl;
535                 Exit(EXIT_STATUS_CONFIG);
536         }
537
538         SetSignals();
539         if (!Config->cmdline.runasroot)
540                 CheckRoot();
541         if (!Config->cmdline.nofork)
542                 ForkIntoBackground();
543
544         std::cout << "InspIRCd Process ID: " << con_green << getpid() << con_reset << std::endl;
545
546         /* During startup we read the configuration now, not in
547          * a seperate thread
548          */
549         this->Config->Read();
550         this->Config->Apply(NULL, "");
551         Logs->OpenFileLogs();
552
553         // If we don't have a SID, generate one based on the server name and the server description
554         if (Config->sid.empty())
555                 Config->sid = UIDGenerator::GenerateSID(Config->ServerName, Config->ServerDesc);
556
557         // Initialize the UID generator with our sid
558         this->UIDGen.init(Config->sid);
559
560         // Create the server user for this server
561         this->FakeClient = new FakeUser(Config->sid, Config->ServerName, Config->ServerDesc);
562
563         // This is needed as all new XLines are marked pending until ApplyLines() is called
564         this->XLines->ApplyLines();
565
566         std::cout << std::endl;
567
568         TryBindPorts();
569
570         this->Modules->LoadAll();
571
572         // Build ISupport as ModuleManager::LoadAll() does not do it
573         this->ISupport.Build();
574
575         std::cout << "InspIRCd is now running as '" << Config->ServerName << "'[" << Config->GetSID() << "] with " << SocketEngine::GetMaxFds() << " max open sockets" << std::endl;
576
577 #ifndef _WIN32
578         if (!Config->cmdline.nofork)
579         {
580                 if (kill(getppid(), SIGTERM) == -1)
581                 {
582                         std::cout << "Error killing parent process: " << strerror(errno) << std::endl;
583                         Logs->Log("STARTUP", LOG_DEFAULT, "Error killing parent process: %s",strerror(errno));
584                 }
585         }
586
587         /* Explicitly shut down stdio's stdin/stdout/stderr.
588          *
589          * The previous logic here was to only do this if stdio was connected to a controlling
590          * terminal.  However, we must do this always to avoid information leaks and other
591          * problems related to stdio.
592          *
593          * The only exception is if we are in debug mode.
594          *
595          *    -- nenolod
596          */
597         if ((!Config->cmdline.nofork) && (!Config->cmdline.forcedebug))
598         {
599                 int fd = open("/dev/null", O_RDWR);
600
601                 fclose(stdin);
602                 fclose(stderr);
603                 fclose(stdout);
604
605                 if (dup2(fd, STDIN_FILENO) < 0)
606                         Logs->Log("STARTUP", LOG_DEFAULT, "Failed to dup /dev/null to stdin.");
607                 if (dup2(fd, STDOUT_FILENO) < 0)
608                         Logs->Log("STARTUP", LOG_DEFAULT, "Failed to dup /dev/null to stdout.");
609                 if (dup2(fd, STDERR_FILENO) < 0)
610                         Logs->Log("STARTUP", LOG_DEFAULT, "Failed to dup /dev/null to stderr.");
611                 close(fd);
612         }
613         else
614         {
615                 Logs->Log("STARTUP", LOG_DEFAULT, "Keeping pseudo-tty open as we are running in the foreground.");
616         }
617 #else
618         /* Set win32 service as running, if we are running as a service */
619         SetServiceRunning();
620
621         // Handle forking
622         if(!Config->cmdline.nofork)
623         {
624                 FreeConsole();
625         }
626
627         QueryPerformanceFrequency(&stats.QPFrequency);
628 #endif
629
630         WritePID(Config->PID);
631         DropRoot();
632
633         Logs->Log("STARTUP", LOG_DEFAULT, "Startup complete as '%s'[%s], %lu max open sockets", Config->ServerName.c_str(),Config->GetSID().c_str(), SocketEngine::GetMaxFds());
634 }
635
636 void InspIRCd::UpdateTime()
637 {
638 #if defined HAS_CLOCK_GETTIME
639         clock_gettime(CLOCK_REALTIME, &TIME);
640 #elif defined _WIN32
641         SYSTEMTIME st;
642         GetSystemTime(&st);
643
644         TIME.tv_sec = time(NULL);
645         TIME.tv_nsec = st.wMilliseconds;
646 #else
647         struct timeval tv;
648         gettimeofday(&tv, NULL);
649
650         TIME.tv_sec = tv.tv_sec;
651         TIME.tv_nsec = tv.tv_usec * 1000;
652 #endif
653 }
654
655 void InspIRCd::Run()
656 {
657         UpdateTime();
658         time_t OLDTIME = TIME.tv_sec;
659
660         while (true)
661         {
662                 /* Check if there is a config thread which has finished executing but has not yet been freed */
663                 if (this->ConfigThread && this->ConfigThread->IsDone())
664                 {
665                         /* Rehash has completed */
666                         this->Logs->Log("CONFIG", LOG_DEBUG, "Detected ConfigThread exiting, tidying up...");
667
668                         this->ConfigThread->Finish();
669
670                         ConfigThread->join();
671                         delete ConfigThread;
672                         ConfigThread = NULL;
673                 }
674
675                 UpdateTime();
676
677                 /* Run background module timers every few seconds
678                  * (the docs say modules shouldnt rely on accurate
679                  * timing using this event, so we dont have to
680                  * time this exactly).
681                  */
682                 if (TIME.tv_sec != OLDTIME)
683                 {
684                         CollectStats();
685                         CheckTimeSkip(OLDTIME, TIME.tv_sec);
686
687                         OLDTIME = TIME.tv_sec;
688
689                         if ((TIME.tv_sec % 3600) == 0)
690                                 FOREACH_MOD(OnGarbageCollect, ());
691
692                         Timers.TickTimers(TIME.tv_sec);
693                         Users->DoBackgroundUserStuff();
694
695                         if ((TIME.tv_sec % 5) == 0)
696                         {
697                                 FOREACH_MOD(OnBackgroundTimer, (TIME.tv_sec));
698                                 SNO->FlushSnotices();
699                         }
700                 }
701
702                 /* Call the socket engine to wait on the active
703                  * file descriptors. The socket engine has everything's
704                  * descriptors in its list... dns, modules, users,
705                  * servers... so its nice and easy, just one call.
706                  * This will cause any read or write events to be
707                  * dispatched to their handlers.
708                  */
709                 SocketEngine::DispatchTrialWrites();
710                 SocketEngine::DispatchEvents();
711
712                 /* if any users were quit, take them out */
713                 GlobalCulls.Apply();
714                 AtomicActions.Run();
715
716                 if (s_signal)
717                 {
718                         this->SignalHandler(s_signal);
719                         s_signal = 0;
720                 }
721         }
722 }
723
724 sig_atomic_t InspIRCd::s_signal = 0;
725
726 void InspIRCd::SetSignal(int signal)
727 {
728         s_signal = signal;
729 }
730
731 /* On posix systems, the flow of the program starts right here, with
732  * ENTRYPOINT being a #define that defines main(). On Windows, ENTRYPOINT
733  * defines smain() and the real main() is in the service code under
734  * win32service.cpp. This allows the service control manager to control
735  * the process where we are running as a windows service.
736  */
737 ENTRYPOINT
738 {
739         new InspIRCd(argc, argv);
740         ServerInstance->Run();
741         delete ServerInstance;
742         return 0;
743 }