]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
1403cdef5a5805b10b22c08810839a22cc8a58af
[user/henk/code/inspircd.git] / src / inspircd.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2012 William Pitcock <nenolod@dereferenced.org>
5  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
6  *   Copyright (C) 2003-2008 Craig Edwards <craigedwards@brainbox.cc>
7  *   Copyright (C) 2008 Uli Schlachter <psychon@znc.in>
8  *   Copyright (C) 2006-2008 Robin Burchell <robin+git@viroteck.net>
9  *   Copyright (C) 2006-2007 Oliver Lupton <oliverlupton@gmail.com>
10  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
11  *   Copyright (C) 2007 Burlex <???@???>
12  *   Copyright (C) 2003 Craig McLure <craig@chatspike.net>
13  *   Copyright (C) 2003 randomdan <???@???>
14  *
15  * This file is part of InspIRCd.  InspIRCd is free software: you can
16  * redistribute it and/or modify it under the terms of the GNU General Public
17  * License as published by the Free Software Foundation, version 2.
18  *
19  * This program is distributed in the hope that it will be useful, but WITHOUT
20  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
21  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
22  * details.
23  *
24  * You should have received a copy of the GNU General Public License
25  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
26  */
27
28
29 /* $Core */
30 #include "inspircd.h"
31 #include "inspircd_version.h"
32 #include <signal.h>
33
34 #ifndef _WIN32
35         #include <dirent.h>
36         #include <unistd.h>
37         #include <sys/resource.h>
38         #include <dlfcn.h>
39         #include <getopt.h>
40
41         /* Some systems don't define RUSAGE_SELF. This should fix them. */
42         #ifndef RUSAGE_SELF
43                 #define RUSAGE_SELF 0
44         #endif
45
46         #include <pwd.h> // setuid
47         #include <grp.h> // setgid
48 #else
49         WORD g_wOriginalColors;
50         WORD g_wBackgroundColor;
51         HANDLE g_hStdout;
52 #endif
53
54 #include <fstream>
55 #include <iostream>
56 #include "xline.h"
57 #include "bancache.h"
58 #include "socketengine.h"
59 #include "socket.h"
60 #include "command_parse.h"
61 #include "exitcodes.h"
62 #include "caller.h"
63 #include "testsuite.h"
64
65 InspIRCd* ServerInstance = NULL;
66 int* mysig = NULL;
67
68 /** Seperate from the other casemap tables so that code *can* still exclusively rely on RFC casemapping
69  * if it must.
70  *
71  * This is provided as a pointer so that modules can change it to their custom mapping tables,
72  * e.g. for national character support.
73  */
74 unsigned const char *national_case_insensitive_map = rfc_case_insensitive_map;
75
76
77 /* Moved from exitcodes.h -- due to duplicate symbols -- Burlex
78  * XXX this is a bit ugly. -- w00t
79  */
80 const char* ExitCodes[] =
81 {
82                 "No error", /* 0 */
83                 "DIE command", /* 1 */
84                 "execv() failed", /* 2 */
85                 "Internal error", /* 3 */
86                 "Config file error", /* 4 */
87                 "Logfile error", /* 5 */
88                 "POSIX fork failed", /* 6 */
89                 "Bad commandline parameters", /* 7 */
90                 "No ports could be bound", /* 8 */
91                 "Can't write PID file", /* 9 */
92                 "SocketEngine could not initialize", /* 10 */
93                 "Refusing to start up as root", /* 11 */
94                 "Found a <die> tag!", /* 12 */
95                 "Couldn't load module on startup", /* 13 */
96                 "Could not create windows forked process", /* 14 */
97                 "Received SIGTERM", /* 15 */
98                 "Bad command handler loaded", /* 16 */
99                 "RegisterServiceCtrlHandler failed", /* 17 */
100                 "UpdateSCMStatus failed", /* 18 */
101                 "CreateEvent failed" /* 19 */
102 };
103
104 template<typename T> static void DeleteZero(T*&n)
105 {
106         T* t = n;
107         n = NULL;
108         delete t;
109 }
110
111 void InspIRCd::Cleanup()
112 {
113         for (unsigned int i = 0; i < ports.size(); i++)
114         {
115                 /* This calls the constructor and closes the listening socket */
116                 ports[i]->cull();
117                 delete ports[i];
118         }
119         ports.clear();
120
121         /* Close all client sockets, or the new process inherits them */
122         LocalUserList::reverse_iterator i = Users->local_users.rbegin();
123         while (i != this->Users->local_users.rend())
124         {
125                 User* u = *i++;
126                 Users->QuitUser(u, "Server shutdown");
127         }
128
129         GlobalCulls.Apply();
130         Modules->UnloadAll();
131
132         /* Delete objects dynamically allocated in constructor (destructor would be more appropriate, but we're likely exiting) */
133         /* Must be deleted before modes as it decrements modelines */
134         if (FakeClient)
135                 FakeClient->cull();
136         if (Res)
137                 Res->cull();
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         char** argv = Config->cmdline.argv;
170
171 #ifdef _WIN32
172         char module[MAX_PATH];
173         if (GetModuleFileNameA(NULL, module, MAX_PATH))
174                 me = module;
175 #else
176         me = argv[0];
177 #endif
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 doesn't free its buckets when we delete items, we occasionally
195  * recreate the hash to free them up.
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.
198  * Since this is quite expensive, it's not done very often.
199  */
200 void InspIRCd::RehashUsersAndChans()
201 {
202         user_hash* old_users = Users->clientlist;
203         Users->clientlist = new user_hash;
204         for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
205                 Users->clientlist->insert(*n);
206         delete old_users;
207
208         user_hash* old_uuid = Users->uuidlist;
209         Users->uuidlist = new user_hash;
210         for (user_hash::const_iterator n = old_uuid->begin(); n != old_uuid->end(); n++)
211                 Users->uuidlist->insert(*n);
212         delete old_uuid;
213
214         chan_hash* old_chans = chanlist;
215         chanlist = new chan_hash;
216         for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
217                 chanlist->insert(*n);
218         delete old_chans;
219
220         // Reset the already_sent IDs so we don't wrap it around and drop a message
221         LocalUser::already_sent_id = 0;
222         for (LocalUserList::const_iterator i = Users->local_users.begin(); i != Users->local_users.end(); i++)
223         {
224                 (**i).already_sent = 0;
225                 (**i).RemoveExpiredInvites();
226         }
227 }
228
229 void InspIRCd::SetSignals()
230 {
231 #ifndef _WIN32
232         signal(SIGALRM, SIG_IGN);
233         signal(SIGHUP, InspIRCd::SetSignal);
234         signal(SIGPIPE, SIG_IGN);
235         signal(SIGCHLD, SIG_IGN);
236         /* We want E2BIG not a signal! */
237         signal(SIGXFSZ, SIG_IGN);
238 #endif
239         signal(SIGTERM, InspIRCd::SetSignal);
240 }
241
242 void InspIRCd::QuickExit(int status)
243 {
244         exit(0);
245 }
246
247 bool InspIRCd::DaemonSeed()
248 {
249 #ifdef _WIN32
250         std::cout << "InspIRCd Process ID: " << con_green << GetCurrentProcessId() << con_reset << std::endl;
251         return true;
252 #else
253         signal(SIGTERM, InspIRCd::QuickExit);
254
255         int childpid;
256         if ((childpid = fork ()) < 0)
257                 return false;
258         else if (childpid > 0)
259         {
260                 /* We wait here for the child process to kill us,
261                  * so that the shell prompt doesnt come back over
262                  * the output.
263                  * Sending a kill with a signal of 0 just checks
264                  * if the child pid is still around. If theyre not,
265                  * they threw an error and we should give up.
266                  */
267                 while (kill(childpid, 0) != -1)
268                         sleep(1);
269                 exit(0);
270         }
271         setsid ();
272         std::cout << "InspIRCd Process ID: " << con_green << getpid() << con_reset << std::endl;
273
274         signal(SIGTERM, InspIRCd::SetSignal);
275
276         rlimit rl;
277         if (getrlimit(RLIMIT_CORE, &rl) == -1)
278         {
279                 this->Logs->Log("STARTUP",DEFAULT,"Failed to getrlimit()!");
280                 return false;
281         }
282         rl.rlim_cur = rl.rlim_max;
283
284         if (setrlimit(RLIMIT_CORE, &rl) == -1)
285                         this->Logs->Log("STARTUP",DEFAULT,"setrlimit() failed, cannot increase coredump size.");
286
287         return true;
288 #endif
289 }
290
291 void InspIRCd::WritePID(const std::string &filename)
292 {
293 #ifndef _WIN32
294         std::string fname(filename);
295         if (fname.empty())
296                 fname = DATA_PATH "/inspircd.pid";
297         std::ofstream outfile(fname.c_str());
298         if (outfile.is_open())
299         {
300                 outfile << getpid();
301                 outfile.close();
302         }
303         else
304         {
305                 std::cout << "Failed to write PID-file '" << fname << "', exiting." << std::endl;
306                 this->Logs->Log("STARTUP",DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
307                 Exit(EXIT_STATUS_PID);
308         }
309 #endif
310 }
311
312 InspIRCd::InspIRCd(int argc, char** argv) :
313          ConfigFileName(CONFIG_PATH "/inspircd.conf"),
314
315          /* Functor pointer initialisation.
316           *
317           * THIS MUST MATCH THE ORDER OF DECLARATION OF THE FUNCTORS, e.g. the methods
318           * themselves within the class.
319           */
320          NICKForced("NICKForced", NULL),
321          OperQuit("OperQuit", NULL),
322          GenRandom(&HandleGenRandom),
323          IsChannel(&HandleIsChannel),
324          IsSID(&HandleIsSID),
325          Rehash(&HandleRehash),
326          IsNick(&HandleIsNick),
327          IsIdent(&HandleIsIdent),
328          FloodQuitUser(&HandleFloodQuitUser),
329          OnCheckExemption(&HandleOnCheckExemption)
330 {
331         ServerInstance = this;
332
333         Extensions.Register(&NICKForced);
334         Extensions.Register(&OperQuit);
335
336         FailedPortList pl;
337         int do_version = 0, do_nofork = 0, do_debug = 0,
338             do_nolog = 0, do_root = 0, do_testsuite = 0;    /* flag variables */
339         int c = 0;
340
341         // Initialize so that if we exit before proper initialization they're not deleted
342         this->Logs = 0;
343         this->Threads = 0;
344         this->PI = 0;
345         this->Users = 0;
346         this->chanlist = 0;
347         this->Config = 0;
348         this->SNO = 0;
349         this->BanCache = 0;
350         this->Modules = 0;
351         this->stats = 0;
352         this->Timers = 0;
353         this->Parser = 0;
354         this->XLines = 0;
355         this->Modes = 0;
356         this->Res = 0;
357         this->ConfigThread = NULL;
358         this->FakeClient = NULL;
359
360         UpdateTime();
361         this->startup_time = TIME.tv_sec;
362
363         // This must be created first, so other parts of Insp can use it while starting up
364         this->Logs = new LogManager;
365
366         SE = CreateSocketEngine();
367
368         this->Threads = new ThreadEngine;
369
370         /* Default implementation does nothing */
371         this->PI = new ProtocolInterface;
372
373         this->s_signal = 0;
374
375         // Create base manager classes early, so nothing breaks
376         this->Users = new UserManager;
377
378         this->Users->clientlist = new user_hash();
379         this->Users->uuidlist = new user_hash();
380         this->chanlist = new chan_hash();
381
382         this->Config = new ServerConfig;
383         this->SNO = new SnomaskManager;
384         this->BanCache = new BanCacheManager;
385         this->Modules = new ModuleManager();
386         this->stats = new serverstats();
387         this->Timers = new TimerManager;
388         this->Parser = new CommandParser;
389         this->XLines = new XLineManager;
390
391         this->Config->cmdline.argv = argv;
392         this->Config->cmdline.argc = argc;
393
394 #ifdef _WIN32
395         srand(TIME.tv_nsec ^ TIME.tv_sec);
396
397         // Initialize the console values
398         g_hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
399         CONSOLE_SCREEN_BUFFER_INFO bufinf;
400         if(GetConsoleScreenBufferInfo(g_hStdout, &bufinf))
401         {
402                 g_wOriginalColors = bufinf.wAttributes & 0x00FF;
403                 g_wBackgroundColor = bufinf.wAttributes & 0x00F0;
404         }
405         else
406         {
407                 g_wOriginalColors = FOREGROUND_RED|FOREGROUND_BLUE|FOREGROUND_GREEN;
408                 g_wBackgroundColor = 0;
409         }
410 #else
411         srandom(TIME.tv_nsec ^ TIME.tv_sec);
412 #endif
413
414         struct option longopts[] =
415         {
416                 { "nofork",     no_argument,            &do_nofork,     1       },
417                 { "logfile",    required_argument,      NULL,           'f'     },
418                 { "config",     required_argument,      NULL,           'c'     },
419                 { "debug",      no_argument,            &do_debug,      1       },
420                 { "nolog",      no_argument,            &do_nolog,      1       },
421                 { "runasroot",  no_argument,            &do_root,       1       },
422                 { "version",    no_argument,            &do_version,    1       },
423                 { "testsuite",  no_argument,            &do_testsuite,  1       },
424                 { 0, 0, 0, 0 }
425         };
426
427         int index;
428         while ((c = getopt_long(argc, argv, ":c:f:", longopts, &index)) != -1)
429         {
430                 switch (c)
431                 {
432                         case 'f':
433                                 /* Log filename was set */
434                                 Config->cmdline.startup_log = optarg;
435                         break;
436                         case 'c':
437                                 /* Config filename was set */
438                                 ConfigFileName = optarg;
439                         break;
440                         case 0:
441                                 /* getopt_long_only() set an int variable, just keep going */
442                         break;
443                         case '?':
444                                 /* Unknown parameter */
445                         default:
446                                 /* Fall through to handle other weird values too */
447                                 std::cout << "Unknown parameter '" << argv[optind-1] << "'" << std::endl;
448                                 std::cout << "Usage: " << argv[0] << " [--nofork] [--nolog] [--debug] [--logfile <filename>] " << std::endl <<
449                                         std::string(static_cast<int>(8+strlen(argv[0])), ' ') << "[--runasroot] [--version] [--config <config>] [--testsuite]" << std::endl;
450                                 Exit(EXIT_STATUS_ARGV);
451                         break;
452                 }
453         }
454
455         if (do_testsuite)
456                 do_nofork = do_debug = true;
457
458         if (do_version)
459         {
460                 std::cout << std::endl << VERSION << " r" << REVISION << std::endl;
461                 Exit(EXIT_STATUS_NOERROR);
462         }
463
464 #ifdef _WIN32
465         // Set up winsock
466         WSADATA wsadata;
467         WSAStartup(MAKEWORD(2,2), &wsadata);
468 #endif
469
470         /* Set the finished argument values */
471         Config->cmdline.nofork = (do_nofork != 0);
472         Config->cmdline.forcedebug = (do_debug != 0);
473         Config->cmdline.writelog = (!do_nolog != 0);
474         Config->cmdline.TestSuite = (do_testsuite != 0);
475
476         if (do_debug)
477         {
478                 FileWriter* fw = new FileWriter(stdout);
479                 FileLogStream* fls = new FileLogStream(RAWIO, fw);
480                 Logs->AddLogTypes("*", fls, true);
481         }
482         else if (!this->OpenLog(argv, argc))
483         {
484                 std::cout << "ERROR: Could not open initial logfile " << Config->cmdline.startup_log << ": " << strerror(errno) << std::endl << std::endl;
485                 Exit(EXIT_STATUS_LOG);
486         }
487
488         if (!ServerConfig::FileExists(ConfigFileName.c_str()))
489         {
490 #ifdef _WIN32
491                 /* Windows can (and defaults to) hide file extensions, so let's play a bit nice for windows users. */
492                 std::string txtconf = this->ConfigFileName;
493                 txtconf.append(".txt");
494
495                 if (ServerConfig::FileExists(txtconf.c_str()))
496                 {
497                         ConfigFileName = txtconf;
498                 }
499                 else
500 #endif
501                 {
502                         std::cout << "ERROR: Cannot open config file: " << ConfigFileName << std::endl << "Exiting..." << std::endl;
503                         this->Logs->Log("STARTUP",DEFAULT,"Unable to open config file %s", ConfigFileName.c_str());
504                         Exit(EXIT_STATUS_CONFIG);
505                 }
506         }
507
508         std::cout << con_green << "Inspire Internet Relay Chat Server" << con_reset << ", compiled on " __DATE__ " at " __TIME__ << std::endl;
509         std::cout << con_green << "(C) InspIRCd Development Team." << con_reset << std::endl << std::endl;
510         std::cout << "Developers:" << std::endl;
511         std::cout << con_green << "\tBrain, FrostyCoolSlug, w00t, Om, Special, peavey" << std::endl;
512         std::cout << "\taquanight, psychon, dz, danieldg, jackmcbarn" << std::endl;\r
513         std::cout << "\tAttila" << con_reset << std::endl << std::endl;
514         std::cout << "Others:\t\t\t" << con_green << "See /INFO Output" << con_reset << std::endl;
515
516         this->Modes = new ModeParser;
517
518 #ifndef _WIN32
519         if (!do_root)
520                 this->CheckRoot();
521         else
522         {
523                 std::cout << "* WARNING * WARNING * WARNING * WARNING * WARNING *" << std::endl\r
524                 << "YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED" << std::endl\r
525                 << "AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED" << std::endl\r
526                 << "OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR" << std::endl\r
527                 << "SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN" << std::endl\r
528                 << "TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART" << std::endl\r
529                 << "THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!" << std::endl << std::endl\r
530                 << "InspIRCd starting in 20 seconds, ctrl+c to abort..." << std::endl;\r
531                 sleep(20);
532         }
533 #endif
534
535         this->SetSignals();
536
537         if (!Config->cmdline.nofork)
538         {
539                 if (!this->DaemonSeed())
540                 {
541                         std::cout << "ERROR: could not go into daemon mode. Shutting down." << std::endl;
542                         Logs->Log("STARTUP", DEFAULT, "ERROR: could not go into daemon mode. Shutting down.");
543                         Exit(EXIT_STATUS_FORK);
544                 }
545         }
546
547         SE->RecoverFromFork();
548
549         /* During startup we don't actually initialize this
550          * in the thread engine.
551          */
552         this->Config->Read();
553         this->Config->Apply(NULL, "");
554         Logs->OpenFileLogs();
555
556         this->Res = new DNS();
557
558         /*
559          * Initialise SID/UID.
560          * For an explanation as to exactly how this works, and why it works this way, see GetUID().
561          *   -- w00t
562          */
563         if (Config->sid.empty())
564         {
565                 // Generate one
566                 unsigned int sid = 0;
567                 char sidstr[4];
568
569                 for (const char* x = Config->ServerName.c_str(); *x; ++x)
570                         sid = 5 * sid + *x;
571                 for (const char* y = Config->ServerDesc.c_str(); *y; ++y)
572                         sid = 5 * sid + *y;
573                 sprintf(sidstr, "%03d", sid % 1000);
574
575                 Config->sid = sidstr;
576         }
577
578         /* set up fake client again this time with the correct uid */
579         this->FakeClient = new FakeUser(Config->sid, Config->ServerName);
580
581         // Get XLine to do it's thing.
582         this->XLines->CheckELines();
583         this->XLines->ApplyLines();
584
585         int bounditems = BindPorts(pl);
586
587         std::cout << std::endl;
588
589         this->Modules->LoadAll();
590
591         /* Just in case no modules were loaded - fix for bug #101 */
592         this->BuildISupport();
593         Config->ApplyDisabledCommands(Config->DisabledCommands);
594
595         if (!pl.empty())
596         {
597                 std::cout << std::endl << "WARNING: Not all your client ports could be bound -- " << std::endl << "starting anyway with " << bounditems
598                         << " of " << bounditems + (int)pl.size() << " client ports bound." << std::endl << std::endl;
599                 std::cout << "The following port(s) failed to bind:" << std::endl << std::endl;
600                 int j = 1;
601                 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
602                 {
603                         std::cout << j << ".\tAddress: " << (i->first.empty() ? "<all>" : i->first) << " \tReason: " << i->second << std::endl;
604                 }
605
606                 std::cout << std::endl << "Hint: Try using a public IP instead of blank or *" << std::endl;
607         }
608
609         std::cout << "InspIRCd is now running as '" << Config->ServerName << "'[" << Config->GetSID() << "] with " << SE->GetMaxFds() << " max open sockets" << std::endl;
610
611 #ifndef _WIN32
612         if (!Config->cmdline.nofork)
613         {
614                 if (kill(getppid(), SIGTERM) == -1)
615                 {
616                         std::cout << "Error killing parent process: " << strerror(errno) << std::endl;
617                         Logs->Log("STARTUP", DEFAULT, "Error killing parent process: %s",strerror(errno));
618                 }
619         }
620
621         /* Explicitly shut down stdio's stdin/stdout/stderr.
622          *
623          * The previous logic here was to only do this if stdio was connected to a controlling
624          * terminal.  However, we must do this always to avoid information leaks and other
625          * problems related to stdio.
626          *
627          * The only exception is if we are in debug mode.
628          *
629          *    -- nenolod
630          */
631         if ((!do_nofork) && (!do_testsuite) && (!Config->cmdline.forcedebug))
632         {
633                 int fd = open("/dev/null", O_RDWR);
634
635                 fclose(stdin);
636                 fclose(stderr);
637                 fclose(stdout);
638
639                 if (dup2(fd, STDIN_FILENO) < 0)
640                         Logs->Log("STARTUP", DEFAULT, "Failed to dup /dev/null to stdin.");
641                 if (dup2(fd, STDOUT_FILENO) < 0)
642                         Logs->Log("STARTUP", DEFAULT, "Failed to dup /dev/null to stdout.");
643                 if (dup2(fd, STDERR_FILENO) < 0)
644                         Logs->Log("STARTUP", DEFAULT, "Failed to dup /dev/null to stderr.");
645                 close(fd);
646         }
647         else
648         {
649                 Logs->Log("STARTUP", DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
650         }
651 #else
652         /* Set win32 service as running, if we are running as a service */
653         SetServiceRunning();
654
655         // Handle forking
656         if(!do_nofork)
657         {
658                 FreeConsole();
659         }
660
661         QueryPerformanceFrequency(&stats->QPFrequency);
662 #endif
663
664         Logs->Log("STARTUP", DEFAULT, "Startup complete as '%s'[%s], %d max open sockets", Config->ServerName.c_str(),Config->GetSID().c_str(), SE->GetMaxFds());
665
666 #ifndef _WIN32
667         std::string SetUser = Config->ConfValue("security")->getString("runasuser");
668         std::string SetGroup = Config->ConfValue("security")->getString("runasgroup");
669         if (!SetGroup.empty())
670         {
671                 int ret;
672
673                 // setgroups
674                 ret = setgroups(0, NULL);
675
676                 if (ret == -1)
677                 {
678                         this->Logs->Log("SETGROUPS", DEFAULT, "setgroups() failed (wtf?): %s", strerror(errno));
679                         this->QuickExit(0);
680                 }
681
682                 // setgid
683                 struct group *g;
684
685                 errno = 0;
686                 g = getgrnam(SetGroup.c_str());
687
688                 if (!g)
689                 {
690                         this->Logs->Log("SETGUID", DEFAULT, "getgrnam() failed (bad user?): %s", strerror(errno));
691                         this->QuickExit(0);
692                 }
693
694                 ret = setgid(g->gr_gid);
695
696                 if (ret == -1)
697                 {
698                         this->Logs->Log("SETGUID", DEFAULT, "setgid() failed (bad user?): %s", strerror(errno));
699                         this->QuickExit(0);
700                 }
701         }
702
703         if (!SetUser.empty())
704         {
705                 // setuid
706                 struct passwd *u;
707
708                 errno = 0;
709                 u = getpwnam(SetUser.c_str());
710
711                 if (!u)
712                 {
713                         this->Logs->Log("SETGUID", DEFAULT, "getpwnam() failed (bad user?): %s", strerror(errno));
714                         this->QuickExit(0);
715                 }
716
717                 int ret = setuid(u->pw_uid);
718
719                 if (ret == -1)
720                 {
721                         this->Logs->Log("SETGUID", DEFAULT, "setuid() failed (bad user?): %s", strerror(errno));
722                         this->QuickExit(0);
723                 }
724         }
725
726         this->WritePID(Config->PID);
727 #endif
728 }
729
730 void InspIRCd::UpdateTime()
731 {
732 #ifdef _WIN32
733         SYSTEMTIME st;
734         GetSystemTime(&st);
735
736         TIME.tv_sec = time(NULL);
737         TIME.tv_nsec = st.wMilliseconds;
738 #else
739         #ifdef HAS_CLOCK_GETTIME
740                 clock_gettime(CLOCK_REALTIME, &TIME);
741         #else
742                 struct timeval tv;
743                 gettimeofday(&tv, NULL);
744                 TIME.tv_sec = tv.tv_sec;
745                 TIME.tv_nsec = tv.tv_usec * 1000;
746         #endif
747 #endif
748 }
749
750 int InspIRCd::Run()
751 {
752         /* See if we're supposed to be running the test suite rather than entering the mainloop */
753         if (Config->cmdline.TestSuite)
754         {
755                 TestSuite* ts = new TestSuite;
756                 delete ts;
757                 Exit(0);
758         }
759
760         UpdateTime();
761         time_t OLDTIME = TIME.tv_sec;
762
763         while (true)
764         {
765 #ifndef _WIN32
766                 static rusage ru;
767 #endif
768
769                 /* Check if there is a config thread which has finished executing but has not yet been freed */
770                 if (this->ConfigThread && this->ConfigThread->IsDone())
771                 {
772                         /* Rehash has completed */
773                         this->Logs->Log("CONFIG",DEBUG,"Detected ConfigThread exiting, tidying up...");
774
775                         this->ConfigThread->Finish();
776
777                         ConfigThread->join();
778                         delete ConfigThread;
779                         ConfigThread = NULL;
780                 }
781
782                 UpdateTime();
783
784                 /* Run background module timers every few seconds
785                  * (the docs say modules shouldnt rely on accurate
786                  * timing using this event, so we dont have to
787                  * time this exactly).
788                  */
789                 if (TIME.tv_sec != OLDTIME)
790                 {
791 #ifndef _WIN32
792                         getrusage(RUSAGE_SELF, &ru);
793                         stats->LastSampled = TIME;
794                         stats->LastCPU = ru.ru_utime;
795 #else
796                         if(QueryPerformanceCounter(&stats->LastSampled))
797                         {
798                                 FILETIME CreationTime;
799                                 FILETIME ExitTime;
800                                 FILETIME KernelTime;
801                                 FILETIME UserTime;
802                                 GetProcessTimes(GetCurrentProcess(), &CreationTime, &ExitTime, &KernelTime, &UserTime);
803                                 stats->LastCPU.dwHighDateTime = KernelTime.dwHighDateTime + UserTime.dwHighDateTime;
804                                 stats->LastCPU.dwLowDateTime = KernelTime.dwLowDateTime + UserTime.dwLowDateTime;
805                         }
806 #endif
807
808                         /* Allow a buffer of two seconds drift on this so that ntpdate etc dont harass admins */
809                         if (TIME.tv_sec < 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.tv_sec);
812                         }
813                         else if (TIME.tv_sec > OLDTIME + 2)
814                         {
815                                 SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is jumping FORWARDS! Clock skipped %lu secs.", (unsigned long)TIME.tv_sec - OLDTIME);
816                         }
817 \r
818                         OLDTIME = TIME.tv_sec;
819
820                         if ((TIME.tv_sec % 3600) == 0)
821                         {
822                                 this->RehashUsersAndChans();
823                                 FOREACH_MOD(I_OnGarbageCollect, OnGarbageCollect());
824                         }
825
826                         Timers->TickTimers(TIME.tv_sec);
827                         this->DoBackgroundUserStuff();
828
829                         if ((TIME.tv_sec % 5) == 0)
830                         {
831                                 FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME.tv_sec));
832                                 SNO->FlushSnotices();
833                         }
834                 }
835
836                 /* Call the socket engine to wait on the active
837                  * file descriptors. The socket engine has everything's
838                  * descriptors in its list... dns, modules, users,
839                  * servers... so its nice and easy, just one call.
840                  * This will cause any read or write events to be
841                  * dispatched to their handlers.
842                  */
843                 this->SE->DispatchTrialWrites();
844                 this->SE->DispatchEvents();
845
846                 /* if any users were quit, take them out */
847                 GlobalCulls.Apply();
848                 AtomicActions.Run();
849
850                 if (this->s_signal)
851                 {
852                         this->SignalHandler(s_signal);
853                         this->s_signal = 0;
854                 }
855         }
856
857         return 0;
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(LocalUser* user)
871 {
872         ModResult res;
873         FIRST_MOD_RESULT(OnCheckReady, res, (user));
874         return (res == MOD_RES_PASSTHRU);
875 }
876
877 void InspIRCd::SetSignal(int signal)
878 {
879         *mysig = signal;
880 }
881
882 /* On posix systems, the flow of the program starts right here, with
883  * ENTRYPOINT being a #define that defines main(). On Windows, ENTRYPOINT
884  * defines smain() and the real main() is in the service code under
885  * win32service.cpp. This allows the service control manager to control
886  * the process where we are running as a windows service.
887  */
888 ENTRYPOINT
889 {
890         new InspIRCd(argc, argv);
891         mysig = &ServerInstance->s_signal;
892         ServerInstance->Run();
893         delete ServerInstance;
894         return 0;
895 }