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