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