]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
4e4b3f5e2796bbe6853b2aa5e7ef028164e1f3ab
[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 /* $Core */
30 #include "inspircd.h"
31 #include <signal.h>
32
33 #ifndef _WIN32
34         #include <dirent.h>
35         #include <unistd.h>
36         #include <sys/resource.h>
37         #include <dlfcn.h>
38         #include <getopt.h>
39
40         /* Some systems don't define RUSAGE_SELF. This should fix them. */
41         #ifndef RUSAGE_SELF
42                 #define RUSAGE_SELF 0
43         #endif
44
45         #include <pwd.h> // setuid
46         #include <grp.h> // setgid
47 #else
48         WORD g_wOriginalColors;
49         WORD g_wBackgroundColor;
50         HANDLE g_hStdout;
51 #endif
52
53 #include <fstream>
54 #include <iostream>
55 #include "xline.h"
56 #include "bancache.h"
57 #include "socketengine.h"
58 #include "socket.h"
59 #include "command_parse.h"
60 #include "exitcodes.h"
61 #include "caller.h"
62 #include "testsuite.h"
63
64 InspIRCd* ServerInstance = NULL;
65
66 /** Seperate from the other casemap tables so that code *can* still exclusively rely on RFC casemapping
67  * if it must.
68  *
69  * This is provided as a pointer so that modules can change it to their custom mapping tables,
70  * e.g. for national character support.
71  */
72 unsigned const char *national_case_insensitive_map = rfc_case_insensitive_map;
73
74
75 /* Moved from exitcodes.h -- due to duplicate symbols -- Burlex
76  * XXX this is a bit ugly. -- w00t
77  */
78 const char* ExitCodes[] =
79 {
80                 "No error", /* 0 */
81                 "DIE command", /* 1 */
82                 "execv() failed", /* 2 */
83                 "Internal error", /* 3 */
84                 "Config file error", /* 4 */
85                 "Logfile error", /* 5 */
86                 "POSIX fork failed", /* 6 */
87                 "Bad commandline parameters", /* 7 */
88                 "No ports could be bound", /* 8 */
89                 "Can't write PID file", /* 9 */
90                 "SocketEngine could not initialize", /* 10 */
91                 "Refusing to start up as root", /* 11 */
92                 "Found a <die> tag!", /* 12 */
93                 "Couldn't load module on startup", /* 13 */
94                 "Could not create windows forked process", /* 14 */
95                 "Received SIGTERM", /* 15 */
96                 "Bad command handler loaded", /* 16 */
97                 "RegisterServiceCtrlHandler failed", /* 17 */
98                 "UpdateSCMStatus failed", /* 18 */
99                 "CreateEvent failed" /* 19 */
100 };
101
102 template<typename T> static void DeleteZero(T*&n)
103 {
104         T* t = n;
105         n = NULL;
106         delete t;
107 }
108
109 void InspIRCd::Cleanup()
110 {
111         for (unsigned int i = 0; i < ports.size(); i++)
112         {
113                 /* This calls the constructor and closes the listening socket */
114                 ports[i]->cull();
115                 delete ports[i];
116         }
117         ports.clear();
118
119         /* Close all client sockets, or the new process inherits them */
120         LocalUserList::reverse_iterator i = Users->local_users.rbegin();
121         while (i != this->Users->local_users.rend())
122         {
123                 User* u = *i++;
124                 Users->QuitUser(u, "Server shutdown");
125         }
126
127         GlobalCulls.Apply();
128         Modules->UnloadAll();
129
130         /* Delete objects dynamically allocated in constructor (destructor would be more appropriate, but we're likely exiting) */
131         /* Must be deleted before modes as it decrements modelines */
132         if (FakeClient)
133                 FakeClient->cull();
134         DeleteZero(this->FakeClient);
135         DeleteZero(this->Users);
136         DeleteZero(this->Modes);
137         DeleteZero(this->XLines);
138         DeleteZero(this->Parser);
139         DeleteZero(this->stats);
140         DeleteZero(this->Modules);
141         DeleteZero(this->BanCache);
142         DeleteZero(this->SNO);
143         DeleteZero(this->Config);
144         DeleteZero(this->chanlist);
145         DeleteZero(this->PI);
146         DeleteZero(this->Threads);
147         DeleteZero(this->Timers);
148         DeleteZero(this->SE);
149         /* Close logging */
150         this->Logs->CloseLogs();
151         DeleteZero(this->Logs);
152 }
153
154 void InspIRCd::Restart(const std::string &reason)
155 {
156         /* SendError flushes each client's queue,
157          * regardless of writeability state
158          */
159         this->SendError(reason);
160
161         /* Figure out our filename (if theyve renamed it, we're boned) */
162         std::string me;
163
164         char** argv = Config->cmdline.argv;
165
166 #ifdef _WIN32
167         char module[MAX_PATH];
168         if (GetModuleFileNameA(NULL, module, MAX_PATH))
169                 me = module;
170 #else
171         me = argv[0];
172 #endif
173
174         this->Cleanup();
175
176         if (execv(me.c_str(), argv) == -1)
177         {
178                 /* Will raise a SIGABRT if not trapped */
179                 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
180         }
181 }
182
183 void InspIRCd::SetSignals()
184 {
185 #ifndef _WIN32
186         signal(SIGALRM, SIG_IGN);
187         signal(SIGHUP, InspIRCd::SetSignal);
188         signal(SIGPIPE, SIG_IGN);
189         signal(SIGCHLD, SIG_IGN);
190         /* We want E2BIG not a signal! */
191         signal(SIGXFSZ, SIG_IGN);
192 #endif
193         signal(SIGTERM, InspIRCd::SetSignal);
194 }
195
196 void InspIRCd::QuickExit(int status)
197 {
198         exit(0);
199 }
200
201 bool InspIRCd::DaemonSeed()
202 {
203 #ifdef _WIN32
204         std::cout << "InspIRCd Process ID: " << con_green << GetCurrentProcessId() << con_reset << std::endl;
205         return true;
206 #else
207         signal(SIGTERM, InspIRCd::QuickExit);
208
209         int childpid;
210         if ((childpid = fork ()) < 0)
211                 return false;
212         else if (childpid > 0)
213         {
214                 /* We wait here for the child process to kill us,
215                  * so that the shell prompt doesnt come back over
216                  * the output.
217                  * Sending a kill with a signal of 0 just checks
218                  * if the child pid is still around. If theyre not,
219                  * they threw an error and we should give up.
220                  */
221                 while (kill(childpid, 0) != -1)
222                         sleep(1);
223                 exit(0);
224         }
225         setsid ();
226         std::cout << "InspIRCd Process ID: " << con_green << getpid() << con_reset << std::endl;
227
228         signal(SIGTERM, InspIRCd::SetSignal);
229
230         rlimit rl;
231         if (getrlimit(RLIMIT_CORE, &rl) == -1)
232         {
233                 this->Logs->Log("STARTUP", LOG_DEFAULT, "Failed to getrlimit()!");
234                 return false;
235         }
236         rl.rlim_cur = rl.rlim_max;
237
238         if (setrlimit(RLIMIT_CORE, &rl) == -1)
239                         this->Logs->Log("STARTUP", LOG_DEFAULT, "setrlimit() failed, cannot increase coredump size.");
240
241         return true;
242 #endif
243 }
244
245 void InspIRCd::WritePID(const std::string &filename)
246 {
247 #ifndef _WIN32
248         std::string fname(filename);
249         if (fname.empty())
250                 fname = DATA_PATH "/inspircd.pid";
251         std::ofstream outfile(fname.c_str());
252         if (outfile.is_open())
253         {
254                 outfile << getpid();
255                 outfile.close();
256         }
257         else
258         {
259                 std::cout << "Failed to write PID-file '" << fname << "', exiting." << std::endl;
260                 this->Logs->Log("STARTUP", LOG_DEFAULT, "Failed to write PID-file '%s', exiting.",fname.c_str());
261                 Exit(EXIT_STATUS_PID);
262         }
263 #endif
264 }
265
266 InspIRCd::InspIRCd(int argc, char** argv) :
267          ConfigFileName(CONFIG_PATH "/inspircd.conf"),
268
269          /* Functor pointer initialisation.
270           *
271           * THIS MUST MATCH THE ORDER OF DECLARATION OF THE FUNCTORS, e.g. the methods
272           * themselves within the class.
273           */
274          OperQuit("OperQuit", NULL),
275          GenRandom(&HandleGenRandom),
276          IsChannel(&HandleIsChannel),
277          Rehash(&HandleRehash),
278          IsNick(&HandleIsNick),
279          IsIdent(&HandleIsIdent),
280          OnCheckExemption(&HandleOnCheckExemption)
281 {
282         ServerInstance = this;
283
284         Extensions.Register(&OperQuit);
285
286         FailedPortList pl;
287         int do_version = 0, do_nofork = 0, do_debug = 0,
288             do_nolog = 0, do_root = 0, do_testsuite = 0;    /* flag variables */
289         int c = 0;
290
291         // Initialize so that if we exit before proper initialization they're not deleted
292         this->Logs = 0;
293         this->Threads = 0;
294         this->PI = 0;
295         this->Users = 0;
296         this->chanlist = 0;
297         this->Config = 0;
298         this->SNO = 0;
299         this->BanCache = 0;
300         this->Modules = 0;
301         this->stats = 0;
302         this->Timers = 0;
303         this->Parser = 0;
304         this->XLines = 0;
305         this->Modes = 0;
306         this->ConfigThread = NULL;
307         this->FakeClient = NULL;
308
309         UpdateTime();
310         this->startup_time = TIME.tv_sec;
311
312         // This must be created first, so other parts of Insp can use it while starting up
313         this->Logs = new LogManager;
314
315         SE = CreateSocketEngine();
316
317         this->Threads = new ThreadEngine;
318
319         /* Default implementation does nothing */
320         this->PI = new ProtocolInterface;
321
322         // Create base manager classes early, so nothing breaks
323         this->Users = new UserManager;
324
325         this->chanlist = new chan_hash();
326
327         this->Config = new ServerConfig;
328         this->SNO = new SnomaskManager;
329         this->BanCache = new BanCacheManager;
330         this->Modules = new ModuleManager();
331         dynamic_reference_base::reset_all();
332         this->stats = new serverstats();
333         this->Timers = new TimerManager;
334         this->Parser = new CommandParser;
335         this->XLines = new XLineManager;
336
337         this->Config->cmdline.argv = argv;
338         this->Config->cmdline.argc = argc;
339
340 #ifdef _WIN32
341         srand(TIME.tv_nsec ^ TIME.tv_sec);
342
343         // Initialize the console values
344         g_hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
345         CONSOLE_SCREEN_BUFFER_INFO bufinf;
346         if(GetConsoleScreenBufferInfo(g_hStdout, &bufinf))
347         {
348                 g_wOriginalColors = bufinf.wAttributes & 0x00FF;
349                 g_wBackgroundColor = bufinf.wAttributes & 0x00F0;
350         }
351         else
352         {
353                 g_wOriginalColors = FOREGROUND_RED|FOREGROUND_BLUE|FOREGROUND_GREEN;
354                 g_wBackgroundColor = 0;
355         }
356 #else
357         srandom(TIME.tv_nsec ^ TIME.tv_sec);
358 #endif
359
360         struct option longopts[] =
361         {
362                 { "nofork",     no_argument,            &do_nofork,     1       },
363                 { "config",     required_argument,      NULL,           'c'     },
364                 { "debug",      no_argument,            &do_debug,      1       },
365                 { "nolog",      no_argument,            &do_nolog,      1       },
366                 { "runasroot",  no_argument,            &do_root,       1       },
367                 { "version",    no_argument,            &do_version,    1       },
368                 { "testsuite",  no_argument,            &do_testsuite,  1       },
369                 { 0, 0, 0, 0 }
370         };
371
372         int index;
373         while ((c = getopt_long(argc, argv, ":c:", longopts, &index)) != -1)
374         {
375                 switch (c)
376                 {
377                         case 'c':
378                                 /* Config filename was set */
379                                 ConfigFileName = optarg;
380                         break;
381                         case 0:
382                                 /* getopt_long_only() set an int variable, just keep going */
383                         break;
384                         case '?':
385                                 /* Unknown parameter */
386                         default:
387                                 /* Fall through to handle other weird values too */
388                                 std::cout << "Unknown parameter '" << argv[optind-1] << "'" << std::endl;
389                                 std::cout << "Usage: " << argv[0] << " [--nofork] [--nolog] [--debug] [--config <config>]" << std::endl <<
390                                         std::string(static_cast<int>(8+strlen(argv[0])), ' ') << "[--runasroot] [--version] [--testsuite]" << std::endl;
391                                 Exit(EXIT_STATUS_ARGV);
392                         break;
393                 }
394         }
395
396         if (do_testsuite)
397                 do_nofork = do_debug = true;
398
399         if (do_version)
400         {
401                 std::cout << std::endl << VERSION << " r" << REVISION << std::endl;
402                 Exit(EXIT_STATUS_NOERROR);
403         }
404
405 #ifdef _WIN32
406         // Set up winsock
407         WSADATA wsadata;
408         WSAStartup(MAKEWORD(2,2), &wsadata);
409 #endif
410
411         /* Set the finished argument values */
412         Config->cmdline.nofork = (do_nofork != 0);
413         Config->cmdline.forcedebug = (do_debug != 0);
414         Config->cmdline.writelog = (!do_nolog != 0);
415         Config->cmdline.TestSuite = (do_testsuite != 0);
416
417         if (do_debug)
418         {
419                 FileWriter* fw = new FileWriter(stdout);
420                 FileLogStream* fls = new FileLogStream(LOG_RAWIO, fw);
421                 Logs->AddLogTypes("*", fls, true);
422         }
423
424         if (!ServerConfig::FileExists(ConfigFileName.c_str()))
425         {
426 #ifdef _WIN32
427                 /* Windows can (and defaults to) hide file extensions, so let's play a bit nice for windows users. */
428                 std::string txtconf = this->ConfigFileName;
429                 txtconf.append(".txt");
430
431                 if (ServerConfig::FileExists(txtconf.c_str()))
432                 {
433                         ConfigFileName = txtconf;
434                 }
435                 else
436 #endif
437                 {
438                         std::cout << "ERROR: Cannot open config file: " << ConfigFileName << std::endl << "Exiting..." << std::endl;
439                         this->Logs->Log("STARTUP", LOG_DEFAULT, "Unable to open config file %s", ConfigFileName.c_str());
440                         Exit(EXIT_STATUS_CONFIG);
441                 }
442         }
443
444         std::cout << con_green << "Inspire Internet Relay Chat Server" << con_reset << ", compiled on " __DATE__ " at " __TIME__ << std::endl;
445         std::cout << con_green << "(C) InspIRCd Development Team." << con_reset << std::endl << std::endl;
446         std::cout << "Developers:" << std::endl;
447         std::cout << con_green << "\tBrain, FrostyCoolSlug, w00t, Om, Special, peavey" << std::endl;
448         std::cout << "\taquanight, psychon, dz, danieldg, jackmcbarn" << std::endl;
449         std::cout << "\tAttila" << con_reset << std::endl << std::endl;
450         std::cout << "Others:\t\t\t" << con_green << "See /INFO Output" << con_reset << std::endl;
451
452         this->Modes = new ModeParser;
453
454 #ifndef _WIN32
455         if (!do_root)
456                 this->CheckRoot();
457         else
458         {
459                 std::cout << "* WARNING * WARNING * WARNING * WARNING * WARNING *" << std::endl
460                 << "YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED" << std::endl
461                 << "AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED" << std::endl
462                 << "OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR" << std::endl
463                 << "SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN" << std::endl
464                 << "TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART" << std::endl
465                 << "THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!" << std::endl << std::endl
466                 << "InspIRCd starting in 20 seconds, ctrl+c to abort..." << std::endl;
467                 sleep(20);
468         }
469 #endif
470
471         this->SetSignals();
472
473         if (!Config->cmdline.nofork)
474         {
475                 if (!this->DaemonSeed())
476                 {
477                         std::cout << "ERROR: could not go into daemon mode. Shutting down." << std::endl;
478                         Logs->Log("STARTUP", LOG_DEFAULT, "ERROR: could not go into daemon mode. Shutting down.");
479                         Exit(EXIT_STATUS_FORK);
480                 }
481         }
482
483         SE->RecoverFromFork();
484
485         /* During startup we don't actually initialize this
486          * in the thread engine.
487          */
488         this->Config->Read();
489         this->Config->Apply(NULL, "");
490         Logs->OpenFileLogs();
491         ModeParser::InitBuiltinModes();
492
493         // If we don't have a SID, generate one based on the server name and the server description
494         if (Config->sid.empty())
495                 Config->sid = UIDGenerator::GenerateSID(Config->ServerName, Config->ServerDesc);
496
497         // Initialize the UID generator with our sid
498         this->UIDGen.init(Config->sid);
499
500         /* set up fake client again this time with the correct uid */
501         this->FakeClient = new FakeUser(Config->sid, Config->ServerName);
502
503         // Get XLine to do it's thing.
504         this->XLines->CheckELines();
505         this->XLines->ApplyLines();
506
507         int bounditems = BindPorts(pl);
508
509         std::cout << std::endl;
510
511         this->Modules->LoadAll();
512
513         /* Just in case no modules were loaded - fix for bug #101 */
514         this->ISupport.Build();
515         Config->ApplyDisabledCommands(Config->DisabledCommands);
516
517         if (!pl.empty())
518         {
519                 std::cout << std::endl << "WARNING: Not all your client ports could be bound -- " << std::endl << "starting anyway with " << bounditems
520                         << " of " << bounditems + (int)pl.size() << " client ports bound." << std::endl << std::endl;
521                 std::cout << "The following port(s) failed to bind:" << std::endl << std::endl;
522                 int j = 1;
523                 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
524                 {
525                         std::cout << j << ".\tAddress: " << (i->first.empty() ? "<all>" : i->first) << " \tReason: " << i->second << std::endl;
526                 }
527
528                 std::cout << std::endl << "Hint: Try using a public IP instead of blank or *" << std::endl;
529         }
530
531         std::cout << "InspIRCd is now running as '" << Config->ServerName << "'[" << Config->GetSID() << "] with " << SE->GetMaxFds() << " max open sockets" << std::endl;
532
533 #ifndef _WIN32
534         if (!Config->cmdline.nofork)
535         {
536                 if (kill(getppid(), SIGTERM) == -1)
537                 {
538                         std::cout << "Error killing parent process: " << strerror(errno) << std::endl;
539                         Logs->Log("STARTUP", LOG_DEFAULT, "Error killing parent process: %s",strerror(errno));
540                 }
541         }
542
543         /* Explicitly shut down stdio's stdin/stdout/stderr.
544          *
545          * The previous logic here was to only do this if stdio was connected to a controlling
546          * terminal.  However, we must do this always to avoid information leaks and other
547          * problems related to stdio.
548          *
549          * The only exception is if we are in debug mode.
550          *
551          *    -- nenolod
552          */
553         if ((!do_nofork) && (!do_testsuite) && (!Config->cmdline.forcedebug))
554         {
555                 int fd = open("/dev/null", O_RDWR);
556
557                 fclose(stdin);
558                 fclose(stderr);
559                 fclose(stdout);
560
561                 if (dup2(fd, STDIN_FILENO) < 0)
562                         Logs->Log("STARTUP", LOG_DEFAULT, "Failed to dup /dev/null to stdin.");
563                 if (dup2(fd, STDOUT_FILENO) < 0)
564                         Logs->Log("STARTUP", LOG_DEFAULT, "Failed to dup /dev/null to stdout.");
565                 if (dup2(fd, STDERR_FILENO) < 0)
566                         Logs->Log("STARTUP", LOG_DEFAULT, "Failed to dup /dev/null to stderr.");
567                 close(fd);
568         }
569         else
570         {
571                 Logs->Log("STARTUP", LOG_DEFAULT, "Keeping pseudo-tty open as we are running in the foreground.");
572         }
573 #else
574         /* Set win32 service as running, if we are running as a service */
575         SetServiceRunning();
576
577         // Handle forking
578         if(!do_nofork)
579         {
580                 FreeConsole();
581         }
582
583         QueryPerformanceFrequency(&stats->QPFrequency);
584 #endif
585
586         Logs->Log("STARTUP", LOG_DEFAULT, "Startup complete as '%s'[%s], %d max open sockets", Config->ServerName.c_str(),Config->GetSID().c_str(), SE->GetMaxFds());
587
588 #ifndef _WIN32
589         std::string SetUser = Config->ConfValue("security")->getString("runasuser");
590         std::string SetGroup = Config->ConfValue("security")->getString("runasgroup");
591         if (!SetGroup.empty())
592         {
593                 int ret;
594
595                 // setgroups
596                 ret = setgroups(0, NULL);
597
598                 if (ret == -1)
599                 {
600                         this->Logs->Log("SETGROUPS", LOG_DEFAULT, "setgroups() failed (wtf?): %s", strerror(errno));
601                         this->QuickExit(0);
602                 }
603
604                 // setgid
605                 struct group *g;
606
607                 errno = 0;
608                 g = getgrnam(SetGroup.c_str());
609
610                 if (!g)
611                 {
612                         this->Logs->Log("SETGUID", LOG_DEFAULT, "getgrnam() failed (bad user?): %s", strerror(errno));
613                         this->QuickExit(0);
614                 }
615
616                 ret = setgid(g->gr_gid);
617
618                 if (ret == -1)
619                 {
620                         this->Logs->Log("SETGUID", LOG_DEFAULT, "setgid() failed (bad user?): %s", strerror(errno));
621                         this->QuickExit(0);
622                 }
623         }
624
625         if (!SetUser.empty())
626         {
627                 // setuid
628                 struct passwd *u;
629
630                 errno = 0;
631                 u = getpwnam(SetUser.c_str());
632
633                 if (!u)
634                 {
635                         this->Logs->Log("SETGUID", LOG_DEFAULT, "getpwnam() failed (bad user?): %s", strerror(errno));
636                         this->QuickExit(0);
637                 }
638
639                 int ret = setuid(u->pw_uid);
640
641                 if (ret == -1)
642                 {
643                         this->Logs->Log("SETGUID", LOG_DEFAULT, "setuid() failed (bad user?): %s", strerror(errno));
644                         this->QuickExit(0);
645                 }
646         }
647
648         this->WritePID(Config->PID);
649 #endif
650 }
651
652 void InspIRCd::UpdateTime()
653 {
654 #ifdef _WIN32
655         SYSTEMTIME st;
656         GetSystemTime(&st);
657
658         TIME.tv_sec = time(NULL);
659         TIME.tv_nsec = st.wMilliseconds;
660 #else
661         #ifdef HAS_CLOCK_GETTIME
662                 clock_gettime(CLOCK_REALTIME, &TIME);
663         #else
664                 struct timeval tv;
665                 gettimeofday(&tv, NULL);
666                 TIME.tv_sec = tv.tv_sec;
667                 TIME.tv_nsec = tv.tv_usec * 1000;
668         #endif
669 #endif
670 }
671
672 int InspIRCd::Run()
673 {
674         /* See if we're supposed to be running the test suite rather than entering the mainloop */
675         if (Config->cmdline.TestSuite)
676         {
677                 TestSuite* ts = new TestSuite;
678                 delete ts;
679                 Exit(0);
680         }
681
682         UpdateTime();
683         time_t OLDTIME = TIME.tv_sec;
684
685         while (true)
686         {
687 #ifndef _WIN32
688                 static rusage ru;
689 #endif
690
691                 /* Check if there is a config thread which has finished executing but has not yet been freed */
692                 if (this->ConfigThread && this->ConfigThread->IsDone())
693                 {
694                         /* Rehash has completed */
695                         this->Logs->Log("CONFIG", LOG_DEBUG, "Detected ConfigThread exiting, tidying up...");
696
697                         this->ConfigThread->Finish();
698
699                         ConfigThread->join();
700                         delete ConfigThread;
701                         ConfigThread = NULL;
702                 }
703
704                 UpdateTime();
705
706                 /* Run background module timers every few seconds
707                  * (the docs say modules shouldnt rely on accurate
708                  * timing using this event, so we dont have to
709                  * time this exactly).
710                  */
711                 if (TIME.tv_sec != OLDTIME)
712                 {
713 #ifndef _WIN32
714                         getrusage(RUSAGE_SELF, &ru);
715                         stats->LastSampled = TIME;
716                         stats->LastCPU = ru.ru_utime;
717 #else
718                         if(QueryPerformanceCounter(&stats->LastSampled))
719                         {
720                                 FILETIME CreationTime;
721                                 FILETIME ExitTime;
722                                 FILETIME KernelTime;
723                                 FILETIME UserTime;
724                                 GetProcessTimes(GetCurrentProcess(), &CreationTime, &ExitTime, &KernelTime, &UserTime);
725                                 stats->LastCPU.dwHighDateTime = KernelTime.dwHighDateTime + UserTime.dwHighDateTime;
726                                 stats->LastCPU.dwLowDateTime = KernelTime.dwLowDateTime + UserTime.dwLowDateTime;
727                         }
728 #endif
729
730                         /* Allow a buffer of two seconds drift on this so that ntpdate etc dont harass admins */
731                         if (TIME.tv_sec < OLDTIME - 2)
732                         {
733                                 SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %lu secs.", (unsigned long)OLDTIME-TIME.tv_sec);
734                         }
735                         else if (TIME.tv_sec > OLDTIME + 2)
736                         {
737                                 SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is jumping FORWARDS! Clock skipped %lu secs.", (unsigned long)TIME.tv_sec - OLDTIME);
738                         }
739
740                         OLDTIME = TIME.tv_sec;
741
742                         if ((TIME.tv_sec % 3600) == 0)
743                         {
744                                 Users->GarbageCollect();
745                                 FOREACH_MOD(I_OnGarbageCollect, OnGarbageCollect());
746                         }
747
748                         Timers->TickTimers(TIME.tv_sec);
749                         Users->DoBackgroundUserStuff();
750
751                         if ((TIME.tv_sec % 5) == 0)
752                         {
753                                 FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME.tv_sec));
754                                 SNO->FlushSnotices();
755                         }
756                 }
757
758                 /* Call the socket engine to wait on the active
759                  * file descriptors. The socket engine has everything's
760                  * descriptors in its list... dns, modules, users,
761                  * servers... so its nice and easy, just one call.
762                  * This will cause any read or write events to be
763                  * dispatched to their handlers.
764                  */
765                 this->SE->DispatchTrialWrites();
766                 this->SE->DispatchEvents();
767
768                 /* if any users were quit, take them out */
769                 GlobalCulls.Apply();
770                 AtomicActions.Run();
771
772                 if (s_signal)
773                 {
774                         this->SignalHandler(s_signal);
775                         s_signal = 0;
776                 }
777         }
778
779         return 0;
780 }
781
782 sig_atomic_t InspIRCd::s_signal = 0;
783
784 void InspIRCd::SetSignal(int signal)
785 {
786         s_signal = signal;
787 }
788
789 /* On posix systems, the flow of the program starts right here, with
790  * ENTRYPOINT being a #define that defines main(). On Windows, ENTRYPOINT
791  * defines smain() and the real main() is in the service code under
792  * win32service.cpp. This allows the service control manager to control
793  * the process where we are running as a windows service.
794  */
795 ENTRYPOINT
796 {
797         new InspIRCd(argc, argv);
798         ServerInstance->Run();
799         delete ServerInstance;
800         return 0;
801 }