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