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