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