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