]> git.netwichtig.de Git - user/henk/code/inspircd.git/blobdiff - win/inspircd_win32wrapper.cpp
Merge pull request #314 from ChrisTX/insp20+DnsQueryConfig
[user/henk/code/inspircd.git] / win / inspircd_win32wrapper.cpp
index 2aac1da05839358565d46a56b379af81e743c0f4..bdd60d1cc6610251a9ca779dc4ec048f23661105 100644 (file)
@@ -1,22 +1,35 @@
-/*       +------------------------------------+
- *       | Inspire Internet Relay Chat Daemon |
- *       +------------------------------------+
+/*
+ * InspIRCd -- Internet Relay Chat Daemon
  *
- *  InspIRCd: (C) 2002-2009 InspIRCd Development Team
- * See: http://wiki.inspircd.org/Credits
+ *   Copyright (C) 2011 Adam <Adam@anope.org>
+ *   Copyright (C) 2007, 2009 Dennis Friis <peavey@inspircd.org>
+ *   Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org>
+ *   Copyright (C) 2007-2009 Craig Edwards <craigedwards@brainbox.cc>
+ *   Copyright (C) 2008 John Brooks <john.brooks@dereferenced.net>
+ *   Copyright (C) 2007 Burlex <???@???>
+ *   Copyright (C) 2007 Robin Burchell <robin+git@viroteck.net>
  *
- * 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/>.
  */
 
+
 #include "inspircd_win32wrapper.h"
 #include "inspircd.h"
 #include "configreader.h"
 #include <string>
 #include <errno.h>
 #include <assert.h>
+#include <Iphlpapi.h>
 #define _WIN32_DCOM
 #include <comdef.h>
 #include <Wbemidl.h>
@@ -24,6 +37,7 @@
 #pragma comment(lib, "wbemuuid.lib")
 #pragma comment(lib, "comsuppwd.lib")
 #pragma comment(lib, "winmm.lib")
+#pragma comment(lib, "Iphlpapi.lib")
 using namespace std;
 
 #ifndef INADDR_NONE
@@ -46,7 +60,7 @@ int inet_aton(const char *cp, struct in_addr *addr)
        return (addr->s_addr == INADDR_NONE) ? 0 : 1;
 }
 
-const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt)
+const char *insp_inet_ntop(int af, const void *src, char *dst, socklen_t cnt)
 {
 
        if (af == AF_INET)
@@ -75,7 +89,7 @@ int geteuid()
        return 1;
 }
 
-int inet_pton(int af, const char *src, void *dst)
+int insp_inet_pton(int af, const char *src, void *dst)
 {
        sockaddr_in sa;
        int len = sizeof(SOCKADDR);
@@ -236,16 +250,17 @@ int printf_c(const char * format, ...)
        return c;
 }
 
-int arg_counter = 1;
+int optind = 1;
 char optarg[514];
