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