]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
Fix module unmapping with culled Module objects
[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         GlobalCulls.Apply();
115         Modules->UnloadAll();
116
117         /* Delete objects dynamically allocated in constructor (destructor would be more appropriate, but we're likely exiting) */
118         /* Must be deleted before modes as it decrements modelines */
119         DeleteZero(this->FakeClient);
120         DeleteZero(this->Users);
121         DeleteZero(this->Modes);
122         DeleteZero(this->XLines);
123         DeleteZero(this->Parser);
124         DeleteZero(this->stats);
125         DeleteZero(this->Modules);
126         DeleteZero(this->BanCache);
127         DeleteZero(this->SNO);
128         DeleteZero(this->Config);
129         DeleteZero(this->Res);
130         DeleteZero(this->chanlist);
131         DeleteZero(this->PI);
132         DeleteZero(this->Threads);
133         DeleteZero(this->Timers);
134         DeleteZero(this->SE);
135         /* Close logging */
136         this->Logs->CloseLogs();
137         DeleteZero(this->Logs);
138 }
139
140 void InspIRCd::Restart(const std::string &reason)
141 {
142         /* SendError flushes each client's queue,
143          * regardless of writeability state
144          */
145         this->SendError(reason);
146
147         /* Figure out our filename (if theyve renamed it, we're boned) */
148         std::string me;
149
150 #ifdef WINDOWS
151         char module[MAX_PATH];
152         if (GetModuleFileName(NULL, module, MAX_PATH))
153                 me = module;
154 #else
155         me = Config->MyDir + "/inspircd";
156 #endif
157
158         char** argv = Config->argv;
159
160         this->Cleanup();
161
162         if (execv(me.c_str(), argv) == -1)
163         {
164                 /* Will raise a SIGABRT if not trapped */
165                 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
166         }
167 }
168
169 void InspIRCd::ResetMaxBans()
170 {
171         for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
172                 i->second->ResetMaxBans();
173 }
174
175 /** Because hash_map doesnt free its buckets when we delete items (this is a 'feature')
176  * we must occasionally rehash the hash (yes really).
177  * We do this by copying the entries from the old hash to a new hash, causing all
178  * empty buckets to be weeded out of the hash. We dont do this on a timer, as its
179  * very expensive, so instead we do it when the user types /REHASH and expects a
180  * short delay anyway.
181  */
182 void InspIRCd::RehashUsersAndChans()
183 {
184         user_hash* old_users = this->Users->clientlist;
185         user_hash* old_uuid  = this->Users->uuidlist;
186         chan_hash* old_chans = this->chanlist;
187
188         this->Users->clientlist = new user_hash();
189         this->Users->uuidlist = new user_hash();
190         this->chanlist = new chan_hash();
191
192         for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
193                 this->Users->clientlist->insert(*n);
194
195         delete old_users;
196
197         for (user_hash::const_iterator n = old_uuid->begin(); n != old_uuid->end(); n++)
198                 this->Users->uuidlist->insert(*n);
199
200         delete old_uuid;
201
202         for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
203                 this->chanlist->insert(*n);
204
205         delete old_chans;
206 }
207
208 void InspIRCd::SetSignals()
209 {
210 #ifndef WIN32
211         signal(SIGALRM, SIG_IGN);
212         signal(SIGHUP, InspIRCd::SetSignal);
213         signal(SIGPIPE, SIG_IGN);
214         signal(SIGCHLD, SIG_IGN);
215         /* We want E2BIG not a signal! */
216         signal(SIGXFSZ, SIG_IGN);
217 #endif
218         signal(SIGTERM, InspIRCd::SetSignal);
219 }
220
221 void InspIRCd::QuickExit(int status)
222 {
223         exit(0);
224 }
225
226 bool InspIRCd::DaemonSeed()
227 {
228 #ifdef WINDOWS
229         printf_c("InspIRCd Process ID: \033[1;32m%lu\033[0m\n", GetCurrentProcessId());
230         return true;
231 #else
232         signal(SIGTERM, InspIRCd::QuickExit);
233
234         int childpid;
235         if ((childpid = fork ()) < 0)
236                 return false;
237         else if (childpid > 0)
238         {
239                 /* We wait here for the child process to kill us,
240                  * so that the shell prompt doesnt come back over
241                  * the output.
242                  * Sending a kill with a signal of 0 just checks
243                  * if the child pid is still around. If theyre not,
244                  * they threw an error and we should give up.
245                  */
246                 while (kill(childpid, 0) != -1)
247                         sleep(1);
248                 exit(0);
249         }
250         setsid ();
251         umask (007);
252         printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
253
254         signal(SIGTERM, InspIRCd::SetSignal);
255
256         rlimit rl;
257         if (getrlimit(RLIMIT_CORE, &rl) == -1)
258         {
259                 this->Logs->Log("STARTUP",DEFAULT,"Failed to getrlimit()!");
260                 return false;
261         }
262         rl.rlim_cur = rl.rlim_max;
263
264         if (setrlimit(RLIMIT_CORE, &rl) == -1)
265                         this->Logs->Log("STARTUP",DEFAULT,"setrlimit() failed, cannot increase coredump size.");
266
267         return true;
268 #endif
269 }
270
271 void InspIRCd::WritePID(const std::string &filename)
272 {
273         std::string fname(filename);
274         if (fname.empty())
275                 fname = "data/inspircd.pid";
276         std::ofstream outfile(fname.c_str());
277         if (outfile.is_open())
278         {
279                 outfile << getpid();
280                 outfile.close();
281         }
282         else
283         {
284                 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
285                 this->Logs->Log("STARTUP",DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
286                 Exit(EXIT_STATUS_PID);
287         }
288 }
289
290 InspIRCd::InspIRCd(int argc, char** argv) :
291          ConfigFileName("inspircd.conf"),
292
293          /* Functor pointer initialisation.
294           *
295           * THIS MUST MATCH THE ORDER OF DECLARATION OF THE FUNCTORS, e.g. the methods
296           * themselves within the class.
297           */
298          NICKForced("NICKForced", NULL),
299          OperQuit("OperQuit", NULL),
300          IsChannel(&HandleIsChannel),
301          IsSID(&HandleIsSID),
302          Rehash(&HandleRehash),
303          IsNick(&HandleIsNick),
304          IsIdent(&HandleIsIdent),
305          FloodQuitUser(&HandleFloodQuitUser)
306 {
307 #ifdef WIN32
308         // Strict, frequent checking of memory on debug builds
309         _CrtSetDbgFlag ( _CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
310
311         // Avoid erroneous frees on early exit
312         WindowsIPC = 0;
313 #endif
314
315         ServerInstance = this;
316
317         Extensions.Register(&NICKForced);
318         Extensions.Register(&OperQuit);
319
320         FailedPortList pl;
321         int do_version = 0, do_nofork = 0, do_debug = 0,
322             do_nolog = 0, do_root = 0, do_testsuite = 0;    /* flag variables */
323         int c = 0;
324
325         // Initialize so that if we exit before proper initialization they're not deleted
326         this->Logs = 0;
327         this->Threads = 0;
328         this->PI = 0;
329         this->Users = 0;
330         this->chanlist = 0;
331         this->Config = 0;
332         this->SNO = 0;
333         this->BanCache = 0;
334         this->Modules = 0;
335         this->stats = 0;
336         this->Timers = 0;
337         this->Parser = 0;
338         this->XLines = 0;
339         this->Modes = 0;
340         this->Res = 0;
341         this->ConfigThread = NULL;
342
343         // Initialise TIME
344         this->TIME = time(NULL);
345
346         // This must be created first, so other parts of Insp can use it while starting up
347         this->Logs = new LogManager;
348
349         SE = CreateSocketEngine();
350
351         this->Threads = new ThreadEngine;
352
353         /* Default implementation does nothing */
354         this->PI = new ProtocolInterface;
355
356         this->s_signal = 0;
357
358         // Create base manager classes early, so nothing breaks
359         this->Users = new UserManager;
360
361         this->Users->unregistered_count = 0;
362
363         this->Users->clientlist = new user_hash();
364         this->Users->uuidlist = new user_hash();
365         this->chanlist = new chan_hash();
366
367         this->Config = new ServerConfig;
368         this->SNO = new SnomaskManager;
369         this->BanCache = new BanCacheManager;
370         this->Modules = new ModuleManager();
371         this->stats = new serverstats();
372         this->Timers = new TimerManager;
373         this->Parser = new CommandParser;
374         this->XLines = new XLineManager;
375
376         this->Config->argv = argv;
377         this->Config->argc = argc;
378
379         this->TIME = this->OLDTIME = this->startup_time = time(NULL);
380         srand(this->TIME);
381
382         *this->LogFileName = 0;
383
384         struct option longopts[] =
385         {
386                 { "nofork",     no_argument,            &do_nofork,     1       },
387                 { "logfile",    required_argument,      NULL,           'f'     },
388                 { "config",     required_argument,      NULL,           'c'     },
389                 { "debug",      no_argument,            &do_debug,      1       },
390                 { "nolog",      no_argument,            &do_nolog,      1       },
391                 { "runasroot",  no_argument,            &do_root,       1       },
392                 { "version",    no_argument,            &do_version,    1       },
393                 { "testsuite",  no_argument,            &do_testsuite,  1       },
394                 { 0, 0, 0, 0 }
395         };
396
397         int index;
398         while ((c = getopt_long_only(argc, argv, ":f:", longopts, &index)) != -1)
399         {
400                 switch (c)
401                 {
402                         case 'f':
403                                 /* Log filename was set */
404                                 strlcpy(LogFileName, optarg, MAXBUF);
405                         break;
406                         case 'c':
407                                 /* Config filename was set */
408                                 ConfigFileName = optarg;
409                         break;
410                         case 0:
411                                 /* getopt_long_only() set an int variable, just keep going */
412                         break;
413                         case '?':
414                                 /* Unknown parameter */
415                         default:
416                                 /* Fall through to handle other weird values too */
417                                 printf("Unknown parameter '%s'\n", argv[optind-1]);
418                                 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])), " ");
419                                 Exit(EXIT_STATUS_ARGV);
420                         break;
421                 }
422         }
423
424         if (do_testsuite)
425                 do_nofork = do_debug = true;
426
427         if (do_version)
428         {
429                 printf("\n%s r%s\n", VERSION, REVISION);
430                 Exit(EXIT_STATUS_NOERROR);
431         }
432
433 #ifdef WIN32
434
435         // Handle forking
436         if(!do_nofork)
437         {
438                 DWORD ExitCode = WindowsForkStart();
439                 if(ExitCode)
440                         exit(ExitCode);
441         }
442
443         // Set up winsock
444         WSADATA wsadata;
445         WSAStartup(MAKEWORD(2,0), &wsadata);
446         ChangeWindowsSpecificPointers();
447 #endif
448
449         /* Set the finished argument values */
450         Config->nofork = do_nofork;
451         Config->forcedebug = do_debug;
452         Config->writelog = !do_nolog;
453         Config->TestSuite = do_testsuite;
454
455         if (!this->OpenLog(argv, argc))
456         {
457                 printf("ERROR: Could not open logfile %s: %s\n\n", Config->logpath.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->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->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                         fclose(stdout);
603                 }
604                 else
605                 {
606                         Logs->Log("STARTUP", DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
607                 }
608         }
609 #else
610         WindowsIPC = new IPC;
611         if(!Config->nofork)
612         {
613                 WindowsForkKillOwner();
614                 FreeConsole();
615         }
616         /* Set win32 service as running, if we are running as a service */
617         SetServiceRunning();
618 #endif
619
620         Logs->Log("STARTUP", DEFAULT, "Startup complete as '%s'[%s], %d max open sockets", Config->ServerName.c_str(),Config->GetSID().c_str(), SE->GetMaxFds());
621
622 #ifndef WIN32
623         if (!Config->SetGroup.empty())
624         {
625                 int ret;
626
627                 // setgroups
628                 ret = setgroups(0, NULL);
629
630                 if (ret == -1)
631                 {
632                         this->Logs->Log("SETGROUPS", DEFAULT, "setgroups() failed (wtf?): %s", strerror(errno));
633                         this->QuickExit(0);
634                 }
635
636                 // setgid
637                 struct group *g;
638
639                 errno = 0;
640                 g = getgrnam(this->Config->SetGroup.c_str());
641
642                 if (!g)
643                 {
644                         this->Logs->Log("SETGUID", DEFAULT, "getgrnam() failed (bad user?): %s", strerror(errno));
645                         this->QuickExit(0);
646                 }
647
648                 ret = setgid(g->gr_gid);
649
650                 if (ret == -1)
651                 {
652                         this->Logs->Log("SETGUID", DEFAULT, "setgid() failed (bad user?): %s", strerror(errno));
653                         this->QuickExit(0);
654                 }
655         }
656
657         if (!Config->SetUser.empty())
658         {
659                 // setuid
660                 struct passwd *u;
661
662                 errno = 0;
663                 u = getpwnam(this->Config->SetUser.c_str());
664
665                 if (!u)
666                 {
667                         this->Logs->Log("SETGUID", DEFAULT, "getpwnam() failed (bad user?): %s", strerror(errno));
668                         this->QuickExit(0);
669                 }
670
671                 int ret = setuid(u->pw_uid);
672
673                 if (ret == -1)
674                 {
675                         this->Logs->Log("SETGUID", DEFAULT, "setuid() failed (bad user?): %s", strerror(errno));
676                         this->QuickExit(0);
677                 }
678         }
679 #endif
680
681         this->WritePID(Config->PID);
682 }
683
684 int InspIRCd::Run()
685 {
686         /* See if we're supposed to be running the test suite rather than entering the mainloop */
687         if (Config->TestSuite)
688         {
689                 TestSuite* ts = new TestSuite;
690                 delete ts;
691                 Exit(0);
692         }
693
694         while (true)
695         {
696 #ifndef WIN32
697                 static rusage ru;
698 #else
699                 static time_t uptime;
700                 static struct tm * stime;
701                 static char window_title[100];
702 #endif
703
704                 /* Check if there is a config thread which has finished executing but has not yet been freed */
705                 if (this->ConfigThread && this->ConfigThread->IsDone())
706                 {
707                         /* Rehash has completed */
708                         this->Logs->Log("CONFIG",DEBUG,"Detected ConfigThread exiting, tidying up...");
709
710                         this->ConfigThread->Finish();
711
712                         ConfigThread->join();
713                         delete ConfigThread;
714                         ConfigThread = NULL;
715                 }
716
717                 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
718                  * Once per loop iteration is pleanty.
719                  */
720                 OLDTIME = TIME;
721                 TIME = time(NULL);
722
723                 /* Run background module timers every few seconds
724                  * (the docs say modules shouldnt rely on accurate
725                  * timing using this event, so we dont have to
726                  * time this exactly).
727                  */
728                 if (TIME != OLDTIME)
729                 {
730                         /* Allow a buffer of two seconds drift on this so that ntpdate etc dont harass admins */
731                         if (TIME < OLDTIME - 2)
732                         {
733                                 SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %lu secs.", (unsigned long)OLDTIME-TIME);
734                         }
735                         else if (TIME > OLDTIME + 2)
736                         {
737                                 SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is jumping FORWARDS! Clock skipped %lu secs.", (unsigned long)TIME - OLDTIME);
738                         }
739
740                         if ((TIME % 3600) == 0)
741                         {
742                                 this->RehashUsersAndChans();
743                                 FOREACH_MOD(I_OnGarbageCollect, OnGarbageCollect());
744                         }
745
746                         Timers->TickTimers(TIME);
747                         this->DoBackgroundUserStuff();
748
749                         if ((TIME % 5) == 0)
750                         {
751                                 FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME));
752                                 SNO->FlushSnotices();
753                         }
754 #ifndef WIN32
755                         /* Same change as in cmd_stats.cpp, use RUSAGE_SELF rather than '0' -- Om */
756                         if (!getrusage(RUSAGE_SELF, &ru))
757                         {
758                                 gettimeofday(&this->stats->LastSampled, NULL);
759                                 this->stats->LastCPU = ru.ru_utime;
760                         }
761 #else
762                         WindowsIPC->Check();
763 #endif
764                 }
765
766                 /* Call the socket engine to wait on the active
767                  * file descriptors. The socket engine has everything's
768                  * descriptors in its list... dns, modules, users,
769                  * servers... so its nice and easy, just one call.
770                  * This will cause any read or write events to be
771                  * dispatched to their handlers.
772                  */
773                 this->SE->DispatchTrialWrites();
774                 this->SE->DispatchEvents();
775
776                 /* if any users were quit, take them out */
777                 GlobalCulls.Apply();
778                 AtomicActions.Run();
779
780                 if (this->s_signal)
781                 {
782                         this->SignalHandler(s_signal);
783                         this->s_signal = 0;
784                 }
785         }
786
787         return 0;
788 }
789
790 /**********************************************************************************/
791
792 /**
793  * An ircd in five lines! bwahahaha. ahahahahaha. ahahah *cough*.
794  */
795
796 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
797  * (until this returns true, a user will block in the waiting state, waiting to connect up to the
798  * registration timeout maximum seconds)
799  */
800 bool InspIRCd::AllModulesReportReady(User* user)
801 {
802         ModResult res;
803         FIRST_MOD_RESULT(OnCheckReady, res, (user));
804         return (res == MOD_RES_PASSTHRU);
805 }
806
807 time_t InspIRCd::Time()
808 {
809         return TIME;
810 }
811
812 void InspIRCd::SetSignal(int signal)
813 {
814         *mysig = signal;
815 }
816
817 /* On posix systems, the flow of the program starts right here, with
818  * ENTRYPOINT being a #define that defines main(). On Windows, ENTRYPOINT
819  * defines smain() and the real main() is in the service code under
820  * win32service.cpp. This allows the service control manager to control
821  * the process where we are running as a windows service.
822  */
823 ENTRYPOINT
824 {
825         new InspIRCd(argc, argv);
826         mysig = &ServerInstance->s_signal;
827         ServerInstance->Run();
828         delete ServerInstance;
829         return 0;
830 }