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