]> git.netwichtig.de Git - user/henk/code/inspircd.git/blobdiff - src/inspircd.cpp
Windows: In-depth cleanup (see details)
[user/henk/code/inspircd.git] / src / inspircd.cpp
index 2ac844bb6abfa625705b493c6ff4bb4d02b2fb2a..42047ce1111a59b81d26dc8f1d1618a2f614f5b5 100644 (file)
@@ -1,22 +1,37 @@
-/*       +------------------------------------+
- *       | Inspire Internet Relay Chat Daemon |
- *       +------------------------------------+
+/*
+ * InspIRCd -- Internet Relay Chat Daemon
  *
- *  InspIRCd: (C) 2002-2010 InspIRCd Development Team
- * See: http://wiki.inspircd.org/Credits
+ *   Copyright (C) 2012 William Pitcock <nenolod@dereferenced.org>
+ *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
+ *   Copyright (C) 2003-2008 Craig Edwards <craigedwards@brainbox.cc>
+ *   Copyright (C) 2008 Uli Schlachter <psychon@znc.in>
+ *   Copyright (C) 2006-2008 Robin Burchell <robin+git@viroteck.net>
+ *   Copyright (C) 2006-2007 Oliver Lupton <oliverlupton@gmail.com>
+ *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
+ *   Copyright (C) 2007 Burlex <???@???>
+ *   Copyright (C) 2003 Craig McLure <craig@chatspike.net>
+ *   Copyright (C) 2003 randomdan <???@???>
  *
- * This program is free but copyrighted software; see
- *         the file COPYING for details.
+ * This file is part of InspIRCd.  InspIRCd is free software: you can
+ * redistribute it and/or modify it under the terms of the GNU General Public
+ * License as published by the Free Software Foundation, version 2.
  *
- * ---------------------------------------------------
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  */
 
+
 /* $Core */
 #include "inspircd.h"
 #include "inspircd_version.h"
 #include <signal.h>
 
-#ifndef WIN32
+#ifndef _WIN32
        #include <dirent.h>
        #include <unistd.h>
        #include <sys/resource.h>
@@ -148,9 +163,9 @@ void InspIRCd::Restart(const std::string &reason)
 
        char** argv = Config->cmdline.argv;
 
-#ifdef WINDOWS
+#ifdef _WIN32
        char module[MAX_PATH];
-       if (GetModuleFileName(NULL, module, MAX_PATH))
+       if (GetModuleFileNameA(NULL, module, MAX_PATH))
                me = module;
 #else
        me = argv[0];
