]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
Extract and run the vs redistributable to $TEMP, not to install dir. saves us 2.6...
[user/henk/code/inspircd.git] / src / inspircd.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2008 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *          the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 /* $Install: src/inspircd $(BINPATH) */
15 #include "inspircd.h"
16 #include <signal.h>
17
18 #ifndef WIN32
19         #include <dirent.h>
20         #include <unistd.h>
21         #include <sys/resource.h>
22         #include <dlfcn.h>
23         #include <getopt.h>
24
25         /* Some systems don't define RUSAGE_SELF. This should fix them. */
26         #ifndef RUSAGE_SELF
27                 #define RUSAGE_SELF 0
28         #endif
29
30         /* CRT memory debugging */
31         #ifdef DEBUG
32         #define _CRTDBG_MAP_ALLOC
33         #include <stdlib.h>
34         #include <crtdbg.h>
35         #endif
36 #endif
37
38 #include <fstream>
39 #include "xline.h"
40 #include "bancache.h"
41 #include "socketengine.h"
42 #include "inspircd_se_config.h"
43 #include "socket.h"
44 #include "command_parse.h"
45 #include "exitcodes.h"
46 #include "caller.h"
47 #include "testsuite.h"
48
49 using irc::sockets::insp_ntoa;
50 using irc::sockets::insp_inaddr;
51 using irc::sockets::insp_sockaddr;
52
53 InspIRCd* SI = NULL;
54 int* mysig = NULL;
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 };
79
80 void InspIRCd::Cleanup()
81 {
82         if (Config)
83         {
84                 for (unsigned int i = 0; i < Config->ports.size(); i++)
85                 {
86                         /* This calls the constructor and closes the listening socket */
87                         delete Config->ports[i];
88                 }
89
90                 Config->ports.clear();
91         }
92
93         /* Close all client sockets, or the new process inherits them */
94         for (std::vector<User*>::const_iterator i = this->Users->local_users.begin(); i != this->Users->local_users.end(); i++)
95         {
96                 (*i)->SetWriteError("Server shutdown");
97                 (*i)->CloseSocket();
98         }
99
100         /* We do this more than once, so that any service providers get a
101          * chance to be unhooked by the modules using them, but then get
102          * a chance to be removed themsleves.
103          *
104          * XXX there may be a better way to do this with 1.2
105          */
106         for (int tries = 0; tries < 3; tries++)
107         {
108                 std::vector<std::string> module_names = Modules->GetAllModuleNames(0);
109                 for (std::vector<std::string>::iterator k = module_names.begin(); k != module_names.end(); ++k)
110                 {
111                         /* Unload all modules, so they get a chance to clean up their listeners */
112                         this->Modules->Unload(k->c_str());
113                 }
114         }
115
116         /* Close logging */
117         this->Logs->CloseLogs();
118
119         /* Cleanup Server Names */
120         for(servernamelist::iterator itr = servernames.begin(); itr != servernames.end(); ++itr)
121                 delete (*itr);
122
123
124 }
125
126 void InspIRCd::Restart(const std::string &reason)
127 {
128         /* SendError flushes each client's queue,
129          * regardless of writeability state
130          */
131         this->SendError(reason);
132
133         this->Cleanup();
134
135         /* Figure out our filename (if theyve renamed it, we're boned) */
136         std::string me;
137
138 #ifdef WINDOWS
139         char module[MAX_PATH];
140         if (GetModuleFileName(NULL, module, MAX_PATH))
141                 me = module;
142 #else
143         me = Config->MyDir + "/inspircd";
144 #endif
145
146         if (execv(me.c_str(), Config->argv) == -1)
147         {
148                 /* Will raise a SIGABRT if not trapped */
149                 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
150         }
151 }
152
153 void InspIRCd::ResetMaxBans()
154 {
155         for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
156                 i->second->ResetMaxBans();
157 }
158
159 /** Because hash_map doesnt free its buckets when we delete items (this is a 'feature')
160  * we must occasionally rehash the hash (yes really).
161  * We do this by copying the entries from the old hash to a new hash, causing all
162  * empty buckets to be weeded out of the hash. We dont do this on a timer, as its
163  * very expensive, so instead we do it when the user types /REHASH and expects a
164  * short delay anyway.
165  */
166 void InspIRCd::RehashUsersAndChans()
167 {
168         user_hash* old_users = this->Users->clientlist;
169         user_hash* old_uuid  = this->Users->uuidlist;
170         chan_hash* old_chans = this->chanlist;
171
172         this->Users->clientlist = new user_hash();
173         this->Users->uuidlist = new user_hash();
174         this->chanlist = new chan_hash();
175
176         for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
177                 this->Users->clientlist->insert(*n);
178
179         delete old_users;
180
181         for (user_hash::const_iterator n = old_uuid->begin(); n != old_uuid->end(); n++)
182                 this->Users->uuidlist->insert(*n);
183
184         delete old_uuid;
185
186         for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
187                 this->chanlist->insert(*n);
188
189         delete old_chans;
190 }
191
192 void InspIRCd::SetSignals()
193 {
194 #ifndef WIN32
195         signal(SIGALRM, SIG_IGN);
196         signal(SIGHUP, InspIRCd::SetSignal);
197         signal(SIGPIPE, SIG_IGN);
198         signal(SIGCHLD, SIG_IGN);
199 #endif
200         signal(SIGTERM, InspIRCd::SetSignal);
201 }
202
203 void InspIRCd::QuickExit(int status)
204 {
205         exit(0);
206 }
207
208 bool InspIRCd::DaemonSeed()
209 {
210 #ifdef WINDOWS
211         printf_c("InspIRCd Process ID: \033[1;32m%lu\033[0m\n", GetCurrentProcessId());
212         return true;
213 #else
214         signal(SIGTERM, InspIRCd::QuickExit);
215
216         int childpid;
217         if ((childpid = fork ()) < 0)
218                 return false;
219         else if (childpid > 0)
220         {
221                 /* We wait here for the child process to kill us,
222                  * so that the shell prompt doesnt come back over
223                  * the output.
224                  * Sending a kill with a signal of 0 just checks
225                  * if the child pid is still around. If theyre not,
226                  * they threw an error and we should give up.
227                  */
228                 while (kill(childpid, 0) != -1)
229                         sleep(1);
230                 exit(0);
231         }
232         setsid ();
233         umask (007);
234         printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
235
236         signal(SIGTERM, InspIRCd::SetSignal);
237
238         rlimit rl;
239         if (getrlimit(RLIMIT_CORE, &rl) == -1)
240         {
241                 this->Logs->Log("STARTUP",DEFAULT,"Failed to getrlimit()!");
242                 return false;
243         }
244         else
245         {
246                 rl.rlim_cur = rl.rlim_max;
247                 if (setrlimit(RLIMIT_CORE, &rl) == -1)
248                         this->Logs->Log("STARTUP",DEFAULT,"setrlimit() failed, cannot increase coredump size.");
249         }
250
251         return true;
252 #endif
253 }
254
255 void InspIRCd::WritePID(const std::string &filename)
256 {
257         std::string fname = (filename.empty() ? "inspircd.pid" : filename);
258         if (*(fname.begin()) != '/')
259         {
260                 std::string::size_type pos;
261                 std::string confpath = this->ConfigFileName;
262                 if ((pos = confpath.rfind("/")) != std::string::npos)
263                 {
264                         /* Leaves us with just the path */
265                         fname = confpath.substr(0, pos) + std::string("/") + fname;
266                 }
267         }
268         std::ofstream outfile(fname.c_str());
269         if (outfile.is_open())
270         {
271                 outfile << getpid();
272                 outfile.close();
273         }
274         else
275         {
276                 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
277                 this->Logs->Log("STARTUP",DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
278                 Exit(EXIT_STATUS_PID);
279         }
280 }
281
282 InspIRCd::InspIRCd(int argc, char** argv)
283         : GlobalCulls(this),
284
285          /* Functor initialisation. Note that the ordering here is very important. 
286           *
287           * THIS MUST MATCH ORDER OF DECLARATION OF THE HandleWhateverFunc classes
288           * within class InspIRCd.
289           */
290          HandleProcessUser(this),
291          HandleIsNick(this),
292          HandleIsIdent(this),
293          HandleFindDescriptor(this),
294          HandleFloodQuitUser(this),
295          HandleIsChannel(this),
296          HandleIsSID(this),
297          HandleRehash(this),
298
299          /* Functor pointer initialisation. Must match the order of the list above
300           *
301           * THIS MUST MATCH THE ORDER OF DECLARATION OF THE FUNCTORS, e.g. the methods
302           * themselves within the class.
303           */
304          ProcessUser(&HandleProcessUser),
305          IsChannel(&HandleIsChannel),
306          IsSID(&HandleIsSID),
307          Rehash(&HandleRehash),
308          IsNick(&HandleIsNick),
309          IsIdent(&HandleIsIdent),
310          FindDescriptor(&HandleFindDescriptor),
311          FloodQuitUser(&HandleFloodQuitUser)
312
313 {
314 #ifdef WIN32
315         _CrtSetDbgFlag ( _CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
316 #endif
317         int found_ports = 0;
318         FailedPortList pl;
319         int do_version = 0, do_nofork = 0, do_debug = 0,
320             do_nolog = 0, do_root = 0, do_testsuite = 0;    /* flag variables */
321         char c = 0;
322
323         memset(&server, 0, sizeof(server));
324         memset(&client, 0, sizeof(client));
325
326         // This must be created first, so other parts of Insp can use it while starting up
327         this->Logs = new LogManager(this);
328
329         SocketEngineFactory* SEF = new SocketEngineFactory();
330         SE = SEF->Create(this);
331         delete SEF;
332
333         ThreadEngineFactory* tef = new ThreadEngineFactory();
334         this->Threads = tef->Create(this);
335         delete tef;
336
337         /* Default implementation does nothing */
338         this->PI = new ProtocolInterface(this);
339
340         this->s_signal = 0;
341         
342         // Create base manager classes early, so nothing breaks
343         this->Users = new UserManager(this);
344         
345         this->Users->unregistered_count = 0;
346
347         this->Users->clientlist = new user_hash();
348         this->Users->uuidlist = new user_hash();
349         this->chanlist = new chan_hash();
350
351         this->Res = NULL;
352
353         this->Config = new ServerConfig(this);
354         this->SNO = new SnomaskManager(this);
355         this->BanCache = new BanCacheManager(this);
356         this->Modules = new ModuleManager(this);
357         this->stats = new serverstats();
358         this->Timers = new TimerManager(this);
359         this->Parser = new CommandParser(this);
360         this->XLines = new XLineManager(this);
361
362         this->Config->argv = argv;
363         this->Config->argc = argc;
364
365         if (chdir(Config->GetFullProgDir().c_str()))
366         {
367                 printf("Unable to change to my directory: %s\nAborted.", strerror(errno));
368                 exit(0);
369         }
370
371         this->Config->opertypes.clear();
372         this->Config->operclass.clear();
373
374         this->TIME = this->OLDTIME = this->startup_time = time(NULL);
375         srand(this->TIME);
376
377         *this->LogFileName = 0;
378         strlcpy(this->ConfigFileName, CONFIG_FILE, MAXBUF);
379
380         struct option longopts[] =
381         {
382                 { "nofork",     no_argument,            &do_nofork,     1       },
383                 { "logfile",    required_argument,      NULL,           'f'     },
384                 { "config",     required_argument,      NULL,           'c'     },
385                 { "debug",      no_argument,            &do_debug,      1       },
386                 { "nolog",      no_argument,            &do_nolog,      1       },
387                 { "runasroot",  no_argument,            &do_root,       1       },
388                 { "version",    no_argument,            &do_version,    1       },
389                 { "testsuite",  no_argument,            &do_testsuite,  1       },
390                 { 0, 0, 0, 0 }
391         };
392
393         while ((c = getopt_long_only(argc, argv, ":f:", longopts, NULL)) != -1)
394         {
395                 switch (c)
396                 {
397                         case 'f':
398                                 /* Log filename was set */
399                                 strlcpy(LogFileName, optarg, MAXBUF);
400                         break;
401                         case 'c':
402                                 /* Config filename was set */
403                                 strlcpy(ConfigFileName, optarg, MAXBUF);
404                         break;
405                         case 0:
406                                 /* getopt_long_only() set an int variable, just keep going */
407                         break;
408                         default:
409                                 /* Unknown parameter! DANGER, INTRUDER.... err.... yeah. */
410                                 printf("Usage: %s [--nofork] [--nolog] [--debug] [--logfile <filename>]\n\
411                                                   [--runasroot] [--version] [--config <config>] [--testsuite]\n", argv[0]);
412                                 Exit(EXIT_STATUS_ARGV);
413                         break;
414                 }
415         }
416
417         if (do_testsuite)
418                 do_nofork = do_debug = true;
419
420         if (do_version)
421         {
422                 printf("\n%s r%s\n", VERSION, REVISION);
423                 Exit(EXIT_STATUS_NOERROR);
424         }
425
426 #ifdef WIN32
427
428         // Handle forking
429         if(!do_nofork)
430         {
431                 DWORD ExitCode = WindowsForkStart(this);
432                 if(ExitCode)
433                         exit(ExitCode);
434         }
435
436         // Set up winsock
437         WSADATA wsadata;
438         WSAStartup(MAKEWORD(2,0), &wsadata);
439         ChangeWindowsSpecificPointers(this);
440 #endif
441         strlcpy(Config->MyExecutable,argv[0],MAXBUF);
442
443         /* Set the finished argument values */
444         Config->nofork = do_nofork;
445         Config->forcedebug = do_debug;
446         Config->writelog = !do_nolog;
447         Config->TestSuite = do_testsuite;
448
449         if (!this->OpenLog(argv, argc))
450         {
451                 printf("ERROR: Could not open logfile %s: %s\n\n", Config->logpath.c_str(), strerror(errno));
452                 Exit(EXIT_STATUS_LOG);
453         }
454
455         if (!ServerConfig::FileExists(this->ConfigFileName))
456         {
457                 printf("ERROR: Cannot open config file: %s\nExiting...\n", this->ConfigFileName);
458                 this->Logs->Log("STARTUP",DEFAULT,"Unable to open config file %s", this->ConfigFileName);
459                 Exit(EXIT_STATUS_CONFIG);
460         }
461
462         printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
463         printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
464         printf_c("Developers:\n");
465         printf_c("\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special\n");
466         printf_c("\t\033[1;32mpippijn, peavey, aquanight, fez\033[0m\n\n");
467         printf_c("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
468
469         Config->ClearStack();
470
471         this->Modes = new ModeParser(this);
472
473         if (!do_root)
474                 this->CheckRoot();
475         else
476         {
477                 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
478                 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
479                 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
480                 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
481                 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
482                 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
483                 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
484                 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
485                 sleep(20);
486         }
487
488         this->SetSignals();
489
490         if (!Config->nofork)
491         {
492                 if (!this->DaemonSeed())
493                 {
494                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
495                         Logs->Log("STARTUP", DEFAULT, "ERROR: could not go into daemon mode. Shutting down.");
496                         Exit(EXIT_STATUS_FORK);
497                 }
498         }
499
500         SE->RecoverFromFork();
501
502         /* During startup we don't actually initialize this
503          * in the thread engine.
504          */
505         this->ConfigThread = new ConfigReaderThread(this, true, NULL);
506         ConfigThread->Run();
507         delete ConfigThread;
508         this->ConfigThread = NULL;
509
510         this->Res = new DNS(this);
511
512         this->AddServerName(Config->ServerName);
513
514         /*
515          * Initialise SID/UID.
516          * For an explanation as to exactly how this works, and why it works this way, see GetUID().
517          *   -- w00t
518          */
519         if (!*Config->sid)
520         {
521                 // Generate one
522                 size_t sid = 0;
523
524                 for (const char* x = Config->ServerName; *x; ++x)
525                         sid = 5 * sid + *x;
526                 for (const char* y = Config->ServerDesc; *y; ++y)
527                         sid = 5 * sid + *y;
528                 sid = sid % 999;
529
530                 Config->sid[0] = (char)(sid / 100 + 48);
531                 Config->sid[1] = (char)(((sid / 10) % 10) + 48);
532                 Config->sid[2] = (char)(sid % 10 + 48);
533         }
534
535         /* set up fake client again this time with the correct uid */
536         this->FakeClient = new User(this, "#INVALID");
537         this->FakeClient->SetFd(FD_MAGIC_NUMBER);
538
539         // Get XLine to do it's thing.
540         this->XLines->CheckELines();
541         this->XLines->ApplyLines();
542
543         CheckDie();
544         int bounditems = BindPorts(true, found_ports, pl);
545
546         printf("\n");
547
548         this->Modules->LoadAll();
549         
550         /* Just in case no modules were loaded - fix for bug #101 */
551         this->BuildISupport();
552         InitializeDisabledCommands(Config->DisabledCommands, this);
553
554         /*if ((Config->ports.size() == 0) && (found_ports > 0))
555         {
556                 printf("\nERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?\n");
557                 Logs->Log("STARTUP", DEFAULT,"ERROR: I couldn't bind any ports! Something else is bound to those ports!");
558                 Exit(EXIT_STATUS_BIND);
559         }*/
560
561         if (Config->ports.size() != (unsigned int)found_ports)
562         {
563                 printf("\nWARNING: Not all your client ports could be bound --\nstarting anyway with %d of %d client ports bound.\n\n", bounditems, found_ports);
564                 printf("The following port(s) failed to bind:\n");
565                 printf("Hint: Try using an IP instead of blank or *\n\n");
566                 int j = 1;
567                 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
568                 {
569                         printf("%d.\tIP: %s\tPort: %lu\n", j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
570                 }
571         }
572
573         printf("\nInspIRCd is now running as '%s'[%s] with %d max open sockets\n", Config->ServerName,Config->GetSID().c_str(), SE->GetMaxFds());
574         
575 #ifndef WINDOWS
576         if (!Config->nofork)
577         {
578                 if (kill(getppid(), SIGTERM) == -1)
579                 {
580                         printf("Error killing parent process: %s\n",strerror(errno));
581                         Logs->Log("STARTUP", DEFAULT, "Error killing parent process: %s",strerror(errno));
582                 }
583         }
584
585         if (isatty(0) && isatty(1) && isatty(2))
586         {
587                 /* We didn't start from a TTY, we must have started from a background process -
588                  * e.g. we are restarting, or being launched by cron. Dont kill parent, and dont
589                  * close stdin/stdout
590                  */
591                 if (!do_nofork)
592                 {
593                         fclose(stdin);
594                         fclose(stderr);
595                         fclose(stdout);
596                 }
597                 else
598                 {
599                         Logs->Log("STARTUP", DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
600                 }
601         }
602 #else
603         WindowsIPC = new IPC(this);
604         if(!Config->nofork)
605         {
606                 WindowsForkKillOwner(this);
607                 FreeConsole();
608         }
609 #endif
610
611         Logs->Log("STARTUP", DEFAULT, "Startup complete as '%s'[%s], %d max open sockets", Config->ServerName,Config->GetSID().c_str(), SE->GetMaxFds());
612
613         this->WritePID(Config->PID);
614 }
615
616 int InspIRCd::Run()
617 {
618         /* See if we're supposed to be running the test suite rather than entering the mainloop */
619         if (Config->TestSuite)
620         {
621                 TestSuite* ts = new TestSuite(this);
622                 delete ts;
623                 Exit(0);
624         }
625
626         while (true)
627         {
628 #ifndef WIN32
629                 static rusage ru;
630 #else
631                 static time_t uptime;
632                 static struct tm * stime;
633                 static char window_title[100];
634 #endif
635
636                 /* Check if there is a config thread which has finished executing but has not yet been freed */
637                 if (this->ConfigThread && this->ConfigThread->GetExitFlag())
638                 {
639                         /* Rehash has completed */
640                         this->Logs->Log("CONFIG",DEBUG,"Detected ConfigThread exiting, tidying up...");
641
642                         /* IMPORTANT: This delete may hang if you fuck up your thread syncronization.
643                          * It will hang waiting for the ConfigThread to 'join' to avoid race conditons,
644                          * until the other thread is completed.
645                          */
646                         delete ConfigThread;
647                         ConfigThread = NULL;
648
649                         /* These are currently not known to be threadsafe, so they are executed outside
650                          * of the thread. It would be pretty simple to move them to the thread Run method
651                          * once they are known threadsafe with all the correct mutexes in place.
652                          *
653                          * XXX: The order of these is IMPORTANT, do not reorder them without testing
654                          * thoroughly!!!
655                          */
656                         this->XLines->CheckELines();
657                         this->XLines->ApplyLines();
658                         this->Res->Rehash();
659                         this->ResetMaxBans();
660                         InitializeDisabledCommands(Config->DisabledCommands, this);
661                         FOREACH_MOD_I(this, I_OnRehash, OnRehash(Config->RehashUser, Config->RehashParameter));
662                         this->BuildISupport();
663                 }
664
665                 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
666                  * Once per loop iteration is pleanty.
667                  */
668                 OLDTIME = TIME;
669                 TIME = time(NULL);
670
671                 /* Run background module timers every few seconds
672                  * (the docs say modules shouldnt rely on accurate
673                  * timing using this event, so we dont have to
674                  * time this exactly).
675                  */
676                 if (TIME != OLDTIME)
677                 {
678                         if (TIME < OLDTIME)
679                         {
680                                 SNO->WriteToSnoMask('A', "\002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %lu secs.", (unsigned long)OLDTIME-TIME);
681                         }
682
683                         if ((TIME % 3600) == 0)
684                         {
685                                 this->RehashUsersAndChans();
686                                 FOREACH_MOD_I(this, I_OnGarbageCollect, OnGarbageCollect());
687                         }
688
689                         Timers->TickTimers(TIME);
690                         this->DoBackgroundUserStuff();
691
692                         if ((TIME % 5) == 0)
693                         {
694                                 FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
695                                 SNO->FlushSnotices();
696                         }
697 #ifndef WIN32
698                         /* Same change as in cmd_stats.cpp, use RUSAGE_SELF rather than '0' -- Om */
699                         if (!getrusage(RUSAGE_SELF, &ru))
700                         {
701                                 gettimeofday(&this->stats->LastSampled, NULL);
702                                 this->stats->LastCPU = ru.ru_utime;
703                         }
704 #else
705                         WindowsIPC->Check();    
706 #endif
707                 }
708
709                 /* Call the socket engine to wait on the active
710                  * file descriptors. The socket engine has everything's
711                  * descriptors in its list... dns, modules, users,
712                  * servers... so its nice and easy, just one call.
713                  * This will cause any read or write events to be
714                  * dispatched to their handlers.
715                  */
716                 this->SE->DispatchEvents();
717
718                 /* if any users were quit, take them out */
719                 this->GlobalCulls.Apply();
720
721                 /* If any inspsockets closed, remove them */
722                 this->BufferedSocketCull();
723
724                 if (this->s_signal)
725                 {
726                         this->SignalHandler(s_signal);
727                         this->s_signal = 0;
728                 }
729         }
730
731         return 0;
732 }
733
734 void InspIRCd::BufferedSocketCull()
735 {
736         for (std::map<BufferedSocket*,BufferedSocket*>::iterator x = SocketCull.begin(); x != SocketCull.end(); ++x)
737         {
738                 this->Logs->Log("MISC",DEBUG,"Cull socket");
739                 SE->DelFd(x->second);
740                 x->second->Close();
741                 delete x->second;
742         }
743         SocketCull.clear();
744 }
745
746 /**********************************************************************************/
747
748 /**
749  * An ircd in five lines! bwahahaha. ahahahahaha. ahahah *cough*.
750  */
751
752 int main(int argc, char ** argv)
753 {
754         SI = new InspIRCd(argc, argv);
755         mysig = &SI->s_signal;
756         SI->Run();
757         delete SI;
758         return 0;
759 }
760
761 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
762  * (until this returns true, a user will block in the waiting state, waiting to connect up to the
763  * registration timeout maximum seconds)
764  */
765 bool InspIRCd::AllModulesReportReady(User* user)
766 {
767         for (EventHandlerIter i = Modules->EventHandlers[I_OnCheckReady].begin(); i != Modules->EventHandlers[I_OnCheckReady].end(); ++i)
768         {
769                 if (!(*i)->OnCheckReady(user))
770                         return false;
771         }
772         return true;
773 }
774
775 time_t InspIRCd::Time()
776 {
777         return TIME;
778 }
779
780 void InspIRCd::SetSignal(int signal)
781 {
782         *mysig = signal;
783 }