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