]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
cd13087cfa3a844ed67c551d8b2ff92e8e40c325
[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          HandleProcessUser(this),
282          HandleIsNick(this),
283          HandleIsIdent(this),
284          HandleFindDescriptor(this),
285          HandleFloodQuitUser(this),
286
287          /* Functor pointer initialisation. Must match the order of the list above */
288          ProcessUser(&HandleProcessUser),
289          IsNick(&HandleIsNick),
290          IsIdent(&HandleIsIdent),
291          FindDescriptor(&HandleFindDescriptor),
292          FloodQuitUser(&HandleFloodQuitUser)
293
294 {
295
296         int found_ports = 0;
297         FailedPortList pl;
298         int do_version = 0, do_nofork = 0, do_debug = 0,
299             do_nolog = 0, do_root = 0, do_testsuite = 0;    /* flag variables */
300         char c = 0;
301
302         memset(&server, 0, sizeof(server));
303         memset(&client, 0, sizeof(client));
304
305         // This must be created first, so other parts of Insp can use it while starting up
306         this->Logs = new LogManager(this);
307
308         SocketEngineFactory* SEF = new SocketEngineFactory();
309         SE = SEF->Create(this);
310         delete SEF;
311
312
313         ThreadEngineFactory* tef = new ThreadEngineFactory();
314         this->Threads = tef->Create(this);
315         delete tef;
316
317         this->s_signal = 0;
318         
319         // Create base manager classes early, so nothing breaks
320         this->Users = new UserManager(this);
321         
322         this->Users->unregistered_count = 0;
323
324         this->Users->clientlist = new user_hash();
325         this->Users->uuidlist = new user_hash();
326         this->chanlist = new chan_hash();
327
328         this->Res = NULL;
329
330         this->Config = new ServerConfig(this);
331         this->SNO = new SnomaskManager(this);
332         this->BanCache = new BanCacheManager(this);
333         this->Modules = new ModuleManager(this);
334         this->stats = new serverstats();
335         this->Timers = new TimerManager(this);
336         this->Parser = new CommandParser(this);
337         this->XLines = new XLineManager(this);
338
339         this->Config->argv = argv;
340         this->Config->argc = argc;
341
342         if (chdir(Config->GetFullProgDir().c_str()))
343         {
344                 printf("Unable to change to my directory: %s\nAborted.", strerror(errno));
345                 exit(0);
346         }
347
348         this->Config->opertypes.clear();
349         this->Config->operclass.clear();
350
351         this->TIME = this->OLDTIME = this->startup_time = time(NULL);
352         srand(this->TIME);
353
354         *this->LogFileName = 0;
355         strlcpy(this->ConfigFileName, CONFIG_FILE, MAXBUF);
356
357         struct option longopts[] =
358         {
359                 { "nofork",     no_argument,            &do_nofork,     1       },
360                 { "logfile",    required_argument,      NULL,           'f'     },
361                 { "config",     required_argument,      NULL,           'c'     },
362                 { "debug",      no_argument,            &do_debug,      1       },
363                 { "nolog",      no_argument,            &do_nolog,      1       },
364                 { "runasroot",  no_argument,            &do_root,       1       },
365                 { "version",    no_argument,            &do_version,    1       },
366                 { "testsuite",  no_argument,            &do_testsuite,  1       },
367                 { 0, 0, 0, 0 }
368         };
369
370         while ((c = getopt_long_only(argc, argv, ":f:", longopts, NULL)) != -1)
371         {
372                 switch (c)
373                 {
374                         case 'f':
375                                 /* Log filename was set */
376                                 strlcpy(LogFileName, optarg, MAXBUF);
377                         break;
378                         case 'c':
379                                 /* Config filename was set */
380                                 strlcpy(ConfigFileName, optarg, MAXBUF);
381                         break;
382                         case 0:
383                                 /* getopt_long_only() set an int variable, just keep going */
384                         break;
385                         default:
386                                 /* Unknown parameter! DANGER, INTRUDER.... err.... yeah. */
387                                 printf("Usage: %s [--nofork] [--nolog] [--debug] [--logfile <filename>]\n\
388                                                   [--runasroot] [--version] [--config <config>] [--testsuite]\n", argv[0]);
389                                 Exit(EXIT_STATUS_ARGV);
390                         break;
391                 }
392         }
393
394         if (do_testsuite)
395                 do_nofork = do_debug = true;
396
397         if (do_version)
398         {
399                 printf("\n%s r%s\n", VERSION, REVISION);
400                 Exit(EXIT_STATUS_NOERROR);
401         }
402
403 #ifdef WIN32
404
405         // Handle forking
406         if(!do_nofork)
407         {
408                 DWORD ExitCode = WindowsForkStart(this);
409                 if(ExitCode)
410                         exit(ExitCode);
411         }
412
413         // Set up winsock
414         WSADATA wsadata;
415         WSAStartup(MAKEWORD(2,0), &wsadata);
416         ChangeWindowsSpecificPointers(this);
417 #endif
418         strlcpy(Config->MyExecutable,argv[0],MAXBUF);
419
420         /* Set the finished argument values */
421         Config->nofork = do_nofork;
422         Config->forcedebug = do_debug;
423         Config->writelog = !do_nolog;
424         Config->TestSuite = do_testsuite;
425
426         if (!this->OpenLog(argv, argc))
427         {
428                 printf("ERROR: Could not open logfile %s: %s\n\n", Config->logpath.c_str(), strerror(errno));
429                 Exit(EXIT_STATUS_LOG);
430         }
431
432         if (!ServerConfig::FileExists(this->ConfigFileName))
433         {
434                 printf("ERROR: Cannot open config file: %s\nExiting...\n", this->ConfigFileName);
435                 this->Logs->Log("STARTUP",DEFAULT,"Unable to open config file %s", this->ConfigFileName);
436                 Exit(EXIT_STATUS_CONFIG);
437         }
438
439         printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
440         printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
441         printf_c("Developers:\n");
442         printf_c("\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special\n");
443         printf_c("\t\033[1;32mpippijn, peavey, aquanight, fez\033[0m\n\n");
444         printf_c("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
445
446         Config->ClearStack();
447
448         this->Modes = new ModeParser(this);
449
450         if (!do_root)
451                 this->CheckRoot();
452         else
453         {
454                 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
455                 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
456                 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
457                 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
458                 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
459                 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
460                 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
461                 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
462                 sleep(20);
463         }
464
465         this->SetSignals();
466
467         if (!Config->nofork)
468         {
469                 if (!this->DaemonSeed())
470                 {
471                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
472                         Logs->Log("STARTUP", DEFAULT, "ERROR: could not go into daemon mode. Shutting down.");
473                         Exit(EXIT_STATUS_FORK);
474                 }
475         }
476
477         SE->RecoverFromFork();
478
479         /* During startup we don't actually initialize this
480          * in the thread engine.
481          */
482         this->ConfigThread = new ConfigReaderThread(this, true, NULL);
483         ConfigThread->Run();
484         delete ConfigThread;
485         this->ConfigThread = NULL;
486
487         this->Res = new DNS(this);
488
489         this->AddServerName(Config->ServerName);
490
491         /*
492          * Initialise SID/UID.
493          * For an explanation as to exactly how this works, and why it works this way, see GetUID().
494          *   -- w00t
495          */
496         if (!*Config->sid)
497         {
498                 // Generate one
499                 size_t sid = 0;
500
501                 for (const char* x = Config->ServerName; *x; ++x)
502                         sid = 5 * sid + *x;
503                 for (const char* y = Config->ServerDesc; *y; ++y)
504                         sid = 5 * sid + *y;
505                 sid = sid % 999;
506
507                 Config->sid[0] = (char)(sid / 100 + 48);
508                 Config->sid[1] = (char)(((sid / 10) % 10) + 48);
509                 Config->sid[2] = (char)(sid % 10 + 48);
510         }
511
512         /* set up fake client again this time with the correct uid */
513         this->FakeClient = new User(this, "#INVALID");
514         this->FakeClient->SetFd(FD_MAGIC_NUMBER);
515
516         // Get XLine to do it's thing.
517         this->XLines->CheckELines();
518         this->XLines->ApplyLines();
519
520         CheckDie();
521         int bounditems = BindPorts(true, found_ports, pl);
522
523         printf("\n");
524
525         this->Modules->LoadAll();
526         
527         /* Just in case no modules were loaded - fix for bug #101 */
528         this->BuildISupport();
529         InitializeDisabledCommands(Config->DisabledCommands, this);
530
531         /*if ((Config->ports.size() == 0) && (found_ports > 0))
532         {
533                 printf("\nERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?\n");
534                 Logs->Log("STARTUP", DEFAULT,"ERROR: I couldn't bind any ports! Something else is bound to those ports!");
535                 Exit(EXIT_STATUS_BIND);
536         }*/
537
538         if (Config->ports.size() != (unsigned int)found_ports)
539         {
540                 printf("\nWARNING: Not all your client ports could be bound --\nstarting anyway with %d of %d client ports bound.\n\n", bounditems, found_ports);
541                 printf("The following port(s) failed to bind:\n");
542                 int j = 1;
543                 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
544                 {
545                         printf("%d.\tIP: %s\tPort: %lu\n", j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
546                 }
547         }
548
549         printf("\nInspIRCd is now running as '%s'[%s] with %d max open sockets\n", Config->ServerName,Config->GetSID().c_str(), SE->GetMaxFds());
550         
551 #ifndef WINDOWS
552         if (!Config->nofork)
553         {
554                 if (kill(getppid(), SIGTERM) == -1)
555                 {
556                         printf("Error killing parent process: %s\n",strerror(errno));
557                         Logs->Log("STARTUP", DEFAULT, "Error killing parent process: %s",strerror(errno));
558                 }
559         }
560
561         if (isatty(0) && isatty(1) && isatty(2))
562         {
563                 /* We didn't start from a TTY, we must have started from a background process -
564                  * e.g. we are restarting, or being launched by cron. Dont kill parent, and dont
565                  * close stdin/stdout
566                  */
567                 if (!do_nofork)
568                 {
569                         fclose(stdin);
570                         fclose(stderr);
571                         fclose(stdout);
572                 }
573                 else
574                 {
575                         Logs->Log("STARTUP", DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
576                 }
577         }
578 #else
579         WindowsIPC = new IPC(this);
580         if(!Config->nofork)
581         {
582                 WindowsForkKillOwner(this);
583                 FreeConsole();
584         }
585 #endif
586
587         Logs->Log("STARTUP", DEFAULT, "Startup complete as '%s'[%s], %d max open sockets", Config->ServerName,Config->GetSID().c_str(), SE->GetMaxFds());
588
589         this->WritePID(Config->PID);
590 }
591
592 int InspIRCd::Run()
593 {
594         /* See if we're supposed to be running the test suite rather than entering the mainloop */
595         if (Config->TestSuite)
596         {
597                 TestSuite* ts = new TestSuite(this);
598                 delete ts;
599                 Exit(0);
600         }
601
602         while (true)
603         {
604 #ifndef WIN32
605                 static rusage ru;
606 #else
607                 static time_t uptime;
608                 static struct tm * stime;
609                 static char window_title[100];
610 #endif
611
612                 /* Check if there is a config thread which has finished executing but has not yet been freed */
613                 if (this->ConfigThread && this->ConfigThread->GetExitFlag())
614                 {
615                         /* Rehash has completed */
616                         this->Logs->Log("CONFIG",DEBUG,"Detected ConfigThread exiting, tidying up...");
617
618                         /* IMPORTANT: This delete may hang if you fuck up your thread syncronization.
619                          * It will hang waiting for the ConfigThread to 'join' to avoid race conditons,
620                          * until the other thread is completed.
621                          */
622                         delete ConfigThread;
623                         ConfigThread = NULL;
624
625                         /* These are currently not known to be threadsafe, so they are executed outside
626                          * of the thread. It would be pretty simple to move them to the thread Run method
627                          * once they are known threadsafe with all the correct mutexes in place.
628                          *
629                          * XXX: The order of these is IMPORTANT, do not reorder them without testing
630                          * thoroughly!!!
631                          */
632                         this->XLines->CheckELines();
633                         this->XLines->ApplyLines();
634                         this->Res->Rehash();
635                         this->ResetMaxBans();
636                         InitializeDisabledCommands(Config->DisabledCommands, this);
637                         FOREACH_MOD_I(this, I_OnRehash, OnRehash(Config->RehashUser, Config->RehashParameter));
638                         this->BuildISupport();
639                 }
640
641                 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
642                  * Once per loop iteration is pleanty.
643                  */
644                 OLDTIME = TIME;
645                 TIME = time(NULL);
646
647                 /* Run background module timers every few seconds
648                  * (the docs say modules shouldnt rely on accurate
649                  * timing using this event, so we dont have to
650                  * time this exactly).
651                  */
652                 if (TIME != OLDTIME)
653                 {
654                         if (TIME < OLDTIME)
655                         {
656                                 SNO->WriteToSnoMask('A', "\002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %lu secs.", (unsigned long)OLDTIME-TIME);
657                         }
658
659                         if ((TIME % 3600) == 0)
660                         {
661                                 this->RehashUsersAndChans();
662                                 FOREACH_MOD_I(this, I_OnGarbageCollect, OnGarbageCollect());
663                         }
664
665                         Timers->TickTimers(TIME);
666                         this->DoBackgroundUserStuff();
667
668                         if ((TIME % 5) == 0)
669                         {
670                                 FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
671                                 SNO->FlushSnotices();
672                         }
673 #ifndef WIN32
674                         /* Same change as in cmd_stats.cpp, use RUSAGE_SELF rather than '0' -- Om */
675                         if (!getrusage(RUSAGE_SELF, &ru))
676                         {
677                                 gettimeofday(&this->stats->LastSampled, NULL);
678                                 this->stats->LastCPU = ru.ru_utime;
679                         }
680 #else
681                         WindowsIPC->Check();    
682 #endif
683                 }
684
685                 /* Call the socket engine to wait on the active
686                  * file descriptors. The socket engine has everything's
687                  * descriptors in its list... dns, modules, users,
688                  * servers... so its nice and easy, just one call.
689                  * This will cause any read or write events to be
690                  * dispatched to their handlers.
691                  */
692                 this->SE->DispatchEvents();
693
694                 /* if any users were quit, take them out */
695                 this->GlobalCulls.Apply();
696
697                 /* If any inspsockets closed, remove them */
698                 this->BufferedSocketCull();
699
700                 if (this->s_signal)
701                 {
702                         this->SignalHandler(s_signal);
703                         this->s_signal = 0;
704                 }
705         }
706
707         return 0;
708 }
709
710 void InspIRCd::BufferedSocketCull()
711 {
712         for (std::map<BufferedSocket*,BufferedSocket*>::iterator x = SocketCull.begin(); x != SocketCull.end(); ++x)
713         {
714                 this->Logs->Log("MISC",DEBUG,"Cull socket");
715                 SE->DelFd(x->second);
716                 x->second->Close();
717                 delete x->second;
718         }
719         SocketCull.clear();
720 }
721
722 /**********************************************************************************/
723
724 /**
725  * An ircd in five lines! bwahahaha. ahahahahaha. ahahah *cough*.
726  */
727
728 int main(int argc, char ** argv)
729 {
730         SI = new InspIRCd(argc, argv);
731         mysig = &SI->s_signal;
732         SI->Run();
733         delete SI;
734         return 0;
735 }
736
737 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
738  * (until this returns true, a user will block in the waiting state, waiting to connect up to the
739  * registration timeout maximum seconds)
740  */
741 bool InspIRCd::AllModulesReportReady(User* user)
742 {
743         for (EventHandlerIter i = Modules->EventHandlers[I_OnCheckReady].begin(); i != Modules->EventHandlers[I_OnCheckReady].end(); ++i)
744         {
745                 if (!(*i)->OnCheckReady(user))
746                         return false;
747         }
748         return true;
749 }
750
751 time_t InspIRCd::Time()
752 {
753         return TIME;
754 }
755
756 void InspIRCd::SetSignal(int signal)
757 {
758         *mysig = signal;
759 }