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