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