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