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