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