@@ -180,24 +195,21 @@ void InspIRCd::ResetMaxBans()
 void InspIRCd::RehashUsersAndChans()
 {
        user_hash* old_users = Users->clientlist;
-       user_hash* old_uuid  = Users->uuidlist;
-       chan_hash* old_chans = chanlist;
-
-       Users->clientlist = new user_hash();
-       Users->uuidlist = new user_hash();
-       chanlist = new chan_hash();
-
+       Users->clientlist = new user_hash;
        for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
                Users->clientlist->insert(*n);
+       delete old_users;
 
+       user_hash* old_uuid = Users->uuidlist;
+       Users->uuidlist = new user_hash;
        for (user_hash::const_iterator n = old_uuid->begin(); n != old_uuid->end(); n++)
                Users->uuidlist->insert(*n);
+       delete old_uuid;
 
+       chan_hash* old_chans = chanlist;
+       chanlist = new chan_hash;
        for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
                chanlist->insert(*n);
-
-       delete old_users;
-       delete old_uuid;
        delete old_chans;
 
        // Reset the already_sent IDs so we don't wrap it around and drop a message
@@ -205,12 +217,13 @@ void InspIRCd::RehashUsersAndChans()
        for (std::vector<LocalUser*>::const_iterator i = Users->local_users.begin(); i != Users->local_users.end(); i++)
        {
                (**i).already_sent = 0;
+               (**i).RemoveExpiredInvites();
        }
 }
 
 void InspIRCd::SetSignals()
 {
-#ifndef WIN32
+#ifndef _WIN32
        signal(SIGALRM, SIG_IGN);
        signal(SIGHUP, InspIRCd::SetSignal);
        signal(SIGPIPE, SIG_IGN);
@@ -228,7 +241,7 @@ void InspIRCd::QuickExit(int status)
 
 bool InspIRCd::DaemonSeed()
 {
-#ifdef WINDOWS
+#ifdef _WIN32
        printf_c("InspIRCd Process ID: \033[1;32m%lu\033[0m\n", GetCurrentProcessId());
        return true;
 #else
@@ -272,9 +285,10 @@ bool InspIRCd::DaemonSeed()
 
 void InspIRCd::WritePID(const std::string &filename)
 {
+#ifndef _WIN32
        std::string fname(filename);
        if (fname.empty())
-               fname = "data/inspircd.pid";
+               fname = DATA_PATH "/inspircd.pid";
        std::ofstream outfile(fname.c_str());
        if (outfile.is_open())
        {
@@ -287,10 +301,11 @@ void InspIRCd::WritePID(const std::string &filename)
                this->Logs->Log("STARTUP",DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
                Exit(EXIT_STATUS_PID);
        }
+#endif
 }
 
 InspIRCd::InspIRCd(int argc, char** argv) :
-        ConfigFileName("conf/inspircd.conf"),
+        ConfigFileName(CONFIG_PATH "/inspircd.conf"),
 
         /* Functor pointer initialisation.
          *
@@ -308,14 +323,6 @@ InspIRCd::InspIRCd(int argc, char** argv) :
         FloodQuitUser(&HandleFloodQuitUser),
         OnCheckExemption(&HandleOnCheckExemption)
 {
-#ifdef WIN32
-       // Strict, frequent checking of memory on debug builds
-       _CrtSetDbgFlag ( _CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
-
-       // Avoid erroneous frees on early exit
-       WindowsIPC = 0;
-#endif
-
        ServerInstance = this;
 
        Extensions.Register(&NICKForced);
@@ -380,7 +387,11 @@ InspIRCd::InspIRCd(int argc, char** argv) :
        this->Config->cmdline.argv = argv;
        this->Config->cmdline.argc = argc;
 
+#ifdef _WIN32
+       srand(TIME.tv_nsec ^ TIME.tv_sec);
+#else
        srandom(TIME.tv_nsec ^ TIME.tv_sec);
+#endif
 
        struct option longopts[] =
        {
@@ -431,27 +442,17 @@ InspIRCd::InspIRCd(int argc, char** argv) :
                Exit(EXIT_STATUS_NOERROR);
        }
 
-#ifdef WIN32
-
-       // Handle forking
-       if(!do_nofork)
-       {
-               DWORD ExitCode = WindowsForkStart();
-               if(ExitCode)
-                       exit(ExitCode);
-       }
-
+#ifdef _WIN32
        // Set up winsock
        WSADATA wsadata;
-       WSAStartup(MAKEWORD(2,0), &wsadata);
-       ChangeWindowsSpecificPointers();
+       WSAStartup(MAKEWORD(2,2), &wsadata);
 #endif
 
        /* Set the finished argument values */
-       Config->cmdline.nofork = do_nofork;
-       Config->cmdline.forcedebug = do_debug;
-       Config->cmdline.writelog = !do_nolog;
-       Config->cmdline.TestSuite = do_testsuite;
+       Config->cmdline.nofork = (do_nofork != 0);
+       Config->cmdline.forcedebug = (do_debug != 0);
+       Config->cmdline.writelog = (!do_nolog != 0);
+       Config->cmdline.TestSuite = (do_testsuite != 0);
 
        if (do_debug)
        {
@@ -467,7 +468,7 @@ InspIRCd::InspIRCd(int argc, char** argv) :
 
        if (!ServerConfig::FileExists(ConfigFileName.c_str()))
        {
-#ifdef WIN32
+#ifdef _WIN32
                /* Windows can (and defaults to) hide file extensions, so let's play a bit nice for windows users. */
                std::string txtconf = this->ConfigFileName;
                txtconf.append(".txt");
@@ -488,12 +489,13 @@ InspIRCd::InspIRCd(int argc, char** argv) :
        printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
        printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
        printf_c("Developers:\n");
-       printf_c("\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special\n");
-       printf_c("\t\033[1;32mpeavey, aquanight, psychon, dz, danieldg\033[0m\n\n");
+       printf_c("\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special, peavey\n");
+       printf_c("\t\033[1;32maquanight, psychon, dz, danieldg, jackmcbarn\033[0m\n\n");
        printf_c("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
 
        this->Modes = new ModeParser;
 
+#ifndef _WIN32
        if (!do_root)
                this->CheckRoot();
        else
@@ -508,6 +510,7 @@ InspIRCd::InspIRCd(int argc, char** argv) :
                printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
                sleep(20);
        }
+#endif
 
        this->SetSignals();
 
@@ -585,7 +588,7 @@ InspIRCd::InspIRCd(int argc, char** argv) :
        printf("\nInspIRCd is now running as '%s'[%s] with %d max open sockets\n",
                Config->ServerName.c_str(),Config->GetSID().c_str(), SE->GetMaxFds());
 
-#ifndef WINDOWS
+#ifndef _WIN32
        if (!Config->cmdline.nofork)
        {
                if (kill(getppid(), SIGTERM) == -1)
@@ -595,38 +598,53 @@ InspIRCd::InspIRCd(int argc, char** argv) :
                }
        }
 
-       if (isatty(0) && isatty(1) && isatty(2))
+       /* Explicitly shut down stdio's stdin/stdout/stderr.
+        *
+        * The previous logic here was to only do this if stdio was connected to a controlling
+        * terminal.  However, we must do this always to avoid information leaks and other
+        * problems related to stdio.
+        *
+        * The only exception is if we are in debug mode.
+        *
+        *    -- nenolod
+        */
+       if ((!do_nofork) && (!do_testsuite) && (!Config->cmdline.forcedebug))
        {
-               /* We didn't start from a TTY, we must have started from a background process -
-                * e.g. we are restarting, or being launched by cron. Dont kill parent, and dont
-                * close stdin/stdout
-                */
-               if ((!do_nofork) && (!do_testsuite))
-               {
-                       fclose(stdin);
-                       fclose(stderr);
-                       if (!Config->cmdline.forcedebug)
-                               fclose(stdout);
-               }
-               else
-               {
-                       Logs->Log("STARTUP", DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
-               }
+               int fd;
+
+               fclose(stdin);
+               fclose(stderr);
+               fclose(stdout);
+
+               fd = open("/dev/null", O_RDWR);
+               if (dup2(fd, 0) < 0)
+                       Logs->Log("STARTUP", DEFAULT, "Failed to dup /dev/null to stdin.");
+               if (dup2(fd, 1) < 0)
+                       Logs->Log("STARTUP", DEFAULT, "Failed to dup /dev/null to stdout.");
+               if (dup2(fd, 2) < 0)
+                       Logs->Log("STARTUP", DEFAULT, "Failed to dup /dev/null to stderr.");
+               close(fd);
        }
-#else
-       WindowsIPC = new IPC;
-       if(!Config->cmdline.nofork)
+       else
        {
-               WindowsForkKillOwner();
-               FreeConsole();
+               Logs->Log("STARTUP", DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
        }
+#else
        /* Set win32 service as running, if we are running as a service */
        SetServiceRunning();
+
+       // Handle forking
+       if(!do_nofork)
+       {
+               FreeConsole();
+       }
+
+       QueryPerformanceFrequency(&stats->QPFrequency);
 #endif
 
        Logs->Log("STARTUP", DEFAULT, "Startup complete as '%s'[%s], %d max open sockets", Config->ServerName.c_str(),Config->GetSID().c_str(), SE->GetMaxFds());
 
-#ifndef WIN32
+#ifndef _WIN32
        std::string SetUser = Config->ConfValue("security")->getString("runasuser");
        std::string SetGroup = Config->ConfValue("security")->getString("runasgroup");
        if (!SetGroup.empty())
@@ -685,20 +703,28 @@ InspIRCd::InspIRCd(int argc, char** argv) :
                        this->QuickExit(0);
                }
        }
-#endif
 
        this->WritePID(Config->PID);
+#endif
 }
 
 void InspIRCd::UpdateTime()
 {
-#ifdef HAS_CLOCK_GETTIME
-       clock_gettime(CLOCK_REALTIME, &TIME);
+#ifdef _WIN32
+       SYSTEMTIME st;
+       GetSystemTime(&st);
+
+       TIME.tv_sec = time(NULL);
+       TIME.tv_nsec = st.wMilliseconds;
 #else
-       struct timeval tv;
-       gettimeofday(&tv, NULL);
-       TIME.tv_sec = tv.tv_sec;
-       TIME.tv_nsec = tv.tv_usec * 1000;
+       #ifdef HAS_CLOCK_GETTIME
+               clock_gettime(CLOCK_REALTIME, &TIME);
+       #else
+               struct timeval tv;
+               gettimeofday(&tv, NULL);
+               TIME.tv_sec = tv.tv_sec;
+               TIME.tv_nsec = tv.tv_usec * 1000;
+       #endif
 #endif
 }
 
@@ -717,12 +743,8 @@ int InspIRCd::Run()
 
        while (true)
        {
-#ifndef WIN32
+#ifndef _WIN32
                static rusage ru;
-#else
-               static time_t uptime;
-               static struct tm * stime;
-               static char window_title[100];
 #endif
 
                /* Check if there is a config thread which has finished executing but has not yet been freed */
@@ -748,12 +770,21 @@ int InspIRCd::Run()
                if (TIME.tv_sec != OLDTIME)
                {
                        OLDTIME = TIME.tv_sec;
-#ifndef WIN32
+#ifndef _WIN32
                        getrusage(RUSAGE_SELF, &ru);
                        stats->LastSampled = TIME;
                        stats->LastCPU = ru.ru_utime;
 #else
-                       WindowsIPC->Check();
+                       if(QueryPerformanceCounter(&stats->LastSampled))
+                       {
+                               FILETIME CreationTime;
+                       FILETIME ExitTime;
+                       FILETIME KernelTime;
+                       FILETIME UserTime;
+                               GetProcessTimes(GetCurrentProcess(), &CreationTime, &ExitTime, &KernelTime, &UserTime);
+                               stats->LastCPU.dwHighDateTime = KernelTime.dwHighDateTime + UserTime.dwHighDateTime;
+                               stats->LastCPU.dwLowDateTime = KernelTime.dwLowDateTime + UserTime.dwLowDateTime;
+                       }
 #endif
 
                        /* Allow a buffer of two seconds drift on this so that ntpdate etc dont harass admins */