]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
Release v2.0.22
[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
228 void InspIRCd::SetSignals()
229 {
230 #ifndef _WIN32
231         signal(SIGALRM, SIG_IGN);
232         signal(SIGHUP, InspIRCd::SetSignal);
233         signal(SIGPIPE, SIG_IGN);
234         signal(SIGCHLD, SIG_IGN);
235         /* We want E2BIG not a signal! */
236         signal(SIGXFSZ, SIG_IGN);
237 #endif
238         signal(SIGTERM, InspIRCd::SetSignal);
239 }
240
241 void InspIRCd::QuickExit(int status)
242 {
243         exit(status);
244 }
245
246 // Required for returning the proper value of EXIT_SUCCESS for the parent process
247 static void VoidSignalHandler(int signalreceived)
248 {
249         exit(0);
250 }
251
252 bool InspIRCd::DaemonSeed()
253 {
254 #ifdef _WIN32
255         std::cout << "InspIRCd Process ID: " << con_green << GetCurrentProcessId() << con_reset << std::endl;
256         return true;
257 #else
258         // Do not use QuickExit here: It will exit with status SIGTERM which would break e.g. daemon scripts
259         signal(SIGTERM, VoidSignalHandler);
260
261         int childpid;
262         if ((childpid = fork ()) < 0)
263                 return false;
264         else if (childpid > 0)
265         {
266                 /* We wait here for the child process to kill us,
267                  * so that the shell prompt doesnt come back over
268                  * the output.
269                  * Sending a kill with a signal of 0 just checks
270                  * if the child pid is still around. If theyre not,
271                  * they threw an error and we should give up.
272                  */
273                 while (kill(childpid, 0) != -1)
274                         sleep(1);
275                 exit(0);
276         }
277         setsid ();
278         std::cout << "InspIRCd Process ID: " << con_green << getpid() << con_reset << std::endl;
279
280         signal(SIGTERM, InspIRCd::SetSignal);
281
282         rlimit rl;
283         if (getrlimit(RLIMIT_CORE, &rl) == -1)
284         {
285                 this->Logs->Log("STARTUP",DEFAULT,"Failed to getrlimit()!");
286                 return false;
287         }
288         rl.rlim_cur = rl.rlim_max;
289
290         if (setrlimit(RLIMIT_CORE, &rl) == -1)
291                         this->Logs->Log("STARTUP",DEFAULT,"setrlimit() failed, cannot increase coredump size.");
292
293         return true;
294 #endif
295 }
296
297 void InspIRCd::WritePID(const std::string& filename, bool exitonfail)
298 {
299 #ifndef _WIN32
300         std::string fname(filename);
301         if (fname.empty())
302                 fname = DATA_PATH "/inspircd.pid";
303         std::ofstream outfile(fname.c_str());
304         if (outfile.is_open())
305         {
306                 outfile << getpid();
307                 outfile.close();
308         }
309         else
310         {\r
311                 if (exitonfail)\r
312                         std::cout << "Failed to write PID-file '" << fname << "', exiting." << std::endl;
313                 this->Logs->Log("STARTUP",DEFAULT,"Failed to write PID-file '%s'%s",fname.c_str(), (exitonfail ? ", exiting." : ""));\r
314                 if (exitonfail)
315                         Exit(EXIT_STATUS_PID);\r
316         }
317 #endif
318 }
319
320 InspIRCd::InspIRCd(int argc, char** argv) :
321          ConfigFileName(CONFIG_PATH "/inspircd.conf"),
322
323          /* Functor pointer initialisation.
324           *
325           * THIS MUST MATCH THE ORDER OF DECLARATION OF THE FUNCTORS, e.g. the methods
326           * themselves within the class.
327           */
328          NICKForced("NICKForced", NULL),
329          OperQuit("OperQuit", NULL),
330          GenRandom(&HandleGenRandom),
331          IsChannel(&HandleIsChannel),
332          IsSID(&HandleIsSID),
333          Rehash(&HandleRehash),
334          IsNick(&HandleIsNick),
335          IsIdent(&HandleIsIdent),
336          FloodQuitUser(&HandleFloodQuitUser),
337          OnCheckExemption(&HandleOnCheckExemption)
338 {
339         ServerInstance = this;
340
341         Extensions.Register(&NICKForced);
342         Extensions.Register(&OperQuit);
343
344         FailedPortList pl;
345         int do_version = 0, do_nofork = 0, do_debug = 0,
346             do_nolog = 0, do_root = 0, do_testsuite = 0;    /* flag variables */
347         int c = 0;
348
349         // Initialize so that if we exit before proper initialization they're not deleted
350         this->Logs = 0;
351         this->Threads = 0;
352         this->PI = 0;
353         this->Users = 0;
354         this->chanlist = 0;
355         this->Config = 0;
356         this->SNO = 0;
357         this->BanCache = 0;
358         this->Modules = 0;
359         this->stats = 0;
360         this->Timers = 0;
361         this->Parser = 0;
362         this->XLines = 0;
363         this->Modes = 0;
364         this->Res = 0;
365         this->ConfigThread = NULL;
366         this->FakeClient = NULL;
367
368         UpdateTime();
369         this->startup_time = TIME.tv_sec;
370
371         // This must be created first, so other parts of Insp can use it while starting up
372         this->Logs = new LogManager;
373
374         SE = CreateSocketEngine();
375
376         this->Threads = new ThreadEngine;
377
378         /* Default implementation does nothing */
379         this->PI = new ProtocolInterface;
380
381         this->s_signal = 0;
382
383         // Create base manager classes early, so nothing breaks
384         this->Users = new UserManager;
385
386         this->Users->clientlist = new user_hash();
387         this->Users->uuidlist = new user_hash();
388         this->chanlist = new chan_hash();
389
390         this->Config = new ServerConfig;
391         this->SNO = new SnomaskManager;
392         this->BanCache = new BanCacheManager;
393         this->Modules = new ModuleManager();
394         this->stats = new serverstats();
395         this->Timers = new TimerManager;
396         this->Parser = new CommandParser;
397         this->XLines = new XLineManager;
398
399         this->Config->cmdline.argv = argv;
400         this->Config->cmdline.argc = argc;
401
402 #ifdef _WIN32
403         srand(TIME.tv_nsec ^ TIME.tv_sec);
404
405         // Initialize the console values
406         g_hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
407         CONSOLE_SCREEN_BUFFER_INFO bufinf;
408         if(GetConsoleScreenBufferInfo(g_hStdout, &bufinf))
409         {
410                 g_wOriginalColors = bufinf.wAttributes & 0x00FF;
411                 g_wBackgroundColor = bufinf.wAttributes & 0x00F0;
412         }
413         else
414         {
415                 g_wOriginalColors = FOREGROUND_RED|FOREGROUND_BLUE|FOREGROUND_GREEN;
416                 g_wBackgroundColor = 0;
417         }
418 #else
419         srandom(TIME.tv_nsec ^ TIME.tv_sec);
420 #endif
421
422         struct option longopts[] =
423         {
424                 { "nofork",     no_argument,            &do_nofork,     1       },
425                 { "logfile",    required_argument,      NULL,           'f'     },
426                 { "config",     required_argument,      NULL,           'c'     },
427                 { "debug",      no_argument,            &do_debug,      1       },
428                 { "nolog",      no_argument,            &do_nolog,      1       },
429                 { "runasroot",  no_argument,            &do_root,       1       },
430                 { "version",    no_argument,            &do_version,    1       },
431                 { "testsuite",  no_argument,            &do_testsuite,  1       },
432                 { 0, 0, 0, 0 }
433         };
434
435         int index;
436         while ((c = getopt_long(argc, argv, ":c:f:", longopts, &index)) != -1)
437         {
438                 switch (c)
439                 {
440                         case 'f':
441                                 /* Log filename was set */
442                                 Config->cmdline.startup_log = optarg;
443                         break;
444                         case 'c':
445                                 /* Config filename was set */
446                                 ConfigFileName = optarg;
447                         break;
448                         case 0:
449                                 /* getopt_long_only() set an int variable, just keep going */
450                         break;
451                         case '?':
452                                 /* Unknown parameter */
453                         default:
454                                 /* Fall through to handle other weird values too */
455                                 std::cout << "Unknown parameter '" << argv[optind-1] << "'" << std::endl;
456                                 std::cout << "Usage: " << argv[0] << " [--nofork] [--nolog] [--debug] [--logfile <filename>] " << std::endl <<
457                                         std::string(static_cast<int>(8+strlen(argv[0])), ' ') << "[--runasroot] [--version] [--config <config>] [--testsuite]" << std::endl;
458                                 Exit(EXIT_STATUS_ARGV);
459                         break;
460                 }
461         }
462
463         if (do_testsuite)
464                 do_nofork = do_debug = true;
465
466         if (do_version)
467         {
468                 std::cout << std::endl << VERSION << " r" << REVISION << std::endl;
469                 Exit(EXIT_STATUS_NOERROR);
470         }
471
472 #ifdef _WIN32
473         // Set up winsock
474         WSADATA wsadata;
475         WSAStartup(MAKEWORD(2,2), &wsadata);
476 #endif
477
478         /* Set the finished argument values */
479         Config->cmdline.nofork = (do_nofork != 0);
480         Config->cmdline.forcedebug = (do_debug != 0);
481         Config->cmdline.writelog = !do_nolog;
482         Config->cmdline.TestSuite = (do_testsuite != 0);
483
484         if (do_debug)
485         {
486                 FileWriter* fw = new FileWriter(stdout);
487                 FileLogStream* fls = new FileLogStream(RAWIO, fw);
488                 Logs->AddLogTypes("*", fls, true);
489         }
490         else if (!this->OpenLog(argv, argc))
491         {
492                 std::cout << "ERROR: Could not open initial logfile " << Config->cmdline.startup_log << ": " << strerror(errno) << std::endl << std::endl;
493                 Exit(EXIT_STATUS_LOG);
494         }
495
496         if (!ServerConfig::FileExists(ConfigFileName.c_str()))
497         {
498 #ifdef _WIN32
499                 /* Windows can (and defaults to) hide file extensions, so let's play a bit nice for windows users. */
500                 std::string txtconf = this->ConfigFileName;
501                 txtconf.append(".txt");
502
503                 if (ServerConfig::FileExists(txtconf.c_str()))
504                 {
505                         ConfigFileName = txtconf;
506                 }
507                 else
508 #endif
509                 {
510                         std::cout << "ERROR: Cannot open config file: " << ConfigFileName << std::endl << "Exiting..." << std::endl;
511                         this->Logs->Log("STARTUP",DEFAULT,"Unable to open config file %s", ConfigFileName.c_str());
512                         Exit(EXIT_STATUS_CONFIG);
513                 }
514         }
515
516         std::cout << con_green << "Inspire Internet Relay Chat Server" << con_reset << ", compiled on " __DATE__ " at " __TIME__ << std::endl;
517         std::cout << con_green << "(C) InspIRCd Development Team." << con_reset << std::endl << std::endl;
518         std::cout << "Developers:" << std::endl;
519         std::cout << con_green << "\tBrain, FrostyCoolSlug, w00t, Om, Special, peavey" << std::endl;
520         std::cout << "\taquanight, psychon, dz, danieldg, jackmcbarn" << std::endl;\r
521         std::cout << "\tAttila" << con_reset << std::endl << std::endl;
522         std::cout << "Others:\t\t\t" << con_green << "See /INFO Output" << con_reset << std::endl;
523
524         this->Modes = new ModeParser;
525
526 #ifndef _WIN32
527         if (!do_root)
528                 this->CheckRoot();
529         else
530         {
531                 std::cout << "* WARNING * WARNING * WARNING * WARNING * WARNING *" << std::endl\r
532                 << "YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED" << std::endl\r
533                 << "AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED" << std::endl\r
534                 << "OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR" << std::endl\r
535                 << "SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN" << std::endl\r
536                 << "TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART" << std::endl\r
537                 << "THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!" << std::endl << std::endl\r
538                 << "InspIRCd starting in 20 seconds, ctrl+c to abort..." << std::endl;\r
539                 sleep(20);
540         }
541 #endif
542
543         this->SetSignals();
544
545         if (!Config->cmdline.nofork)
546         {
547                 if (!this->DaemonSeed())
548                 {
549                         std::cout << "ERROR: could not go into daemon mode. Shutting down." << std::endl;
550                         Logs->Log("STARTUP", DEFAULT, "ERROR: could not go into daemon mode. Shutting down.");
551                         Exit(EXIT_STATUS_FORK);
552                 }
553         }
554
555         SE->RecoverFromFork();
556
557         /* During startup we don't actually initialize this
558          * in the thread engine.
559          */
560         this->Config->Read();
561         this->Config->Apply(NULL, "");
562         Logs->OpenFileLogs();
563
564         this->Res = new DNS();
565
566         /*
567          * Initialise SID/UID.
568          * For an explanation as to exactly how this works, and why it works this way, see GetUID().
569          *   -- w00t
570          */
571         if (Config->sid.empty())
572         {
573                 // Generate one
574                 unsigned int sid = 0;
575                 char sidstr[4];
576
577                 for (const char* x = Config->ServerName.c_str(); *x; ++x)
578                         sid = 5 * sid + *x;
579                 for (const char* y = Config->ServerDesc.c_str(); *y; ++y)
580                         sid = 5 * sid + *y;
581                 sprintf(sidstr, "%03d", sid % 1000);
582
583                 Config->sid = sidstr;
584         }
585
586         /* set up fake client again this time with the correct uid */
587         this->FakeClient = new FakeUser(Config->sid, Config->ServerName);
588
589         // Get XLine to do it's thing.
590         this->XLines->CheckELines();
591         this->XLines->ApplyLines();
592
593         int bounditems = BindPorts(pl);
594
595         std::cout << std::endl;
596
597         this->Modules->LoadAll();
598
599         /* Just in case no modules were loaded - fix for bug #101 */
600         this->BuildISupport();
601         Config->ApplyDisabledCommands(Config->DisabledCommands);
602
603         if (!pl.empty())
604         {
605                 std::cout << std::endl << "WARNING: Not all your client ports could be bound -- " << std::endl << "starting anyway with " << bounditems
606                         << " of " << bounditems + (int)pl.size() << " client ports bound." << std::endl << std::endl;
607                 std::cout << "The following port(s) failed to bind:" << std::endl << std::endl;
608                 int j = 1;
609                 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
610                 {
611                         std::cout << j << ".\tAddress: " << (i->first.empty() ? "<all>" : i->first) << " \tReason: " << i->second << std::endl;
612                 }
613
614                 std::cout << std::endl << "Hint: Try using a public IP instead of blank or *" << std::endl;
615         }
616
617         std::cout << "InspIRCd is now running as '" << Config->ServerName << "'[" << Config->GetSID() << "] with " << SE->GetMaxFds() << " max open sockets" << std::endl;
618
619 #ifndef _WIN32
620         if (!Config->cmdline.nofork)
621         {
622                 if (kill(getppid(), SIGTERM) == -1)
623                 {
624                         std::cout << "Error killing parent process: " << strerror(errno) << std::endl;
625                         Logs->Log("STARTUP", DEFAULT, "Error killing parent process: %s",strerror(errno));
626                 }
627         }
628
629         /* Explicitly shut down stdio's stdin/stdout/stderr.
630          *
631          * The previous logic here was to only do this if stdio was connected to a controlling
632          * terminal.  However, we must do this always to avoid information leaks and other
633          * problems related to stdio.
634          *
635          * The only exception is if we are in debug mode.
636          *
637          *    -- nenolod
638          */
639         if ((!do_nofork) && (!do_testsuite) && (!Config->cmdline.forcedebug))
640         {
641                 int fd = open("/dev/null", O_RDWR);
642
643                 fclose(stdin);
644                 fclose(stderr);
645                 fclose(stdout);
646
647                 if (dup2(fd, STDIN_FILENO) < 0)
648                         Logs->Log("STARTUP", DEFAULT, "Failed to dup /dev/null to stdin.");
649                 if (dup2(fd, STDOUT_FILENO) < 0)
650                         Logs->Log("STARTUP", DEFAULT, "Failed to dup /dev/null to stdout.");
651                 if (dup2(fd, STDERR_FILENO) < 0)
652                         Logs->Log("STARTUP", DEFAULT, "Failed to dup /dev/null to stderr.");
653                 close(fd);
654         }
655         else
656         {
657                 Logs->Log("STARTUP", DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
658         }
659 #else
660         /* Set win32 service as running, if we are running as a service */
661         SetServiceRunning();
662
663         // Handle forking
664         if(!do_nofork)
665         {
666                 FreeConsole();
667         }
668
669         QueryPerformanceFrequency(&stats->QPFrequency);
670 #endif
671
672         Logs->Log("STARTUP", DEFAULT, "Startup complete as '%s'[%s], %d max open sockets", Config->ServerName.c_str(),Config->GetSID().c_str(), SE->GetMaxFds());
673
674 #ifndef _WIN32
675         std::string SetUser = Config->ConfValue("security")->getString("runasuser");
676         std::string SetGroup = Config->ConfValue("security")->getString("runasgroup");
677         if (!SetGroup.empty())
678         {
679                 int ret;
680
681                 // setgroups
682                 ret = setgroups(0, NULL);
683
684                 if (ret == -1)
685                 {
686                         this->Logs->Log("SETGROUPS", DEFAULT, "setgroups() failed (wtf?): %s", strerror(errno));
687                         this->QuickExit(0);
688                 }
689
690                 // setgid
691                 struct group *g;
692
693                 errno = 0;
694                 g = getgrnam(SetGroup.c_str());
695
696                 if (!g)
697                 {
698                         this->Logs->Log("SETGUID", DEFAULT, "getgrnam(%s) failed (wrong group?): %s", SetGroup.c_str(), strerror(errno));
699                         this->QuickExit(0);
700                 }
701
702                 ret = setgid(g->gr_gid);
703
704                 if (ret == -1)
705                 {
706                         this->Logs->Log("SETGUID", DEFAULT, "setgid() failed (wrong group?): %s", strerror(errno));
707                         this->QuickExit(0);
708                 }
709         }
710
711         if (!SetUser.empty())
712         {
713                 // setuid
714                 struct passwd *u;
715
716                 errno = 0;
717                 u = getpwnam(SetUser.c_str());
718
719                 if (!u)
720                 {
721                         this->Logs->Log("SETGUID", DEFAULT, "getpwnam(%s) failed (wrong user?): %s", SetUser.c_str(), strerror(errno));
722                         this->QuickExit(0);
723                 }
724
725                 int ret = setuid(u->pw_uid);
726
727                 if (ret == -1)
728                 {
729                         this->Logs->Log("SETGUID", DEFAULT, "setuid() failed (wrong user?): %s", strerror(errno));
730                         this->QuickExit(0);
731                 }
732         }
733
734         this->WritePID(Config->PID);
735 #endif
736 }
737
738 void InspIRCd::UpdateTime()
739 {
740 #ifdef _WIN32
741         SYSTEMTIME st;
742         GetSystemTime(&st);
743
744         TIME.tv_sec = time(NULL);
745         TIME.tv_nsec = st.wMilliseconds;
746 #else
747         #ifdef HAS_CLOCK_GETTIME
748                 clock_gettime(CLOCK_REALTIME, &TIME);
749         #else
750                 struct timeval tv;
751                 gettimeofday(&tv, NULL);
752                 TIME.tv_sec = tv.tv_sec;
753                 TIME.tv_nsec = tv.tv_usec * 1000;
754         #endif
755 #endif
756 }
757
758 int InspIRCd::Run()
759 {
760         /* See if we're supposed to be running the test suite rather than entering the mainloop */
761         if (Config->cmdline.TestSuite)
762         {
763                 TestSuite* ts = new TestSuite;
764                 delete ts;
765                 Exit(0);
766         }
767
768         UpdateTime();
769         time_t OLDTIME = TIME.tv_sec;
770
771         while (true)
772         {
773 #ifndef _WIN32
774                 static rusage ru;
775 #endif
776
777                 /* Check if there is a config thread which has finished executing but has not yet been freed */
778                 if (this->ConfigThread && this->ConfigThread->IsDone())
779                 {
780                         /* Rehash has completed */
781                         this->Logs->Log("CONFIG",DEBUG,"Detected ConfigThread exiting, tidying up...");
782
783                         this->ConfigThread->Finish();
784
785                         ConfigThread->join();
786                         delete ConfigThread;
787                         ConfigThread = NULL;
788                 }
789
790                 UpdateTime();
791
792                 /* Run background module timers every few seconds
793                  * (the docs say modules shouldnt rely on accurate
794                  * timing using this event, so we dont have to
795                  * time this exactly).
796                  */
797                 if (TIME.tv_sec != OLDTIME)
798                 {
799 #ifndef _WIN32
800                         getrusage(RUSAGE_SELF, &ru);
801                         stats->LastSampled = TIME;
802                         stats->LastCPU = ru.ru_utime;
803 #else
804                         if(QueryPerformanceCounter(&stats->LastSampled))
805                         {
806                                 FILETIME CreationTime;
807                                 FILETIME ExitTime;
808                                 FILETIME KernelTime;
809                                 FILETIME UserTime;
810                                 GetProcessTimes(GetCurrentProcess(), &CreationTime, &ExitTime, &KernelTime, &UserTime);
811                                 stats->LastCPU.dwHighDateTime = KernelTime.dwHighDateTime + UserTime.dwHighDateTime;
812                                 stats->LastCPU.dwLowDateTime = KernelTime.dwLowDateTime + UserTime.dwLowDateTime;
813                         }
814 #endif
815
816                         /* Allow a buffer of two seconds drift on this so that ntpdate etc dont harass admins */
817                         if (TIME.tv_sec < OLDTIME - 2)
818                         {
819                                 SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %lu secs.", (unsigned long)(OLDTIME-TIME.tv_sec));
820                         }
821                         else if (TIME.tv_sec > OLDTIME + 2)
822                         {
823                                 SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is jumping FORWARDS! Clock skipped %lu secs.", (unsigned long)(TIME.tv_sec - OLDTIME));
824                         }
825 \r
826                         OLDTIME = TIME.tv_sec;
827
828                         if ((TIME.tv_sec % 3600) == 0)
829                         {
830                                 this->RehashUsersAndChans();
831                                 FOREACH_MOD(I_OnGarbageCollect, OnGarbageCollect());
832                         }
833
834                         Timers->TickTimers(TIME.tv_sec);
835                         this->DoBackgroundUserStuff();
836
837                         if ((TIME.tv_sec % 5) == 0)
838                         {
839                                 FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME.tv_sec));
840                                 SNO->FlushSnotices();
841                         }
842                 }
843
844                 /* Call the socket engine to wait on the active
845                  * file descriptors. The socket engine has everything's
846                  * descriptors in its list... dns, modules, users,
847                  * servers... so its nice and easy, just one call.
848                  * This will cause any read or write events to be
849                  * dispatched to their handlers.
850                  */
851                 this->SE->DispatchTrialWrites();
852                 this->SE->DispatchEvents();
853
854                 /* if any users were quit, take them out */
855                 GlobalCulls.Apply();
856                 AtomicActions.Run();
857
858                 if (s_signal)
859                 {
860                         this->SignalHandler(s_signal);
861                         s_signal = 0;
862                 }
863         }
864
865         return 0;
866 }
867
868 /**********************************************************************************/
869
870 /**
871  * An ircd in five lines! bwahahaha. ahahahahaha. ahahah *cough*.
872  */
873
874 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
875  * (until this returns true, a user will block in the waiting state, waiting to connect up to the
876  * registration timeout maximum seconds)
877  */
878 bool InspIRCd::AllModulesReportReady(LocalUser* user)
879 {
880         ModResult res;
881         FIRST_MOD_RESULT(OnCheckReady, res, (user));
882         return (res == MOD_RES_PASSTHRU);
883 }
884
885 sig_atomic_t InspIRCd::s_signal = 0;
886
887 void InspIRCd::SetSignal(int signal)
888 {
889         s_signal = signal;
890 }
891
892 /* On posix systems, the flow of the program starts right here, with
893  * ENTRYPOINT being a #define that defines main(). On Windows, ENTRYPOINT
894  * defines smain() and the real main() is in the service code under
895  * win32service.cpp. This allows the service control manager to control
896  * the process where we are running as a windows service.
897  */
898 ENTRYPOINT
899 {
900         new InspIRCd(argc, argv);
901         ServerInstance->Run();
902         delete ServerInstance;
903         return 0;
904 }