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