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