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