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