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