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