]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
Stop recreating hashmaps every hour, move garbage collection code related to local...
[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 void InspIRCd::SetSignals()
195 {
196 #ifndef _WIN32
197         signal(SIGALRM, SIG_IGN);
198         signal(SIGHUP, InspIRCd::SetSignal);
199         signal(SIGPIPE, SIG_IGN);
200         signal(SIGCHLD, SIG_IGN);
201         /* We want E2BIG not a signal! */
202         signal(SIGXFSZ, SIG_IGN);
203 #endif
204         signal(SIGTERM, InspIRCd::SetSignal);
205 }
206
207 void InspIRCd::QuickExit(int status)
208 {
209         exit(0);
210 }
211
212 bool InspIRCd::DaemonSeed()
213 {
214 #ifdef _WIN32
215         std::cout << "InspIRCd Process ID: " << con_green << GetCurrentProcessId() << con_reset << std::endl;
216         return true;
217 #else
218         signal(SIGTERM, InspIRCd::QuickExit);
219
220         int childpid;
221         if ((childpid = fork ()) < 0)
222                 return false;
223         else if (childpid > 0)
224         {
225                 /* We wait here for the child process to kill us,
226                  * so that the shell prompt doesnt come back over
227                  * the output.
228                  * Sending a kill with a signal of 0 just checks
229                  * if the child pid is still around. If theyre not,
230                  * they threw an error and we should give up.
231                  */
232                 while (kill(childpid, 0) != -1)
233                         sleep(1);
234                 exit(0);
235         }
236         setsid ();
237         std::cout << "InspIRCd Process ID: " << con_green << getpid() << con_reset << std::endl;
238
239         signal(SIGTERM, InspIRCd::SetSignal);
240
241         rlimit rl;
242         if (getrlimit(RLIMIT_CORE, &rl) == -1)
243         {
244                 this->Logs->Log("STARTUP",DEFAULT,"Failed to getrlimit()!");
245                 return false;
246         }
247         rl.rlim_cur = rl.rlim_max;
248
249         if (setrlimit(RLIMIT_CORE, &rl) == -1)
250                         this->Logs->Log("STARTUP",DEFAULT,"setrlimit() failed, cannot increase coredump size.");
251
252         return true;
253 #endif
254 }
255
256 void InspIRCd::WritePID(const std::string &filename)
257 {
258 #ifndef _WIN32
259         std::string fname(filename);
260         if (fname.empty())
261                 fname = DATA_PATH "/inspircd.pid";
262         std::ofstream outfile(fname.c_str());
263         if (outfile.is_open())
264         {
265                 outfile << getpid();
266                 outfile.close();
267         }
268         else
269         {
270                 std::cout << "Failed to write PID-file '" << fname << "', exiting." << std::endl;
271                 this->Logs->Log("STARTUP",DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
272                 Exit(EXIT_STATUS_PID);
273         }
274 #endif
275 }
276
277 InspIRCd::InspIRCd(int argc, char** argv) :
278          ConfigFileName(CONFIG_PATH "/inspircd.conf"),
279
280          /* Functor pointer initialisation.
281           *
282           * THIS MUST MATCH THE ORDER OF DECLARATION OF THE FUNCTORS, e.g. the methods
283           * themselves within the class.
284           */
285          NICKForced("NICKForced", NULL),
286          OperQuit("OperQuit", NULL),
287          GenRandom(&HandleGenRandom),
288          IsChannel(&HandleIsChannel),
289          Rehash(&HandleRehash),
290          IsNick(&HandleIsNick),
291          IsIdent(&HandleIsIdent),
292          OnCheckExemption(&HandleOnCheckExemption)
293 {
294         ServerInstance = this;
295
296         Extensions.Register(&NICKForced);
297         Extensions.Register(&OperQuit);
298
299         FailedPortList pl;
300         int do_version = 0, do_nofork = 0, do_debug = 0,
301             do_nolog = 0, do_root = 0, do_testsuite = 0;    /* flag variables */
302         int c = 0;
303
304         // Initialize so that if we exit before proper initialization they're not deleted
305         this->Logs = 0;
306         this->Threads = 0;
307         this->PI = 0;
308         this->Users = 0;
309         this->chanlist = 0;
310         this->Config = 0;
311         this->SNO = 0;
312         this->BanCache = 0;
313         this->Modules = 0;
314         this->stats = 0;
315         this->Timers = 0;
316         this->Parser = 0;
317         this->XLines = 0;
318         this->Modes = 0;
319         this->Res = 0;
320         this->ConfigThread = NULL;
321         this->FakeClient = NULL;
322
323         UpdateTime();
324         this->startup_time = TIME.tv_sec;
325
326         // This must be created first, so other parts of Insp can use it while starting up
327         this->Logs = new LogManager;
328
329         SE = CreateSocketEngine();
330
331         this->Threads = new ThreadEngine;
332
333         /* Default implementation does nothing */
334         this->PI = new ProtocolInterface;
335
336         this->s_signal = 0;
337
338         // Create base manager classes early, so nothing breaks
339         this->Users = new UserManager;
340
341         this->Users->unregistered_count = 0;
342
343         this->Users->clientlist = new user_hash();
344         this->Users->uuidlist = new user_hash();
345         this->chanlist = new chan_hash();
346
347         this->Config = new ServerConfig;
348         this->SNO = new SnomaskManager;
349         this->BanCache = new BanCacheManager;
350         this->Modules = new ModuleManager();
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
520         this->Res = new DNS();
521
522         /*
523          * Initialise SID/UID.
524          * For an explanation as to exactly how this works, and why it works this way, see GetUID().
525          *   -- w00t
526          */
527         if (Config->sid.empty())
528         {
529                 // Generate one
530                 unsigned int sid = 0;
531                 char sidstr[4];
532
533                 for (const char* x = Config->ServerName.c_str(); *x; ++x)
534                         sid = 5 * sid + *x;
535                 for (const char* y = Config->ServerDesc.c_str(); *y; ++y)
536                         sid = 5 * sid + *y;
537                 sprintf(sidstr, "%03d", sid % 1000);
538
539                 Config->sid = sidstr;
540         }
541
542         /* set up fake client again this time with the correct uid */
543         this->FakeClient = new FakeUser(Config->sid, Config->ServerName);
544
545         // Get XLine to do it's thing.
546         this->XLines->CheckELines();
547         this->XLines->ApplyLines();
548
549         int bounditems = BindPorts(pl);
550
551         std::cout << std::endl;
552
553         this->Modules->LoadAll();
554
555         /* Just in case no modules were loaded - fix for bug #101 */
556         this->BuildISupport();
557         Config->ApplyDisabledCommands(Config->DisabledCommands);
558
559         if (!pl.empty())
560         {
561                 std::cout << std::endl << "WARNING: Not all your client ports could be bound -- " << std::endl << "starting anyway with " << bounditems
562                         << " of " << bounditems + (int)pl.size() << " client ports bound." << std::endl << std::endl;
563                 std::cout << "The following port(s) failed to bind:" << std::endl << std::endl;
564                 int j = 1;
565                 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
566                 {
567                         std::cout << j << ".\tAddress: " << (i->first.empty() ? "<all>" : i->first) << " \tReason: " << i->second << std::endl;
568                 }
569
570                 std::cout << std::endl << "Hint: Try using a public IP instead of blank or *" << std::endl;
571         }
572
573         std::cout << "InspIRCd is now running as '" << Config->ServerName << "'[" << Config->GetSID() << "] with " << SE->GetMaxFds() << " max open sockets" << std::endl;
574
575 #ifndef _WIN32
576         if (!Config->cmdline.nofork)
577         {
578                 if (kill(getppid(), SIGTERM) == -1)
579                 {
580                         std::cout << "Error killing parent process: " << strerror(errno) << std::endl;
581                         Logs->Log("STARTUP", DEFAULT, "Error killing parent process: %s",strerror(errno));
582                 }
583         }
584
585         /* Explicitly shut down stdio's stdin/stdout/stderr.
586          *
587          * The previous logic here was to only do this if stdio was connected to a controlling
588          * terminal.  However, we must do this always to avoid information leaks and other
589          * problems related to stdio.
590          *
591          * The only exception is if we are in debug mode.
592          *
593          *    -- nenolod
594          */
595         if ((!do_nofork) && (!do_testsuite) && (!Config->cmdline.forcedebug))
596         {
597                 int fd = open("/dev/null", O_RDWR);
598
599                 fclose(stdin);
600                 fclose(stderr);
601                 fclose(stdout);
602
603                 if (dup2(fd, STDIN_FILENO) < 0)
604                         Logs->Log("STARTUP", DEFAULT, "Failed to dup /dev/null to stdin.");
605                 if (dup2(fd, STDOUT_FILENO) < 0)
606                         Logs->Log("STARTUP", DEFAULT, "Failed to dup /dev/null to stdout.");
607                 if (dup2(fd, STDERR_FILENO) < 0)
608                         Logs->Log("STARTUP", DEFAULT, "Failed to dup /dev/null to stderr.");
609                 close(fd);
610         }
611         else
612         {
613                 Logs->Log("STARTUP", DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
614         }
615 #else
616         /* Set win32 service as running, if we are running as a service */
617         SetServiceRunning();
618
619         // Handle forking
620         if(!do_nofork)
621         {
622                 FreeConsole();
623         }
624
625         QueryPerformanceFrequency(&stats->QPFrequency);
626 #endif
627
628         Logs->Log("STARTUP", DEFAULT, "Startup complete as '%s'[%s], %d max open sockets", Config->ServerName.c_str(),Config->GetSID().c_str(), SE->GetMaxFds());
629
630 #ifndef _WIN32
631         std::string SetUser = Config->ConfValue("security")->getString("runasuser");
632         std::string SetGroup = Config->ConfValue("security")->getString("runasgroup");
633         if (!SetGroup.empty())
634         {
635                 int ret;
636
637                 // setgroups
638                 ret = setgroups(0, NULL);
639
640                 if (ret == -1)
641                 {
642                         this->Logs->Log("SETGROUPS", DEFAULT, "setgroups() failed (wtf?): %s", strerror(errno));
643                         this->QuickExit(0);
644                 }
645
646                 // setgid
647                 struct group *g;
648
649                 errno = 0;
650                 g = getgrnam(SetGroup.c_str());
651
652                 if (!g)
653                 {
654                         this->Logs->Log("SETGUID", DEFAULT, "getgrnam() failed (bad user?): %s", strerror(errno));
655                         this->QuickExit(0);
656                 }
657
658                 ret = setgid(g->gr_gid);
659
660                 if (ret == -1)
661                 {
662                         this->Logs->Log("SETGUID", DEFAULT, "setgid() failed (bad user?): %s", strerror(errno));
663                         this->QuickExit(0);
664                 }
665         }
666
667         if (!SetUser.empty())
668         {
669                 // setuid
670                 struct passwd *u;
671
672                 errno = 0;
673                 u = getpwnam(SetUser.c_str());
674
675                 if (!u)
676                 {
677                         this->Logs->Log("SETGUID", DEFAULT, "getpwnam() failed (bad user?): %s", strerror(errno));
678                         this->QuickExit(0);
679                 }
680
681                 int ret = setuid(u->pw_uid);
682
683                 if (ret == -1)
684                 {
685                         this->Logs->Log("SETGUID", DEFAULT, "setuid() failed (bad user?): %s", strerror(errno));
686                         this->QuickExit(0);
687                 }
688         }
689
690         this->WritePID(Config->PID);
691 #endif
692 }
693
694 void InspIRCd::UpdateTime()
695 {
696 #ifdef _WIN32
697         SYSTEMTIME st;
698         GetSystemTime(&st);
699
700         TIME.tv_sec = time(NULL);
701         TIME.tv_nsec = st.wMilliseconds;
702 #else
703         #ifdef HAS_CLOCK_GETTIME
704                 clock_gettime(CLOCK_REALTIME, &TIME);
705         #else
706                 struct timeval tv;
707                 gettimeofday(&tv, NULL);
708                 TIME.tv_sec = tv.tv_sec;
709                 TIME.tv_nsec = tv.tv_usec * 1000;
710         #endif
711 #endif
712 }
713
714 int InspIRCd::Run()
715 {
716         /* See if we're supposed to be running the test suite rather than entering the mainloop */
717         if (Config->cmdline.TestSuite)
718         {
719                 TestSuite* ts = new TestSuite;
720                 delete ts;
721                 Exit(0);
722         }
723
724         UpdateTime();
725         time_t OLDTIME = TIME.tv_sec;
726
727         while (true)
728         {
729 #ifndef _WIN32
730                 static rusage ru;
731 #endif
732
733                 /* Check if there is a config thread which has finished executing but has not yet been freed */
734                 if (this->ConfigThread && this->ConfigThread->IsDone())
735                 {
736                         /* Rehash has completed */
737                         this->Logs->Log("CONFIG",DEBUG,"Detected ConfigThread exiting, tidying up...");
738
739                         this->ConfigThread->Finish();
740
741                         ConfigThread->join();
742                         delete ConfigThread;
743                         ConfigThread = NULL;
744                 }
745
746                 UpdateTime();
747
748                 /* Run background module timers every few seconds
749                  * (the docs say modules shouldnt rely on accurate
750                  * timing using this event, so we dont have to
751                  * time this exactly).
752                  */
753                 if (TIME.tv_sec != OLDTIME)
754                 {
755 #ifndef _WIN32
756                         getrusage(RUSAGE_SELF, &ru);
757                         stats->LastSampled = TIME;
758                         stats->LastCPU = ru.ru_utime;
759 #else
760                         if(QueryPerformanceCounter(&stats->LastSampled))
761                         {
762                                 FILETIME CreationTime;
763                                 FILETIME ExitTime;
764                                 FILETIME KernelTime;
765                                 FILETIME UserTime;
766                                 GetProcessTimes(GetCurrentProcess(), &CreationTime, &ExitTime, &KernelTime, &UserTime);
767                                 stats->LastCPU.dwHighDateTime = KernelTime.dwHighDateTime + UserTime.dwHighDateTime;
768                                 stats->LastCPU.dwLowDateTime = KernelTime.dwLowDateTime + UserTime.dwLowDateTime;
769                         }
770 #endif
771
772                         /* Allow a buffer of two seconds drift on this so that ntpdate etc dont harass admins */
773                         if (TIME.tv_sec < OLDTIME - 2)
774                         {
775                                 SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %lu secs.", (unsigned long)OLDTIME-TIME.tv_sec);
776                         }
777                         else if (TIME.tv_sec > OLDTIME + 2)
778                         {
779                                 SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is jumping FORWARDS! Clock skipped %lu secs.", (unsigned long)TIME.tv_sec - OLDTIME);
780                         }
781
782                         OLDTIME = TIME.tv_sec;
783
784                         if ((TIME.tv_sec % 3600) == 0)
785                         {
786                                 Users->GarbageCollect();
787                                 FOREACH_MOD(I_OnGarbageCollect, OnGarbageCollect());
788                         }
789
790                         Timers->TickTimers(TIME.tv_sec);
791                         this->DoBackgroundUserStuff();
792
793                         if ((TIME.tv_sec % 5) == 0)
794                         {
795                                 FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME.tv_sec));
796                                 SNO->FlushSnotices();
797                         }
798                 }
799
800                 /* Call the socket engine to wait on the active
801                  * file descriptors. The socket engine has everything's
802                  * descriptors in its list... dns, modules, users,
803                  * servers... so its nice and easy, just one call.
804                  * This will cause any read or write events to be
805                  * dispatched to their handlers.
806                  */
807                 this->SE->DispatchTrialWrites();
808                 this->SE->DispatchEvents();
809
810                 /* if any users were quit, take them out */
811                 GlobalCulls.Apply();
812                 AtomicActions.Run();
813
814                 if (this->s_signal)
815                 {
816                         this->SignalHandler(s_signal);
817                         this->s_signal = 0;
818                 }
819         }
820
821         return 0;
822 }
823
824 /**********************************************************************************/
825
826 /**
827  * An ircd in five lines! bwahahaha. ahahahahaha. ahahah *cough*.
828  */
829
830 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
831  * (until this returns true, a user will block in the waiting state, waiting to connect up to the
832  * registration timeout maximum seconds)
833  */
834 bool InspIRCd::AllModulesReportReady(LocalUser* user)
835 {
836         ModResult res;
837         FIRST_MOD_RESULT(OnCheckReady, res, (user));
838         return (res == MOD_RES_PASSTHRU);
839 }
840
841 void InspIRCd::SetSignal(int signal)
842 {
843         *mysig = signal;
844 }
845
846 /* On posix systems, the flow of the program starts right here, with
847  * ENTRYPOINT being a #define that defines main(). On Windows, ENTRYPOINT
848  * defines smain() and the real main() is in the service code under
849  * win32service.cpp. This allows the service control manager to control
850  * the process where we are running as a windows service.
851  */
852 ENTRYPOINT
853 {
854         new InspIRCd(argc, argv);
855         mysig = &ServerInstance->s_signal;
856         ServerInstance->Run();
857         delete ServerInstance;
858         return 0;
859 }