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