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