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