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