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