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