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