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