]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
Extract port binding code to a function and improve output.
[user/henk/code/inspircd.git] / src / inspircd.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2012 William Pitcock <nenolod@dereferenced.org>
5  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
6  *   Copyright (C) 2003-2008 Craig Edwards <craigedwards@brainbox.cc>
7  *   Copyright (C) 2008 Uli Schlachter <psychon@znc.in>
8  *   Copyright (C) 2006-2008 Robin Burchell <robin+git@viroteck.net>
9  *   Copyright (C) 2006-2007 Oliver Lupton <oliverlupton@gmail.com>
10  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
11  *   Copyright (C) 2007 Burlex <???@???>
12  *   Copyright (C) 2003 Craig McLure <craig@chatspike.net>
13  *   Copyright (C) 2003 randomdan <???@???>
14  *
15  * This file is part of InspIRCd.  InspIRCd is free software: you can
16  * redistribute it and/or modify it under the terms of the GNU General Public
17  * License as published by the Free Software Foundation, version 2.
18  *
19  * This program is distributed in the hope that it will be useful, but WITHOUT
20  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
21  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
22  * details.
23  *
24  * You should have received a copy of the GNU General Public License
25  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
26  */
27
28
29 #include "inspircd.h"
30 #include <signal.h>
31
32 #ifndef _WIN32
33         #include <unistd.h>
34         #include <sys/resource.h>
35         #include <dlfcn.h>
36         #include <getopt.h>
37         #include <pwd.h> // setuid
38         #include <grp.h> // setgid
39 #else
40         WORD g_wOriginalColors;
41         WORD g_wBackgroundColor;
42         HANDLE g_hStdout;
43 #endif
44
45 #include <fstream>
46 #include <iostream>
47 #include "xline.h"
48 #include "exitcodes.h"
49
50 InspIRCd* ServerInstance = NULL;
51
52 /** Seperate from the other casemap tables so that code *can* still exclusively rely on RFC casemapping
53  * if it must.
54  *
55  * This is provided as a pointer so that modules can change it to their custom mapping tables,
56  * e.g. for national character support.
57  */
58 unsigned const char *national_case_insensitive_map = rfc_case_insensitive_map;
59
60
61 /* Moved from exitcodes.h -- due to duplicate symbols -- Burlex
62  * XXX this is a bit ugly. -- w00t
63  */
64 const char* ExitCodes[] =
65 {
66                 "No error",                                                             // 0
67                 "DIE command",                                                  // 1
68                 "Config file error",                                    // 2
69                 "Logfile error",                                                // 3
70                 "POSIX fork failed",                                    // 4
71                 "Bad commandline parameters",                   // 5
72                 "Can't write PID file",                                 // 6
73                 "SocketEngine could not initialize",    // 7
74                 "Refusing to start up as root",                 // 8
75                 "Couldn't load module on startup",              // 9
76                 "Received SIGTERM"                                              // 10
77 };
78
79 namespace
80 {
81         void VoidSignalHandler(int);
82
83         // Warns a user running as root that they probably shouldn't.
84         void CheckRoot()
85         {
86 #ifndef _WIN32
87                 if (getegid() != 0 && geteuid() != 0)
88                         return;
89
90                 std::cout << con_red << "Warning!" << con_reset << " You have started as root. Running as root is generally not required" << std::endl
91                         << "and may allow an attacker to gain access to your system if they find a way to" << std::endl
92                         << "exploit your IRC server." << std::endl
93                         << std::endl;
94                 if (isatty(fileno(stdout)))
95                 {
96                         std::cout << "InspIRCd will start in 30 seconds. If you are sure that you need to run as root" << std::endl
97                                 << "then you can pass the " << con_bright << "--runasroot" << con_reset << " option to disable this wait." << std::endl;
98                         sleep(30);
99                 }
100                 else
101                 {
102                         std::cout << "If you are sure that you need to run as root then you can pass the " << con_bright << "--runasroot" << con_reset << std::endl
103                                 << "option to disable this error." << std::endl;
104                                 ServerInstance->Exit(EXIT_STATUS_ROOT);
105                 }
106 #endif
107         }
108
109         // Collects performance statistics for the STATS command.
110         void CollectStats()
111         {
112 #ifndef _WIN32
113                 static rusage ru;
114                 if (getrusage(RUSAGE_SELF, &ru) == -1)
115                         return; // Should never happen.
116
117                 ServerInstance->stats.LastSampled.tv_sec = ServerInstance->Time();
118                 ServerInstance->stats.LastSampled.tv_nsec = ServerInstance->Time_ns();
119                 ServerInstance->stats.LastCPU = ru.ru_utime;
120 #else
121                 if (!QueryPerformanceCounter(&ServerInstance->stats.LastSampled))
122                         return; // Should never happen.
123
124                 FILETIME CreationTime;
125                 FILETIME ExitTime;
126                 FILETIME KernelTime;
127                 FILETIME UserTime;
128                 GetProcessTimes(GetCurrentProcess(), &CreationTime, &ExitTime, &KernelTime, &UserTime);
129
130                 ServerInstance->stats.LastCPU.dwHighDateTime = KernelTime.dwHighDateTime + UserTime.dwHighDateTime;
131                 ServerInstance->stats.LastCPU.dwLowDateTime = KernelTime.dwLowDateTime + UserTime.dwLowDateTime;
132 #endif
133         }
134
135         // Deletes a pointer and then zeroes it.
136         template<typename T>
137         void DeleteZero(T*& pr)
138         {
139                 T* p = pr;
140                 pr = NULL;
141                 delete p;
142         }
143
144         // Drops to the unprivileged user/group specified in <security:runas{user,group}>.
145         void DropRoot()
146         {
147 #ifndef _WIN32
148                 ConfigTag* security = ServerInstance->Config->ConfValue("security");
149
150                 const std::string SetGroup = security->getString("runasgroup");
151                 if (!SetGroup.empty())
152                 {
153                         errno = 0;
154                         if (setgroups(0, NULL) == -1)
155                         {
156                                 ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "setgroups() failed (wtf?): %s", strerror(errno));
157                                 exit(EXIT_STATUS_CONFIG);
158                         }
159
160                         struct group* g = getgrnam(SetGroup.c_str());
161                         if (!g)
162                         {
163                                 ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "getgrnam(%s) failed (wrong group?): %s", SetGroup.c_str(), strerror(errno));
164                                 exit(EXIT_STATUS_CONFIG);
165                         }
166
167                         if (setgid(g->gr_gid) == -1)
168                         {
169                                 ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "setgid(%d) failed (wrong group?): %s", g->gr_gid, strerror(errno));
170                                 exit(EXIT_STATUS_CONFIG);
171                         }
172                 }
173
174                 const std::string SetUser = security->getString("runasuser");
175                 if (!SetUser.empty())
176                 {
177                         errno = 0;
178                         struct passwd* u = getpwnam(SetUser.c_str());
179                         if (!u)
180                         {
181                                 ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "getpwnam(%s) failed (wrong user?): %s", SetUser.c_str(), strerror(errno));
182                                 exit(EXIT_STATUS_CONFIG);
183                         }
184
185                         if (setuid(u->pw_uid) == -1)
186                         {
187                                 ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "setuid(%d) failed (wrong user?): %s", u->pw_uid, strerror(errno));
188                                 exit(EXIT_STATUS_CONFIG);
189                         }
190                 }
191 #endif
192         }
193
194         // Expands a path relative to the current working directory.
195         std::string ExpandPath(const char* path)
196         {
197 #ifdef _WIN32
198                 TCHAR configPath[MAX_PATH + 1];
199                 if (GetFullPathName(path, MAX_PATH, configPath, NULL) > 0)
200                         return configPath;
201 #else
202                 char configPath[PATH_MAX + 1];
203                 if (realpath(path, configPath))
204                         return configPath;
205 #endif
206                 return path;
207         }
208
209         // Locates a config file on the file system.
210         bool FindConfigFile(std::string& path)
211         {
212                 if (FileSystem::FileExists(path))
213                         return true;
214
215 #ifdef _WIN32
216                 // Windows hides file extensions by default so try appending .txt to the path
217                 // to help users who have that feature enabled and can't create .conf files.
218                 const std::string txtpath = path + ".txt";
219                 if (FileSystem::FileExists(txtpath))
220                 {
221                         path.assign(txtpath);
222                         return true;
223                 }
224 #endif
225                 return false;
226         }
227
228         // Attempts to fork into the background.
229         void ForkIntoBackground()
230         {
231 #ifndef _WIN32
232                 // We use VoidSignalHandler whilst forking to avoid breaking daemon scripts
233                 // if the parent process exits with SIGTERM (15) instead of EXIT_STATUS_NOERROR (0).
234                 signal(SIGTERM, VoidSignalHandler);
235
236                 errno = 0;
237                 int childpid = fork();
238                 if (childpid < 0)
239                 {
240                         ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "fork() failed: %s", strerror(errno));
241                         std::cout << con_red << "Error:" << con_reset << " unable to fork into background: " << strerror(errno);
242                         ServerInstance->Exit(EXIT_STATUS_FORK);
243                 }
244                 else if (childpid > 0)
245                 {
246                         // Wait until the child process kills the parent so that the shell prompt
247                         // doesnt display over the output. Sending a kill with a signal of 0 just
248                         // checks that the child pid is still running. If it is not then an error
249                         // happened and the parent should exit.
250                         while (kill(childpid, 0) != -1)
251                                 sleep(1);
252                         exit(EXIT_STATUS_NOERROR);
253                 }
254                 else
255                 {
256                         setsid();
257                         signal(SIGTERM, InspIRCd::SetSignal);
258                         SocketEngine::RecoverFromFork();
259                 }
260 #endif
261         }
262
263         // Increase the size of a core dump file to improve debugging problems.
264         void IncreaseCoreDumpSize()
265         {
266 #ifndef _WIN32
267                 errno = 0;
268                 rlimit rl;
269                 if (getrlimit(RLIMIT_CORE, &rl) == -1)
270                 {
271                         ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "Unable to increase core dump size: getrlimit(RLIMIT_CORE) failed: %s", strerror(errno));
272                         return;
273                 }
274
275                 rl.rlim_cur = rl.rlim_max;
276                 if (setrlimit(RLIMIT_CORE, &rl) == -1)
277                         ServerInstance->Logs->Log("STARTUP", LOG_DEFAULT, "Unable to increase core dump size: setrlimit(RLIMIT_CORE) failed: %s", strerror(errno));
278 #endif
279         }
280
281         // Parses the command line options.
282         void ParseOptions()
283         {
284                 int do_debug = 0, do_nofork = 0,    do_nolog = 0;
285                 int do_nopid = 0, do_runasroot = 0, do_version = 0;
286                 struct option longopts[] =
287                 {
288                         { "config",    required_argument, NULL,          'c' },
289                         { "debug",     no_argument,       &do_debug,     1 },
290                         { "nofork",    no_argument,       &do_nofork,    1 },
291                         { "nolog",     no_argument,       &do_nolog,     1 },
292                         { "nopid",     no_argument,       &do_nopid,     1 },
293                         { "runasroot", no_argument,       &do_runasroot, 1 },
294                         { "version",   no_argument,       &do_version,   1 },
295                         { 0, 0, 0, 0 }
296                 };
297
298                 char** argv = ServerInstance->Config->cmdline.argv;
299                 int ret;
300                 while ((ret = getopt_long(ServerInstance->Config->cmdline.argc, argv, ":c:", longopts, NULL)) != -1)
301                 {
302                         switch (ret)
303                         {
304                                 case 0:
305                                         // A long option was specified.
306                                         break;
307
308                                 case 'c':
309                                         // The -c option was specified.
310                                         ServerInstance->ConfigFileName = ExpandPath(optarg);
311                                         break;
312
313                                 default:
314                                         // An unknown option was specified.
315                                         std::cout << con_red << "Error:" <<  con_reset << " unknown option '" << argv[optind - 1] << "'." << std::endl
316                                                 << con_bright << "Usage: " << con_reset << argv[0] << " [--config <file>] [--debug] [--nofork] [--nolog]" << std::endl
317                                                 << std::string(strlen(argv[0]) + 8, ' ') << "[--nopid] [--runasroot] [--version]" << std::endl;
318                                         ServerInstance->Exit(EXIT_STATUS_ARGV);
319                                         break;
320                         }
321                 }
322
323                 if (do_version)
324                 {
325                         std::cout << std::endl << INSPIRCD_VERSION << std::endl;
326                         ServerInstance->Exit(EXIT_STATUS_NOERROR);
327                 }
328
329                 // Store the relevant parsed arguments
330                 ServerInstance->Config->cmdline.forcedebug = !!do_debug;
331                 ServerInstance->Config->cmdline.nofork = !!do_nofork;
332                 ServerInstance->Config->cmdline.runasroot = !!do_runasroot;
333                 ServerInstance->Config->cmdline.writelog = !do_nolog;
334                 ServerInstance->Config->cmdline.writepid = !do_nopid;
335         }
336         // Seeds the random number generator if applicable.
337         void SeedRng(timespec ts)
338         {
339 #if defined _WIN32
340                 srand(ts.tv_nsec ^ ts.tv_sec);
341 #elif !defined HAS_ARC4RANDOM_BUF
342                 srandom(ts.tv_nsec ^ ts.tv_sec);
343 #endif
344         }
345
346         // Sets handlers for various process signals.
347         void SetSignals()
348         {
349 #ifndef _WIN32
350                 signal(SIGALRM, SIG_IGN);
351                 signal(SIGCHLD, SIG_IGN);
352                 signal(SIGHUP, InspIRCd::SetSignal);
353                 signal(SIGPIPE, SIG_IGN);
354                 signal(SIGUSR1, SIG_IGN);
355                 signal(SIGUSR2, SIG_IGN);
356                 signal(SIGXFSZ, SIG_IGN);
357 #endif
358                 signal(SIGTERM, InspIRCd::SetSignal);
359         }
360
361         void TryBindPorts()
362         {
363                 FailedPortList pl;
364                 ServerInstance->BindPorts(pl);
365
366                 if (!pl.empty())
367                 {
368                         std::cout << con_red << "Warning!" << con_reset << " Some of your listener" << (pl.size() == 1 ? "s" : "") << " failed to bind:" << std::endl
369                                 << std::endl;
370
371                         for (FailedPortList::const_iterator iter = pl.begin(); iter != pl.end(); ++iter)
372                         {
373                                 const FailedPort& fp = *iter;
374                                 std::cout << "  " << con_bright << fp.sa.str() << con_reset << ": " << strerror(fp.error) << '.' << std::endl
375                                         << "  " << "Created from <bind> tag at " << fp.tag->getTagLocation() << std::endl
376                                         << std::endl;
377                         }
378
379                         std::cout << con_bright << "Hints:" << con_reset << std::endl
380                                 << "- For TCP/IP listeners try using a public IP address in <bind:address> instead" << std::endl
381                                 << "  of * of leaving it blank." << std::endl
382                                 << "- For UNIX socket listeners try enabling <bind:rewrite> to replace old sockets." << std::endl;
383                 }
384         }
385
386         // Required for returning the proper value of EXIT_SUCCESS for the parent process.
387         void VoidSignalHandler(int)
388         {
389                 exit(EXIT_STATUS_NOERROR);
390         }
391 }
392
393 void InspIRCd::Cleanup()
394 {
395         // Close all listening sockets
396         for (unsigned int i = 0; i < ports.size(); i++)
397         {
398                 ports[i]->cull();
399                 delete ports[i];
400         }
401         ports.clear();
402
403         // Tell modules that we're shutting down.
404         const std::string quitmsg = "Server shutting down";
405         FOREACH_MOD(OnShutdown, (quitmsg));
406
407         // Disconnect all local users
408         const UserManager::LocalList& list = Users.GetLocalUsers();
409         while (!list.empty())
410                 ServerInstance->Users.QuitUser(list.front(), quitmsg);
411
412         GlobalCulls.Apply();
413         Modules->UnloadAll();
414
415         /* Delete objects dynamically allocated in constructor (destructor would be more appropriate, but we're likely exiting) */
416         /* Must be deleted before modes as it decrements modelines */
417         if (FakeClient)
418         {
419                 delete FakeClient->server;
420                 FakeClient->cull();
421         }
422         DeleteZero(this->FakeClient);
423         DeleteZero(this->XLines);
424         DeleteZero(this->Config);
425         SocketEngine::Deinit();
426         Logs->CloseLogs();
427 }
428
429 void InspIRCd::WritePID(const std::string& filename, bool exitonfail)
430 {
431 #ifndef _WIN32
432         if (!ServerInstance->Config->cmdline.writepid)
433         {
434                 this->Logs->Log("STARTUP", LOG_DEFAULT, "--nopid specified on command line; PID file not written.");
435                 return;
436         }
437
438         std::string fname = ServerInstance->Config->Paths.PrependData(filename.empty() ? "inspircd.pid" : filename);
439         std::ofstream outfile(fname.c_str());
440         if (outfile.is_open())
441         {
442                 outfile << getpid();
443                 outfile.close();
444         }
445         else
446         {
447                 if (exitonfail)
448                         std::cout << "Failed to write PID-file '" << fname << "', exiting." << std::endl;
449                 this->Logs->Log("STARTUP", LOG_DEFAULT, "Failed to write PID-file '%s'%s", fname.c_str(), (exitonfail ? ", exiting." : ""));
450                 if (exitonfail)
451                         Exit(EXIT_STATUS_PID);
452         }
453 #endif
454 }
455
456 InspIRCd::InspIRCd(int argc, char** argv)
457         : FakeClient(NULL)
458         , ConfigFileName(INSPIRCD_CONFIG_PATH "/inspircd.conf")
459         , ConfigThread(NULL)
460         , Config(NULL)
461         , XLines(NULL)
462         , PI(&DefaultProtocolInterface)
463         , GenRandom(&DefaultGenRandom)
464         , IsChannel(&DefaultIsChannel)
465         , IsNick(&DefaultIsNick)
466         , IsIdent(&DefaultIsIdent)
467 {
468         ServerInstance = this;
469
470         UpdateTime();
471         this->startup_time = TIME.tv_sec;
472
473         IncreaseCoreDumpSize();
474         SeedRng(TIME);
475         SocketEngine::Init();
476
477         this->Config = new ServerConfig;
478         dynamic_reference_base::reset_all();
479         this->XLines = new XLineManager;
480
481         this->Config->cmdline.argv = argv;
482         this->Config->cmdline.argc = argc;
483
484 #ifdef _WIN32
485         // Initialize the console values
486         g_hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
487         CONSOLE_SCREEN_BUFFER_INFO bufinf;
488         if(GetConsoleScreenBufferInfo(g_hStdout, &bufinf))
489         {
490                 g_wOriginalColors = bufinf.wAttributes & 0x00FF;
491                 g_wBackgroundColor = bufinf.wAttributes & 0x00F0;
492         }
493         else
494         {
495                 g_wOriginalColors = FOREGROUND_RED|FOREGROUND_BLUE|FOREGROUND_GREEN;
496                 g_wBackgroundColor = 0;
497         }
498 #endif
499
500         {
501                 ServiceProvider* provs[] =
502                 {
503                         &rfcevents.numeric, &rfcevents.join, &rfcevents.part, &rfcevents.kick, &rfcevents.quit, &rfcevents.nick,
504                         &rfcevents.mode, &rfcevents.topic, &rfcevents.privmsg, &rfcevents.invite, &rfcevents.ping, &rfcevents.pong,
505                         &rfcevents.error
506                 };
507                 Modules.AddServices(provs, sizeof(provs)/sizeof(provs[0]));
508         }
509
510         std::cout << con_green << "InspIRCd - Internet Relay Chat Daemon" << con_reset << std::endl
511                 << "See " << con_green << "/INFO" << con_reset << " for contributors & authors" << std::endl
512                 << std::endl;
513
514         ParseOptions();
515         if (Config->cmdline.forcedebug)
516         {
517                 FileWriter* fw = new FileWriter(stdout, 1);
518                 FileLogStream* fls = new FileLogStream(LOG_RAWIO, fw);
519                 Logs->AddLogTypes("*", fls, true);
520         }
521
522         if (!FindConfigFile(ConfigFileName))
523         {
524                 this->Logs->Log("STARTUP", LOG_DEFAULT, "Unable to open config file %s", ConfigFileName.c_str());
525                 std::cout << "ERROR: Cannot open config file: " << ConfigFileName << std::endl << "Exiting..." << std::endl;
526                 Exit(EXIT_STATUS_CONFIG);
527         }
528
529         SetSignals();
530         if (!Config->cmdline.runasroot)
531                 CheckRoot();
532         if (!Config->cmdline.nofork)
533                 ForkIntoBackground();
534
535         std::cout << "InspIRCd Process ID: " << con_green << getpid() << con_reset << std::endl;
536
537         /* During startup we read the configuration now, not in
538          * a seperate thread
539          */
540         this->Config->Read();
541         this->Config->Apply(NULL, "");
542         Logs->OpenFileLogs();
543
544         // If we don't have a SID, generate one based on the server name and the server description
545         if (Config->sid.empty())
546                 Config->sid = UIDGenerator::GenerateSID(Config->ServerName, Config->ServerDesc);
547
548         // Initialize the UID generator with our sid
549         this->UIDGen.init(Config->sid);
550
551         // Create the server user for this server
552         this->FakeClient = new FakeUser(Config->sid, Config->ServerName, Config->ServerDesc);
553
554         // This is needed as all new XLines are marked pending until ApplyLines() is called
555         this->XLines->ApplyLines();
556
557         std::cout << std::endl;
558
559         this->Modules->LoadAll();
560
561         // Build ISupport as ModuleManager::LoadAll() does not do it
562         this->ISupport.Build();
563
564         TryBindPorts();
565
566         std::cout << "InspIRCd is now running as '" << Config->ServerName << "'[" << Config->GetSID() << "] with " << SocketEngine::GetMaxFds() << " max open sockets" << std::endl;
567
568 #ifndef _WIN32
569         if (!Config->cmdline.nofork)
570         {
571                 if (kill(getppid(), SIGTERM) == -1)
572                 {
573                         std::cout << "Error killing parent process: " << strerror(errno) << std::endl;
574                         Logs->Log("STARTUP", LOG_DEFAULT, "Error killing parent process: %s",strerror(errno));
575                 }
576         }
577
578         /* Explicitly shut down stdio's stdin/stdout/stderr.
579          *
580          * The previous logic here was to only do this if stdio was connected to a controlling
581          * terminal.  However, we must do this always to avoid information leaks and other
582          * problems related to stdio.
583          *
584          * The only exception is if we are in debug mode.
585          *
586          *    -- nenolod
587          */
588         if ((!Config->cmdline.nofork) && (!Config->cmdline.forcedebug))
589         {
590                 int fd = open("/dev/null", O_RDWR);
591
592                 fclose(stdin);
593                 fclose(stderr);
594                 fclose(stdout);
595
596                 if (dup2(fd, STDIN_FILENO) < 0)
597                         Logs->Log("STARTUP", LOG_DEFAULT, "Failed to dup /dev/null to stdin.");
598                 if (dup2(fd, STDOUT_FILENO) < 0)
599                         Logs->Log("STARTUP", LOG_DEFAULT, "Failed to dup /dev/null to stdout.");
600                 if (dup2(fd, STDERR_FILENO) < 0)
601                         Logs->Log("STARTUP", LOG_DEFAULT, "Failed to dup /dev/null to stderr.");
602                 close(fd);
603         }
604         else
605         {
606                 Logs->Log("STARTUP", LOG_DEFAULT, "Keeping pseudo-tty open as we are running in the foreground.");
607         }
608 #else
609         /* Set win32 service as running, if we are running as a service */
610         SetServiceRunning();
611
612         // Handle forking
613         if(!Config->cmdline.nofork)
614         {
615                 FreeConsole();
616         }
617
618         QueryPerformanceFrequency(&stats.QPFrequency);
619 #endif
620
621         WritePID(Config->PID);
622         DropRoot();
623
624         Logs->Log("STARTUP", LOG_DEFAULT, "Startup complete as '%s'[%s], %lu max open sockets", Config->ServerName.c_str(),Config->GetSID().c_str(), SocketEngine::GetMaxFds());
625 }
626
627 void InspIRCd::UpdateTime()
628 {
629 #if defined HAS_CLOCK_GETTIME
630         clock_gettime(CLOCK_REALTIME, &TIME);
631 #elif defined _WIN32
632         SYSTEMTIME st;
633         GetSystemTime(&st);
634
635         TIME.tv_sec = time(NULL);
636         TIME.tv_nsec = st.wMilliseconds;
637 #else
638         struct timeval tv;
639         gettimeofday(&tv, NULL);
640
641         TIME.tv_sec = tv.tv_sec;
642         TIME.tv_nsec = tv.tv_usec * 1000;
643 #endif
644 }
645
646 void InspIRCd::Run()
647 {
648         UpdateTime();
649         time_t OLDTIME = TIME.tv_sec;
650
651         while (true)
652         {
653                 /* Check if there is a config thread which has finished executing but has not yet been freed */
654                 if (this->ConfigThread && this->ConfigThread->IsDone())
655                 {
656                         /* Rehash has completed */
657                         this->Logs->Log("CONFIG", LOG_DEBUG, "Detected ConfigThread exiting, tidying up...");
658
659                         this->ConfigThread->Finish();
660
661                         ConfigThread->join();
662                         delete ConfigThread;
663                         ConfigThread = NULL;
664                 }
665
666                 UpdateTime();
667
668                 /* Run background module timers every few seconds
669                  * (the docs say modules shouldnt rely on accurate
670                  * timing using this event, so we dont have to
671                  * time this exactly).
672                  */
673                 if (TIME.tv_sec != OLDTIME)
674                 {
675                         CollectStats();
676
677                         if (Config->TimeSkipWarn)
678                         {
679                                 time_t timediff = TIME.tv_sec - OLDTIME;
680
681                                 if (timediff > Config->TimeSkipWarn)
682                                         SNO->WriteToSnoMask('a', "\002Performance warning!\002 Server clock jumped forwards by %lu seconds!", timediff);
683
684                                 else if (timediff < -Config->TimeSkipWarn)
685                                         SNO->WriteToSnoMask('a', "\002Performance warning!\002 Server clock jumped backwards by %lu seconds!", labs(timediff));
686                         }
687
688                         OLDTIME = TIME.tv_sec;
689
690                         if ((TIME.tv_sec % 3600) == 0)
691                                 FOREACH_MOD(OnGarbageCollect, ());
692
693                         Timers.TickTimers(TIME.tv_sec);
694                         Users->DoBackgroundUserStuff();
695
696                         if ((TIME.tv_sec % 5) == 0)
697                         {
698                                 FOREACH_MOD(OnBackgroundTimer, (TIME.tv_sec));
699                                 SNO->FlushSnotices();
700                         }
701                 }
702
703                 /* Call the socket engine to wait on the active
704                  * file descriptors. The socket engine has everything's
705                  * descriptors in its list... dns, modules, users,
706                  * servers... so its nice and easy, just one call.
707                  * This will cause any read or write events to be
708                  * dispatched to their handlers.
709                  */
710                 SocketEngine::DispatchTrialWrites();
711                 SocketEngine::DispatchEvents();
712
713                 /* if any users were quit, take them out */
714                 GlobalCulls.Apply();
715                 AtomicActions.Run();
716
717                 if (s_signal)
718                 {
719                         this->SignalHandler(s_signal);
720                         s_signal = 0;
721                 }
722         }
723 }
724
725 sig_atomic_t InspIRCd::s_signal = 0;
726
727 void InspIRCd::SetSignal(int signal)
728 {
729         s_signal = signal;
730 }
731
732 /* On posix systems, the flow of the program starts right here, with
733  * ENTRYPOINT being a #define that defines main(). On Windows, ENTRYPOINT
734  * defines smain() and the real main() is in the service code under
735  * win32service.cpp. This allows the service control manager to control
736  * the process where we are running as a windows service.
737  */
738 ENTRYPOINT
739 {
740         new InspIRCd(argc, argv);
741         ServerInstance->Run();
742         delete ServerInstance;
743         return 0;
744 }