-int getopt_long_only(int ___argc, char *const *___argv, const char *__shortopts, const struct option *__longopts, int *__longind)
+int getopt_long(int ___argc, char *const *___argv, const char *__shortopts, const struct option *__longopts, int *__longind)
 {
        // burlex todo: handle the shortops, at the moment it only works with longopts.
 
-       if (___argc == 1 || arg_counter == ___argc)                     // No arguments (apart from filename)
+       if (___argc == 1 || optind == ___argc)                  // No arguments (apart from filename)
                return -1;
 
-       const char * opt = ___argv[arg_counter];
+       const char * opt = ___argv[optind];
+       optind++;
 
        // if we're not an option, return an error.
        if (strnicmp(opt, "--", 2) != 0)
@@ -262,18 +277,18 @@ int getopt_long_only(int ___argc, char *const *___argv, const char *__shortopts,
                {
                        // woot, found a valid argument =)
                        char * par = 0;
-                       if ((arg_counter + 1) != ___argc)
+                       if ((optind) != ___argc)
                        {
                                // grab the parameter from the next argument (if its not another argument)
-                               if (strnicmp(___argv[arg_counter+1], "--", 2) != 0)
+                               if (strnicmp(___argv[optind], "--", 2) != 0)
                                {
-                                       arg_counter++;          // Trash this next argument, we won't be needing it.
-                                       par = ___argv[arg_counter];
+//                                     optind++;               // Trash this next argument, we won't be needing it.
+                                       par = ___argv[optind-1];
                                }
                        }                       
 
                        // increment the argument for next time
-                       arg_counter++;
+//                     optind++;
 
                        // determine action based on type
                        if (__longopts[i].has_arg == required_argument && !par)
@@ -307,77 +322,6 @@ int getopt_long_only(int ___argc, char *const *___argv, const char *__shortopts,
        return 1;
 }
 
-/* These three functions were created from looking at how ares does it
- * (...and they look far tidier in C++)
- */
-
-/* Get active nameserver */
-bool GetNameServer(HKEY regkey, const char *key, char* &output)
-{
-       DWORD size = 0;
-       DWORD result = RegQueryValueEx(regkey, key, 0, NULL, NULL, &size);
-       if (((result != ERROR_SUCCESS) && (result != ERROR_MORE_DATA)) || (!size))
-               return false;
-
-       output = new char[size+1];
-
-       if ((RegQueryValueEx(regkey, key, 0, NULL, (LPBYTE)output, &size) != ERROR_SUCCESS) || (!*output))
-       {
-               delete output;
-               return false;
-       }
-       return true;
-}
-
-/* Check a network interface for its nameserver */
-bool GetInterface(HKEY regkey, const char *key, char* &output)
-{
-       char buf[39];
-       DWORD size = 39;
-       int idx = 0;
-       HKEY top;
-
-       while (RegEnumKeyEx(regkey, idx++, buf, &size, 0, NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
-       {
-               size = 39;
-               if (RegOpenKeyEx(regkey, buf, 0, KEY_QUERY_VALUE, &top) != ERROR_SUCCESS)
-                       continue;
-               int rc = GetNameServer(top, key, output);
-               RegCloseKey(top);
-               if (rc)
-                       return true;
-       }
-       return false;
-}
-
-
-std::string FindNameServerWin()
-{
-       std::string returnval = "127.0.0.1";
-       HKEY top, key;
-       char* dns = NULL;
-
-       /* Lets see if the correct registry hive and tree exist */
-       if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\Tcpip\\Parameters", 0, KEY_READ, &top) == ERROR_SUCCESS)
-       {
-               /* If they do, attempt to get the nameserver name */
-               RegOpenKeyEx(top, "Interfaces", 0, KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &key);
-               if ((GetNameServer(top, "NameServer", dns)) || (GetNameServer(top, "DhcpNameServer", dns))
-                       || (GetInterface(key, "NameServer", dns)) || (GetInterface(key, "DhcpNameServer", dns)))
-               {
-                       if (dns)
-                       {
-                               returnval = dns;
-                               delete dns;
-                       }
-               }
-               RegCloseKey(key);
-               RegCloseKey(top);
-       }
-       return returnval;
-}
-
-
 void ClearConsole()
 {
        COORD coordScreen = { 0, 0 };    /* here's where we'll home the cursor */
@@ -412,13 +356,12 @@ void ClearConsole()
 /* Many inspircd classes contain function pointers/functors which can be changed to point at platform specific implementations
  * of code. This function repoints these pointers and functors so that calls are windows specific.
  */
-void ChangeWindowsSpecificPointers(InspIRCd* Instance)
+void ChangeWindowsSpecificPointers()
 {
-       Instance->Logs->Log("win32",DEBUG,"Changing to windows specific pointer and functor set");
-       Instance->Config->DNSServerValidator = &ValidateWindowsDnsServer;
+       ServerInstance->Logs->Log("win32",DEBUG,"Changing to windows specific pointer and functor set");
 }
 
-DWORD WindowsForkStart(InspIRCd* Instance)
+DWORD WindowsForkStart()
 {
         /* Windows implementation of fork() :P */
        if (owner_processid)
@@ -498,56 +441,69 @@ DWORD WindowsForkStart(InspIRCd* Instance)
         return ExitCode;
 }
 
-void WindowsForkKillOwner(InspIRCd * Instance)
+void WindowsForkKillOwner()
 {
         HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, owner_processid);
         if(!hProcess || !owner_processid)
         {
                 printf("Could not open process id %u: %s.\n", owner_processid, dlerror());
-                Instance->Exit(14);
+                ServerInstance->Exit(14);
         }
 
         // die die die
         if(!TerminateProcess(hProcess, 0))
         {
                 printf("Could not TerminateProcess(): %s\n", dlerror());
-                Instance->Exit(14);
+                ServerInstance->Exit(14);
         }
 
         CloseHandle(hProcess);
 }
 
-bool ValidateWindowsDnsServer(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
+void FindDNS(std::string& server)
 {
-       if (!*(data.GetString()))
+       if (!server.empty())
+               return;
+
+       PFIXED_INFO pFixedInfo;
+       DWORD dwBufferSize = sizeof(FIXED_INFO);
+       pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, sizeof(FIXED_INFO));
+
+       if(pFixedInfo)
+       {
+               if (GetNetworkParams(pFixedInfo, &dwBufferSize) == ERROR_BUFFER_OVERFLOW) {
+                       HeapFree(GetProcessHeap(), 0, pFixedInfo);
+                       pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, dwBufferSize);
+               }
+
+               if(pFixedInfo) {
+                       if (GetNetworkParams(pFixedInfo, &dwBufferSize) == NO_ERROR)
+                               server = pFixedInfo->DnsServerList.IpAddress.String;
+
+                       HeapFree(GetProcessHeap(), 0, pFixedInfo);
+               }
+       }
+       
+       /* If empty use default to 127.0.0.1 */
+       if(server.empty())
        {
-               std::string nameserver;
-               conf->GetInstance()->Logs->Log("win32",DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in the registry...");
-               nameserver = FindNameServerWin();
-               /* Windows stacks multiple nameservers in one registry key, seperated by commas.
-                * Spotted by Cataclysm.
-                */
-               if (nameserver.find(',') != std::string::npos)
-                       nameserver = nameserver.substr(0, nameserver.find(','));
-               /* Just to be FUCKING AKWARD, windows fister... err i mean vista...
-                * seperates the nameservers with spaces instead.
-                */
-               if (nameserver.find(' ') != std::string::npos)
-                       nameserver = nameserver.substr(0, nameserver.find(' '));
-               data.Set(nameserver.c_str());
-               conf->GetInstance()->Logs->Log("win32",DEFAULT,"<dns:server> set to '%s' as first active resolver in registry.", nameserver.c_str());
+               ServerInstance->Logs->Log("CONFIG",DEFAULT,"No viable nameserver found! Defaulting to nameserver '127.0.0.1'!");
+               server = "127.0.0.1";
+       }
+       else
+       {
+               ServerInstance->Logs->Log("CONFIG",DEFAULT,"<dns:server> set to '%s' as first active resolver.", server.c_str());
        }
-       return true;
 }
 
-int gettimeofday(struct timeval * tv, void * tz)
+int clock_gettime(int clock, struct timespec * tv)
 {
        if(tv == NULL)
                return -1;
 
        DWORD mstime = timeGetTime();
        tv->tv_sec   = time(NULL);
-       tv->tv_usec  = (mstime - (tv->tv_sec * 1000)) * 1000;
+       tv->tv_nsec  = (mstime - (tv->tv_sec * 1000)) * 1000000;
        return 0;       
 }
 
@@ -623,66 +579,96 @@ void donewmi()
 int getcpu()
 {
        HRESULT hres;
+       int cpu = -1;
 
        /* Use WQL, similar to SQL, to construct a query that lists the cpu usage and pid of all processes */
        IEnumWbemClassObject* pEnumerator = NULL;
-       hres = pSvc->ExecQuery(L"WQL", L"Select PercentProcessorTime,IDProcess from Win32_PerfFormattedData_PerfProc_Process",
-               WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
-    
-       /* Query didn't work */
-       if (FAILED(hres))
-               return -1;
 
-       IWbemClassObject *pclsObj = NULL;
-       ULONG uReturn = 0;
-   
-       /* Iterate the query results */
-       while (pEnumerator)
-       {
-               VARIANT vtProp;
-               /* Next item */
-               HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
+       BSTR Language = SysAllocString(L"WQL");
+       BSTR Query    = SysAllocString(L"Select PercentProcessorTime,IDProcess from Win32_PerfFormattedData_PerfProc_Process");
 
-               /* No more items left */
-               if (uReturn == 0)
-                       break;
+       hres = pSvc->ExecQuery(Language, Query, WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
+
+       /* Query didn't work */
+       if (!FAILED(hres))
+       {
+               IWbemClassObject *pclsObj = NULL;
+               ULONG uReturn = 0;
 
-               /* Find process ID */
-               hr = pclsObj->Get(L"IDProcess", 0, &vtProp, 0, 0);
-               if (!FAILED(hr))
+               /* Iterate the query results */
+               while (pEnumerator)
                {
-                       /* Matches our process ID? */
-                       if (vtProp.uintVal == GetCurrentProcessId())
+                       VARIANT vtProp;
+                       VariantInit(&vtProp);
+                       /* Next item */
+                       HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
+
+                       /* No more items left */
+                       if (uReturn == 0)
+                               break;
+
+                       /* Find process ID */
+                       hr = pclsObj->Get(L"IDProcess", 0, &vtProp, 0, 0);
+                       if (!FAILED(hr))
                        {
+                               /* Matches our process ID? */
+                               UINT pid = vtProp.uintVal;
                                VariantClear(&vtProp);
-                               /* Get CPU percentage for this process */
-                               hr = pclsObj->Get(L"PercentProcessorTime", 0, &vtProp, 0, 0);
-                               if (!FAILED(hr))
-                               {
-                                       /* Deal with wide string ickyness. Who in their right
-                                        * mind puts a number in a bstrVal wide string item?!
-                                        */
-                                       VariantClear(&vtProp);
-                                       int cpu = 0;
-                                       std::wstringstream out(vtProp.bstrVal);
-                                       out >> cpu;
-                                       pEnumerator->Release();
+                               if (pid == GetCurrentProcessId())
+                               {                                       
+                                       /* Get CPU percentage for this process */
+                                       hr = pclsObj->Get(L"PercentProcessorTime", 0, &vtProp, 0, 0);
+                                       if (!FAILED(hr))
+                                       {
+                                               /* Deal with wide string ickyness. Who in their right
+                                                * mind puts a number in a bstrVal wide string item?!
+                                                */
+                                               cpu = 0;
+                                               std::wstringstream out(vtProp.bstrVal);
+                                               out >> cpu;
+                                               VariantClear(&vtProp);
+                                       }
                                        pclsObj->Release();
-                                       return cpu;
+                                       break;
                                }
+                               pclsObj->Release();
                        }
                }
+
+               pEnumerator->Release();
        }
-       pEnumerator->Release();
-       pclsObj->Release();
-       return -1;
+
+       SysFreeString(Language);
+       SysFreeString(Query);
+
+       return cpu;
 }
 
-void usleep(unsigned long usecs)
+int random()
 {
-       if (usecs > 0UL)
-       {
-               unsigned long millis = ((usecs + 999UL) / 1000UL);
-               SleepEx(millis, false);
-       }
+       return rand();
 }
+
+void srandom(unsigned int seed)
+{
+       srand(seed);
+}
+
+int gettimeofday(timeval *tv, void *)
+{
+       SYSTEMTIME st;
+       GetSystemTime(&st);
+
+       tv->tv_sec = time(NULL);
+       tv->tv_usec = st.wMilliseconds;
+
+       return 0;
+}
+
+/* World's largest hack to make reference<> work */
+#include "../src/modules/m_spanningtree/link.h"
+#include "../src/modules/ssl.h"
+template class reference<Link>;
+template class reference<Autoconnect>;
+template class reference<ssl_cert>;
+template class reference<OperInfo>;