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