]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
Make sure usage lines up neatly.
[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 /* $Install: src/inspircd $(BINPATH) */
16 #include "inspircd.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         /* Remove core commands */
130         Parser->RemoveCommands("<core>");
131
132         /* Cleanup Server Names */
133         for(servernamelist::iterator itr = servernames.begin(); itr != servernames.end(); ++itr)
134                 delete (*itr);
135
136         /* Delete objects dynamically allocated in constructor (destructor would be more appropriate, but we're likely exiting) */
137         /* Must be deleted before modes as it decrements modelines */
138         DeleteZero(this->Users);
139         DeleteZero(this->Modes);
140         DeleteZero(this->XLines);
141         DeleteZero(this->Parser);
142         DeleteZero(this->stats);
143         DeleteZero(this->Modules);
144         DeleteZero(this->BanCache);
145         DeleteZero(this->SNO);
146         DeleteZero(this->Config);
147         DeleteZero(this->Res);
148         DeleteZero(this->chanlist);
149         DeleteZero(this->PI);
150         DeleteZero(this->Threads);
151         DeleteZero(this->Timers);
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         : GlobalCulls(this),
320
321          /* Functor initialisation. Note that the ordering here is very important.
322           *
323           * THIS MUST MATCH ORDER OF DECLARATION OF THE HandleWhateverFunc classes
324           * within class InspIRCd.
325           */
326          HandleProcessUser(this),
327          HandleIsNick(this),
328          HandleIsIdent(this),
329          HandleFloodQuitUser(this),
330          HandleIsChannel(this),
331          HandleIsSID(this),
332          HandleRehash(this),
333
334          /* Functor pointer initialisation. Must match the order of the list above
335           *
336           * THIS MUST MATCH THE ORDER OF DECLARATION OF THE FUNCTORS, e.g. the methods
337           * themselves within the class.
338           */
339          ProcessUser(&HandleProcessUser),
340          IsChannel(&HandleIsChannel),
341          IsSID(&HandleIsSID),
342          Rehash(&HandleRehash),
343          IsNick(&HandleIsNick),
344          IsIdent(&HandleIsIdent),
345          FloodQuitUser(&HandleFloodQuitUser)
346
347 {
348 #ifdef WIN32
349         // Strict, frequent checking of memory on debug builds
350         _CrtSetDbgFlag ( _CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
351
352         // Avoid erroneous frees on early exit
353         WindowsIPC = 0;
354 #endif
355         FailedPortList pl;
356         int do_version = 0, do_nofork = 0, do_debug = 0,
357             do_nolog = 0, do_root = 0, do_testsuite = 0;    /* flag variables */
358         int c = 0;
359
360         // Initialize so that if we exit before proper initialization they're not deleted
361         this->Logs = 0;
362         this->Threads = 0;
363         this->PI = 0;
364         this->Users = 0;
365         this->chanlist = 0;
366         this->Config = 0;
367         this->SNO = 0;
368         this->BanCache = 0;
369         this->Modules = 0;
370         this->stats = 0;
371         this->Timers = 0;
372         this->Parser = 0;
373         this->XLines = 0;
374         this->Modes = 0;
375         this->Res = 0;
376         this->ConfigThread = NULL;
377
378         // Initialise TIME
379         this->TIME = time(NULL);
380
381         memset(&server, 0, sizeof(server));
382         memset(&client, 0, sizeof(client));
383
384         // This must be created first, so other parts of Insp can use it while starting up
385         this->Logs = new LogManager(this);
386
387         SocketEngineFactory* SEF = new SocketEngineFactory();
388         SE = SEF->Create(this);
389         delete SEF;
390
391         this->Threads = new ThreadEngine(this);
392
393         /* Default implementation does nothing */
394         this->PI = new ProtocolInterface(this);
395
396         this->s_signal = 0;
397
398         // Create base manager classes early, so nothing breaks
399         this->Users = new UserManager(this);
400
401         this->Users->unregistered_count = 0;
402
403         this->Users->clientlist = new user_hash();
404         this->Users->uuidlist = new user_hash();
405         this->chanlist = new chan_hash();
406
407         this->Config = new ServerConfig(this);
408         this->SNO = new SnomaskManager(this);
409         this->BanCache = new BanCacheManager(this);
410         this->Modules = new ModuleManager(this);
411         this->stats = new serverstats();
412         this->Timers = new TimerManager(this);
413         this->Parser = new CommandParser(this);
414         this->XLines = new XLineManager(this);
415
416         this->Config->argv = argv;
417         this->Config->argc = argc;
418
419         if (chdir(Config->GetFullProgDir().c_str()))
420         {
421                 printf("Unable to change to my directory: %s\nAborted.", strerror(errno));
422                 exit(0);
423         }
424
425         this->Config->opertypes.clear();
426         this->Config->operclass.clear();
427
428         this->TIME = this->OLDTIME = this->startup_time = time(NULL);
429         srand(this->TIME);
430
431         *this->LogFileName = 0;
432         strlcpy(this->ConfigFileName, CONFIG_FILE, MAXBUF);
433
434         struct option longopts[] =
435         {
436                 { "nofork",     no_argument,            &do_nofork,     1       },
437                 { "logfile",    required_argument,      NULL,           'f'     },
438                 { "config",     required_argument,      NULL,           'c'     },
439                 { "debug",      no_argument,            &do_debug,      1       },
440                 { "nolog",      no_argument,            &do_nolog,      1       },
441                 { "runasroot",  no_argument,            &do_root,       1       },
442                 { "version",    no_argument,            &do_version,    1       },
443                 { "testsuite",  no_argument,            &do_testsuite,  1       },
444                 { 0, 0, 0, 0 }
445         };
446
447         int index;
448         while ((c = getopt_long_only(argc, argv, ":f:", longopts, &index)) != -1)
449         {
450                 switch (c)
451                 {
452                         case 'f':
453                                 /* Log filename was set */
454                                 strlcpy(LogFileName, optarg, MAXBUF);
455                         break;
456                         case 'c':
457                                 /* Config filename was set */
458                                 strlcpy(ConfigFileName, optarg, MAXBUF);
459                         break;
460                         case 0:
461                                 /* getopt_long_only() set an int variable, just keep going */
462                         break;
463                         case '?':
464                                 /* Unknown parameter */
465                         default:
466                                 /* Fall through to handle other weird values too */
467                                 printf("Unknown parameter '%s'\n", argv[optind-1]);
468                                 printf("Usage: %s [--nofork] [--nolog] [--debug] [--logfile <filename>]\n%*s[--runasroot] [--version] [--config <config>] [--testsuite]\n", argv[0], 8+strlen(argv[0]), " ");
469                                 Exit(EXIT_STATUS_ARGV);
470                         break;
471                 }
472         }
473
474         if (do_testsuite)
475                 do_nofork = do_debug = true;
476
477         if (do_version)
478         {
479                 printf("\n%s r%s\n", VERSION, REVISION);
480                 Exit(EXIT_STATUS_NOERROR);
481         }
482
483 #ifdef WIN32
484
485         // Handle forking
486         if(!do_nofork)
487         {
488                 DWORD ExitCode = WindowsForkStart(this);
489                 if(ExitCode)
490                         exit(ExitCode);
491         }
492
493         // Set up winsock
494         WSADATA wsadata;
495         WSAStartup(MAKEWORD(2,0), &wsadata);
496         ChangeWindowsSpecificPointers(this);
497 #endif
498         strlcpy(Config->MyExecutable,argv[0],MAXBUF);
499
500         /* Set the finished argument values */
501         Config->nofork = do_nofork;
502         Config->forcedebug = do_debug;
503         Config->writelog = !do_nolog;
504         Config->TestSuite = do_testsuite;
505
506         if (!this->OpenLog(argv, argc))
507         {
508                 printf("ERROR: Could not open logfile %s: %s\n\n", Config->logpath.c_str(), strerror(errno));
509                 Exit(EXIT_STATUS_LOG);
510         }
511
512         if (!ServerConfig::FileExists(this->ConfigFileName))
513         {
514 #ifdef WIN32
515                 /* Windows can (and defaults to) hide file extensions, so let's play a bit nice for windows users. */
516                 std::string txtconf = this->ConfigFileName;
517                 txtconf.append(".txt");
518
519                 if (ServerConfig::FileExists(txtconf.c_str()))
520                 {
521                         strlcat(this->ConfigFileName, ".txt", MAXBUF);
522                 }
523                 else
524 #endif
525                 {
526                         printf("ERROR: Cannot open config file: %s\nExiting...\n", this->ConfigFileName);
527                         this->Logs->Log("STARTUP",DEFAULT,"Unable to open config file %s", this->ConfigFileName);
528                         Exit(EXIT_STATUS_CONFIG);
529                 }
530         }
531
532         printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
533         printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
534         printf_c("Developers:\n");
535         printf_c("\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special\n");
536         printf_c("\t\033[1;32mpeavey, aquanight, psychon, dz, danieldg\033[0m\n\n");
537         printf_c("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
538
539         Config->ClearStack();
540
541         this->Modes = new ModeParser(this);
542
543         if (!do_root)
544                 this->CheckRoot();
545         else
546         {
547                 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
548                 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
549                 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
550                 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
551                 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
552                 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
553                 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
554                 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
555                 sleep(20);
556         }
557
558         this->SetSignals();
559
560         if (!Config->nofork)
561         {
562                 if (!this->DaemonSeed())
563                 {
564                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
565                         Logs->Log("STARTUP", DEFAULT, "ERROR: could not go into daemon mode. Shutting down.");
566                         Exit(EXIT_STATUS_FORK);
567                 }
568         }
569
570         SE->RecoverFromFork();
571
572         /* During startup we don't actually initialize this
573          * in the thread engine.
574          */
575         this->Config->Read();
576         this->Config->Apply(NULL, "");
577         Logs->OpenFileLogs();
578
579         /** Note: This is safe, the method checks for user == NULL */
580         this->Parser->SetupCommandTable();
581
582         this->Res = new DNS(this);
583
584         this->AddServerName(Config->ServerName);
585
586         /*
587          * Initialise SID/UID.
588          * For an explanation as to exactly how this works, and why it works this way, see GetUID().
589          *   -- w00t
590          */
591         if (!*Config->sid)
592         {
593                 // Generate one
594                 size_t sid = 0;
595
596                 for (const char* x = Config->ServerName; *x; ++x)
597                         sid = 5 * sid + *x;
598                 for (const char* y = Config->ServerDesc; *y; ++y)
599                         sid = 5 * sid + *y;
600                 sid = sid % 999;
601
602                 Config->sid[0] = (char)(sid / 100 + 48);
603                 Config->sid[1] = (char)(((sid / 10) % 10) + 48);
604                 Config->sid[2] = (char)(sid % 10 + 48);
605                 Config->sid[3] = '\0';
606         }
607
608         /* set up fake client again this time with the correct uid */
609         this->FakeClient = new FakeUser(this, "!");
610         this->FakeClient->SetFakeServer(Config->ServerName);
611
612         // Get XLine to do it's thing.
613         this->XLines->CheckELines();
614         this->XLines->ApplyLines();
615
616         CheckDie();
617         int bounditems = BindPorts(pl);
618
619         printf("\n");
620
621         this->Modules->LoadAll();
622
623         /* Just in case no modules were loaded - fix for bug #101 */
624         this->BuildISupport();
625         InitializeDisabledCommands(Config->DisabledCommands, this);
626
627         if (!pl.empty())
628         {
629                 printf("\nWARNING: Not all your client ports could be bound --\nstarting anyway with %d of %d client ports bound.\n\n",
630                         bounditems, bounditems + (int)pl.size());
631                 printf("The following port(s) failed to bind:\n");
632                 printf("Hint: Try using a public IP instead of blank or *\n\n");
633                 int j = 1;
634                 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
635                 {
636                         printf("%d.\tAddress: %s\tReason: %s\n", j, i->first.empty() ? "<all>" : i->first.c_str(), i->second.c_str());
637                 }
638         }
639
640         printf("\nInspIRCd is now running as '%s'[%s] with %d max open sockets\n", Config->ServerName,Config->GetSID().c_str(), SE->GetMaxFds());
641
642 #ifndef WINDOWS
643         if (!Config->nofork)
644         {
645                 if (kill(getppid(), SIGTERM) == -1)
646                 {
647                         printf("Error killing parent process: %s\n",strerror(errno));
648                         Logs->Log("STARTUP", DEFAULT, "Error killing parent process: %s",strerror(errno));
649                 }
650         }
651
652         if (isatty(0) && isatty(1) && isatty(2))
653         {
654                 /* We didn't start from a TTY, we must have started from a background process -
655                  * e.g. we are restarting, or being launched by cron. Dont kill parent, and dont
656                  * close stdin/stdout
657                  */
658                 if ((!do_nofork) && (!do_testsuite))
659                 {
660                         fclose(stdin);
661                         fclose(stderr);
662                         fclose(stdout);
663                 }
664                 else
665                 {
666                         Logs->Log("STARTUP", DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
667                 }
668         }
669 #else
670         WindowsIPC = new IPC(this);
671         if(!Config->nofork)
672         {
673                 WindowsForkKillOwner(this);
674                 FreeConsole();
675         }
676         /* Set win32 service as running, if we are running as a service */
677         SetServiceRunning();
678 #endif
679
680         Logs->Log("STARTUP", DEFAULT, "Startup complete as '%s'[%s], %d max open sockets", Config->ServerName,Config->GetSID().c_str(), SE->GetMaxFds());
681
682 #ifndef WIN32
683         if (*(this->Config->SetGroup))
684         {
685                 int ret;
686
687                 // setgroups
688                 ret = setgroups(0, NULL);
689
690                 if (ret == -1)
691                 {
692                         this->Logs->Log("SETGROUPS", DEFAULT, "setgroups() failed (wtf?): %s", strerror(errno));
693                         this->QuickExit(0);
694                 }
695
696                 // setgid
697                 struct group *g;
698
699                 errno = 0;
700                 g = getgrnam(this->Config->SetGroup);
701
702                 if (!g)
703                 {
704                         this->Logs->Log("SETGUID", DEFAULT, "getgrnam() failed (bad user?): %s", strerror(errno));
705                         this->QuickExit(0);
706                 }
707
708                 ret = setgid(g->gr_gid);
709
710                 if (ret == -1)
711                 {
712                         this->Logs->Log("SETGUID", DEFAULT, "setgid() failed (bad user?): %s", strerror(errno));
713                         this->QuickExit(0);
714                 }
715         }
716
717         if (*(this->Config->SetUser))
718         {
719                 // setuid
720                 struct passwd *u;
721
722                 errno = 0;
723                 u = getpwnam(this->Config->SetUser);
724
725                 if (!u)
726                 {
727                         this->Logs->Log("SETGUID", DEFAULT, "getpwnam() failed (bad user?): %s", strerror(errno));
728                         this->QuickExit(0);
729                 }
730
731                 int ret = setuid(u->pw_uid);
732
733                 if (ret == -1)
734                 {
735                         this->Logs->Log("SETGUID", DEFAULT, "setuid() failed (bad user?): %s", strerror(errno));
736                         this->QuickExit(0);
737                 }
738         }
739 #endif
740
741         this->WritePID(Config->PID);
742 }
743
744 int InspIRCd::Run()
745 {
746         /* See if we're supposed to be running the test suite rather than entering the mainloop */
747         if (Config->TestSuite)
748         {
749                 TestSuite* ts = new TestSuite(this);
750                 delete ts;
751                 Exit(0);
752         }
753
754         while (true)
755         {
756 #ifndef WIN32
757                 static rusage ru;
758 #else
759                 static time_t uptime;
760                 static struct tm * stime;
761                 static char window_title[100];
762 #endif
763
764                 /* Check if there is a config thread which has finished executing but has not yet been freed */
765                 if (this->ConfigThread && this->ConfigThread->IsDone())
766                 {
767                         /* Rehash has completed */
768                         this->Logs->Log("CONFIG",DEBUG,"Detected ConfigThread exiting, tidying up...");
769
770                         /* Switch over logfiles */
771                         Logs->CloseLogs();
772                         Logs->OpenFileLogs();
773
774                         /*
775                          * Apply the changed configuration from the rehash. This is not done within the
776                          * configuration thread becasuse they may invoke functions that are not threadsafe.
777                          *
778                          * XXX: The order of these is IMPORTANT, do not reorder them without testing
779                          * thoroughly!!!
780                          */
781                         this->ConfigThread->Finish();
782                         this->XLines->CheckELines();
783                         this->XLines->ApplyLines();
784                         this->Res->Rehash();
785                         this->ResetMaxBans();
786                         InitializeDisabledCommands(Config->DisabledCommands, this);
787                         User* user = ConfigThread->TheUserUID.empty() ? FindNick(ConfigThread->TheUserUID) : NULL;
788                         FOREACH_MOD_I(this, I_OnRehash, OnRehash(user));
789                         this->BuildISupport();
790
791                         delete ConfigThread;
792                         ConfigThread = NULL;
793                 }
794
795                 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
796                  * Once per loop iteration is pleanty.
797                  */
798                 OLDTIME = TIME;
799                 TIME = time(NULL);
800
801                 /* Run background module timers every few seconds
802                  * (the docs say modules shouldnt rely on accurate
803                  * timing using this event, so we dont have to
804                  * time this exactly).
805                  */
806                 if (TIME != OLDTIME)
807                 {
808                         /* Allow a buffer of two seconds drift on this so that ntpdate etc dont harass admins */
809                         if (TIME < OLDTIME - 2)
810                         {
811                                 SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %lu secs.", (unsigned long)OLDTIME-TIME);
812                         }
813                         else if (TIME > OLDTIME + 2)
814                         {
815                                 SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is jumping FORWARDS! Clock skipped %lu secs.", (unsigned long)TIME - OLDTIME);
816                         }
817
818                         if ((TIME % 3600) == 0)
819                         {
820                                 this->RehashUsersAndChans();
821                                 FOREACH_MOD_I(this, I_OnGarbageCollect, OnGarbageCollect());
822                         }
823
824                         Timers->TickTimers(TIME);
825                         this->DoBackgroundUserStuff();
826
827                         if ((TIME % 5) == 0)
828                         {
829                                 FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
830                                 SNO->FlushSnotices();
831                         }
832 #ifndef WIN32
833                         /* Same change as in cmd_stats.cpp, use RUSAGE_SELF rather than '0' -- Om */
834                         if (!getrusage(RUSAGE_SELF, &ru))
835                         {
836                                 gettimeofday(&this->stats->LastSampled, NULL);
837                                 this->stats->LastCPU = ru.ru_utime;
838                         }
839 #else
840                         WindowsIPC->Check();
841 #endif
842                 }
843
844                 /* Call the socket engine to wait on the active
845                  * file descriptors. The socket engine has everything's
846                  * descriptors in its list... dns, modules, users,
847                  * servers... so its nice and easy, just one call.
848                  * This will cause any read or write events to be
849                  * dispatched to their handlers.
850                  */
851                 this->SE->DispatchEvents();
852
853                 /* if any users were quit, take them out */
854                 this->GlobalCulls.Apply();
855
856                 /* If any inspsockets closed, remove them */
857                 this->BufferedSocketCull();
858
859                 if (this->s_signal)
860                 {
861                         this->SignalHandler(s_signal);
862                         this->s_signal = 0;
863                 }
864         }
865
866         return 0;
867 }
868
869 void InspIRCd::BufferedSocketCull()
870 {
871         for (std::map<BufferedSocket*,BufferedSocket*>::iterator x = SocketCull.begin(); x != SocketCull.end(); ++x)
872         {
873                 this->Logs->Log("MISC",DEBUG,"Cull socket");
874                 SE->DelFd(x->second);
875                 x->second->Close();
876                 delete x->second;
877         }
878         SocketCull.clear();
879 }
880
881 /**********************************************************************************/
882
883 /**
884  * An ircd in five lines! bwahahaha. ahahahahaha. ahahah *cough*.
885  */
886
887 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
888  * (until this returns true, a user will block in the waiting state, waiting to connect up to the
889  * registration timeout maximum seconds)
890  */
891 bool InspIRCd::AllModulesReportReady(User* user)
892 {
893         for (EventHandlerIter i = Modules->EventHandlers[I_OnCheckReady].begin(); i != Modules->EventHandlers[I_OnCheckReady].end(); ++i)
894         {
895                 if (!(*i)->OnCheckReady(user))
896                         return false;
897         }
898         return true;
899 }
900
901 time_t InspIRCd::Time()
902 {
903         return TIME;
904 }
905
906 void InspIRCd::SetSignal(int signal)
907 {
908         *mysig = signal;
909 }
910
911 /* On posix systems, the flow of the program starts right here, with
912  * ENTRYPOINT being a #define that defines main(). On Windows, ENTRYPOINT
913  * defines smain() and the real main() is in the service code under
914  * win32service.cpp. This allows the service control manager to control
915  * the process where we are running as a windows service.
916  */
917 ENTRYPOINT
918 {
919         SI = new InspIRCd(argc, argv);
920         mysig = &SI->s_signal;
921         SI->Run();
922         delete SI;
923         return 0;
924 }