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