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