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