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