2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2011 Adam <Adam@anope.org>
5 * Copyright (C) 2007, 2009 Dennis Friis <peavey@inspircd.org>
6 * Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org>
7 * Copyright (C) 2007-2009 Craig Edwards <craigedwards@brainbox.cc>
8 * Copyright (C) 2008 John Brooks <john.brooks@dereferenced.net>
9 * Copyright (C) 2007 Burlex <???@???>
10 * Copyright (C) 2007 Robin Burchell <robin+git@viroteck.net>
12 * This file is part of InspIRCd. InspIRCd is free software: you can
13 * redistribute it and/or modify it under the terms of the GNU General Public
14 * License as published by the Free Software Foundation, version 2.
16 * This program is distributed in the hope that it will be useful, but WITHOUT
17 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
18 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
26 #include "inspircd_win32wrapper.h"
28 #include "configreader.h"
36 #pragma comment(lib, "wbemuuid.lib")
37 #pragma comment(lib, "comsuppwd.lib")
38 #pragma comment(lib, "winmm.lib")
42 #define INADDR_NONE 0xffffffff
47 IWbemLocator *pLoc = NULL;
48 IWbemServices *pSvc = NULL;
50 /* This MUST remain static and delcared outside the class, so that WriteProcessMemory can reference it properly */
51 static DWORD owner_processid = 0;
54 int inet_aton(const char *cp, struct in_addr *addr)
56 unsigned long ip = inet_addr(cp);
58 return (addr->s_addr == INADDR_NONE) ? 0 : 1;
61 const char *insp_inet_ntop(int af, const void *src, char *dst, socklen_t cnt)
66 struct sockaddr_in in;
67 memset(&in, 0, sizeof(in));
68 in.sin_family = AF_INET;
69 memcpy(&in.sin_addr, src, sizeof(struct in_addr));
70 getnameinfo((struct sockaddr *)&in, sizeof(struct sockaddr_in), dst, cnt, NULL, 0, NI_NUMERICHOST);
73 else if (af == AF_INET6)
75 struct sockaddr_in6 in;
76 memset(&in, 0, sizeof(in));
77 in.sin6_family = AF_INET6;
78 memcpy(&in.sin6_addr, src, sizeof(struct in_addr6));
79 getnameinfo((struct sockaddr *)&in, sizeof(struct sockaddr_in6), dst, cnt, NULL, 0, NI_NUMERICHOST);
90 int insp_inet_pton(int af, const char *src, void *dst)
93 int len = sizeof(SOCKADDR);
94 int rv = WSAStringToAddress((LPSTR)src, af, NULL, (LPSOCKADDR)&sa, &len);
97 if(WSAGetLastError() == 10022) // Invalid Argument
102 memcpy(dst, &sa.sin_addr, sizeof(struct in_addr));
106 void setcolor(int color_code)
108 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color_code);
111 DIR * opendir(const char * path)
113 std::string search_path = string(path) + "\\*.*";
115 HANDLE f = FindFirstFile(search_path.c_str(), &fd);
116 if (f != INVALID_HANDLE_VALUE)
119 memcpy(&d->find_data, &fd, sizeof(WIN32_FIND_DATA));
130 dirent * readdir(DIR * handle)
133 handle->first = false;
136 if (!FindNextFile(handle->find_handle, &handle->find_data))
140 strncpy(handle->dirent_pointer.d_name, handle->find_data.cFileName, MAX_PATH);
141 return &handle->dirent_pointer;
144 void closedir(DIR * handle)
146 FindClose(handle->find_handle);
150 const char * dlerror()
152 static char errormessage[500];
153 DWORD error = GetLastError();
158 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)errormessage, 500, 0);
162 #define TRED FOREGROUND_RED | FOREGROUND_INTENSITY
163 #define TGREEN FOREGROUND_GREEN | FOREGROUND_INTENSITY
164 #define TYELLOW FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY
165 #define TNORMAL FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE
166 #define TWHITE TNORMAL | FOREGROUND_INTENSITY
167 #define TBLUE FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY
169 /* Handles colors in printf */
170 int printf_c(const char * format, ...)
172 // Better hope we're not multithreaded, otherwise we'll have chickens crossing the road other side to get the to :P
173 static char message[MAXBUF];
174 static char temp[MAXBUF];
177 /* parse arguments */
179 va_start(ap, format);
180 vsnprintf(message, 500, format, ap);
183 /* search for unix-style escape sequences */
186 const char * p = message;
191 // Escape sequence -> copy into the temp buffer, and parse the color.
194 while ((*p) && (*p != 'm'))
205 if (sscanf(temp, "[%u;%u", &color1, &color2) == 2)
210 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN | FOREGROUND_INTENSITY); // Yellow
215 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
224 // Returning to normal colour.
225 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
230 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), TWHITE);
235 sprintf(message, "Unknown color code: %s", temp);
236 MessageBox(0, message, message, MB_OK);
253 int getopt_long(int ___argc, char *const *___argv, const char *__shortopts, const struct option *__longopts, int *__longind)
255 // burlex todo: handle the shortops, at the moment it only works with longopts.
257 if (___argc == 1 || optind == ___argc) // No arguments (apart from filename)
260 const char * opt = ___argv[optind];
263 // if we're not an option, return an error.
264 if (strnicmp(opt, "--", 2) != 0)
270 // parse argument list
272 for (; __longopts[i].name != 0; ++i)
274 if (!strnicmp(__longopts[i].name, opt, strlen(__longopts[i].name)))
276 // woot, found a valid argument =)
278 if ((optind) != ___argc)
280 // grab the parameter from the next argument (if its not another argument)
281 if (strnicmp(___argv[optind], "--", 2) != 0)
283 // optind++; // Trash this next argument, we won't be needing it.
284 par = ___argv[optind-1];
288 // increment the argument for next time
291 // determine action based on type
292 if (__longopts[i].has_arg == required_argument && !par)
294 // parameter missing and its a required parameter option
298 // store argument in optarg
300 strncpy(optarg, par, 514);
302 if (__longopts[i].flag != 0)
304 // this is a variable, we have to set it if this argument is found.
305 *__longopts[i].flag = 1;
310 if (__longopts[i].val == -1 || par == 0)
313 return __longopts[i].val;
319 // return 1 (invalid argument)
323 /* These three functions were created from looking at how ares does it
324 * (...and they look far tidier in C++)
327 /* Get active nameserver */
328 bool GetNameServer(HKEY regkey, const char *key, char* &output)
331 DWORD result = RegQueryValueEx(regkey, key, 0, NULL, NULL, &size);
332 if (((result != ERROR_SUCCESS) && (result != ERROR_MORE_DATA)) || (!size))
335 output = new char[size+1];
337 if ((RegQueryValueEx(regkey, key, 0, NULL, (LPBYTE)output, &size) != ERROR_SUCCESS) || (!*output))
345 /* Check a network interface for its nameserver */
346 bool GetInterface(HKEY regkey, const char *key, char* &output)
353 while (RegEnumKeyEx(regkey, idx++, buf, &size, 0, NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
356 if (RegOpenKeyEx(regkey, buf, 0, KEY_QUERY_VALUE, &top) != ERROR_SUCCESS)
358 int rc = GetNameServer(top, key, output);
367 std::string FindNameServerWin()
369 std::string returnval;
373 /* Lets see if the correct registry hive and tree exist */
374 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\Tcpip\\Parameters", 0, KEY_READ, &top) == ERROR_SUCCESS)
376 /* If they do, attempt to get the nameserver name */
377 RegOpenKeyEx(top, "Interfaces", 0, KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &key);
378 if ((GetNameServer(top, "NameServer", dns)) || (GetNameServer(top, "DhcpNameServer", dns))
379 || (GetInterface(key, "NameServer", dns)) || (GetInterface(key, "DhcpNameServer", dns)))
396 COORD coordScreen = { 0, 0 }; /* here's where we'll home the cursor */
397 HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
399 CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */
400 DWORD dwConSize; /* number of character cells in the current buffer */
402 /* get the number of character cells in the current buffer */
404 if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
406 dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
407 /* fill the entire screen with blanks */
408 if (FillConsoleOutputCharacter( hConsole, (TCHAR) ' ', dwConSize, coordScreen, &cCharsWritten ))
410 /* get the current text attribute */
411 if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
413 /* now set the buffer's attributes accordingly */
414 if (FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten ))
416 /* put the cursor at (0, 0) */
417 SetConsoleCursorPosition( hConsole, coordScreen );
425 /* Many inspircd classes contain function pointers/functors which can be changed to point at platform specific implementations
426 * of code. This function repoints these pointers and functors so that calls are windows specific.
428 void ChangeWindowsSpecificPointers()
430 ServerInstance->Logs->Log("win32",DEBUG,"Changing to windows specific pointer and functor set");
433 DWORD WindowsForkStart()
435 /* Windows implementation of fork() :P */
439 char module[MAX_PATH];
440 if(!GetModuleFileName(NULL, module, MAX_PATH))
442 printf("GetModuleFileName() failed.\n");
446 STARTUPINFO startupinfo;
447 PROCESS_INFORMATION procinfo;
448 ZeroMemory(&startupinfo, sizeof(STARTUPINFO));
449 ZeroMemory(&procinfo, sizeof(PROCESS_INFORMATION));
451 // Fill in the startup info struct
452 GetStartupInfo(&startupinfo);
454 /* Default creation flags create the processes suspended */
455 DWORD startupflags = CREATE_SUSPENDED;
457 /* On windows 2003/XP and above, we can use the value
458 * CREATE_PRESERVE_CODE_AUTHZ_LEVEL which gives more access
459 * to the process which we may require on these operating systems.
462 vi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
464 if ((vi.dwMajorVersion >= 5) && (vi.dwMinorVersion > 0))
465 startupflags |= CREATE_PRESERVE_CODE_AUTHZ_LEVEL;
467 // Launch our "forked" process.
468 BOOL bSuccess = CreateProcess ( module, // Module (exe) filename
469 strdup(GetCommandLine()), // Command line (exe plus parameters from the OS)
470 // NOTE: We cannot return the direct value of the
471 // GetCommandLine function here, as the pointer is
472 // passed straight to the child process, and will be
473 // invalid once we exit as it goes out of context.
474 // strdup() seems ok, though.
475 0, // PROCESS_SECURITY_ATTRIBUTES
476 0, // THREAD_SECURITY_ATTRIBUTES
477 TRUE, // We went to inherit handles.
478 startupflags, // Allow us full access to the process and suspend it.
480 0, // CURRENT_DIRECTORY
481 &startupinfo, // startup info
482 &procinfo); // process info
486 printf("CreateProcess() error: %s\n", dlerror());
490 // Set the owner process id in the target process.
492 DWORD pid = GetCurrentProcessId();
493 if(!WriteProcessMemory(procinfo.hProcess, &owner_processid, &pid, sizeof(DWORD), &written) || written != sizeof(DWORD))
495 printf("WriteProcessMemory() failed: %s\n", dlerror());
499 // Resume the other thread (let it start)
500 ResumeThread(procinfo.hThread);
502 // Wait for the new process to kill us. If there is some error, the new process will end and we will end up at the next line.
503 WaitForSingleObject(procinfo.hProcess, INFINITE);
505 // If we hit this it means startup failed, default to 14 if this fails.
507 GetExitCodeProcess(procinfo.hProcess, &ExitCode);
508 CloseHandle(procinfo.hThread);
509 CloseHandle(procinfo.hProcess);
513 void WindowsForkKillOwner()
515 HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, owner_processid);
516 if(!hProcess || !owner_processid)
518 printf("Could not open process id %u: %s.\n", owner_processid, dlerror());
519 ServerInstance->Exit(14);
523 if(!TerminateProcess(hProcess, 0))
525 printf("Could not TerminateProcess(): %s\n", dlerror());
526 ServerInstance->Exit(14);
529 CloseHandle(hProcess);
532 void FindDNS(std::string& server)
537 ServerInstance->Logs->Log("CONFIG",DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in the registry...");
538 std::string nameserver = FindNameServerWin();
540 /* If empty use default to 127.0.0.1 */
541 if (nameserver.empty())
543 ServerInstance->Logs->Log("CONFIG",DEFAULT,"No viable nameserver found in registry! Defaulting to nameserver '127.0.0.1'!");
544 server = "127.0.0.1";
548 /* Windows stacks multiple nameservers in one registry key, seperated by commas.
549 * Spotted by Cataclysm.
551 if (nameserver.find(',') != std::string::npos)
552 nameserver = nameserver.substr(0, nameserver.find(','));
554 /* Just to be FUCKING AKWARD, windows fister... err i mean vista...
555 * seperates the nameservers with spaces instead.
557 if (nameserver.find(' ') != std::string::npos)
558 nameserver = nameserver.substr(0, nameserver.find(' '));
561 ServerInstance->Logs->Log("CONFIG",DEFAULT,"<dns:server> set to '%s' as first active resolver in registry.", nameserver.c_str());
564 int clock_gettime(int clock, struct timespec * tv)
569 DWORD mstime = timeGetTime();
570 tv->tv_sec = time(NULL);
571 tv->tv_nsec = (mstime - (tv->tv_sec * 1000)) * 1000000;
575 /* Initialise WMI. Microsoft have the silliest ideas about easy ways to
576 * obtain the CPU percentage of a running process!
577 * The whole API for this uses evil DCOM and is entirely unicode, giving
578 * all results and accepting queries as wide strings.
584 /* Initialise COM. This can kill babies. */
585 hres = CoInitializeEx(0, COINIT_MULTITHREADED);
589 /* COM security. This stuff kills kittens */
590 hres = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT,
591 RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL);
599 /* Instance to COM object */
601 hres = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID*)&pLoc);
611 /* Connect to DCOM server */
612 hres = pLoc->ConnectServer(_bstr_t(L"ROOT\\CIMV2"), NULL, NULL, 0, NULL, 0, 0, &pSvc);
614 /* That didn't work, maybe no kittens found to kill? */
622 /* Don't even ASK what this does. I'm still not too sure myself. */
623 hres = CoSetProxyBlanket(pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL,
624 RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE);
643 /* Return the CPU usage in percent of this process */
649 /* Use WQL, similar to SQL, to construct a query that lists the cpu usage and pid of all processes */
650 IEnumWbemClassObject* pEnumerator = NULL;
652 BSTR Language = SysAllocString(L"WQL");
653 BSTR Query = SysAllocString(L"Select PercentProcessorTime,IDProcess from Win32_PerfFormattedData_PerfProc_Process");
655 hres = pSvc->ExecQuery(Language, Query, WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
657 /* Query didn't work */
660 IWbemClassObject *pclsObj = NULL;
663 /* Iterate the query results */
667 VariantInit(&vtProp);
669 HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
671 /* No more items left */
675 /* Find process ID */
676 hr = pclsObj->Get(L"IDProcess", 0, &vtProp, 0, 0);
679 /* Matches our process ID? */
680 UINT pid = vtProp.uintVal;
681 VariantClear(&vtProp);
682 if (pid == GetCurrentProcessId())
684 /* Get CPU percentage for this process */
685 hr = pclsObj->Get(L"PercentProcessorTime", 0, &vtProp, 0, 0);
688 /* Deal with wide string ickyness. Who in their right
689 * mind puts a number in a bstrVal wide string item?!
692 std::wstringstream out(vtProp.bstrVal);
694 VariantClear(&vtProp);
703 pEnumerator->Release();
706 SysFreeString(Language);
707 SysFreeString(Query);
717 void srandom(unsigned int seed)
722 int gettimeofday(timeval *tv, void *)
727 tv->tv_sec = time(NULL);
728 tv->tv_usec = st.wMilliseconds;
733 /* World's largest hack to make reference<> work */
734 #include "../src/modules/m_spanningtree/link.h"
735 #include "../src/modules/ssl.h"
736 template class reference<Link>;
737 template class reference<Autoconnect>;
738 template class reference<ssl_cert>;
739 template class reference<OperInfo>;