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