1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 InspIRCd Development Team
6 * See: http://wiki.inspircd.org/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
14 #include "inspircd_win32wrapper.h"
16 #include "configreader.h"
24 #pragma comment(lib, "wbemuuid.lib")
25 #pragma comment(lib, "comsuppwd.lib")
26 #pragma comment(lib, "winmm.lib")
30 #define INADDR_NONE 0xffffffff
35 IWbemLocator *pLoc = NULL;
36 IWbemServices *pSvc = NULL;
38 /* This MUST remain static and delcared outside the class, so that WriteProcessMemory can reference it properly */
39 static DWORD owner_processid = 0;
42 int inet_aton(const char *cp, struct in_addr *addr)
44 unsigned long ip = inet_addr(cp);
46 return (addr->s_addr == INADDR_NONE) ? 0 : 1;
49 const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt)
54 struct sockaddr_in in;
55 memset(&in, 0, sizeof(in));
56 in.sin_family = AF_INET;
57 memcpy(&in.sin_addr, src, sizeof(struct in_addr));
58 getnameinfo((struct sockaddr *)&in, sizeof(struct sockaddr_in), dst, cnt, NULL, 0, NI_NUMERICHOST);
61 else if (af == AF_INET6)
63 struct sockaddr_in6 in;
64 memset(&in, 0, sizeof(in));
65 in.sin6_family = AF_INET6;
66 memcpy(&in.sin6_addr, src, sizeof(struct in_addr6));
67 getnameinfo((struct sockaddr *)&in, sizeof(struct sockaddr_in6), dst, cnt, NULL, 0, NI_NUMERICHOST);
78 int inet_pton(int af, const char *src, void *dst)
81 int len = sizeof(SOCKADDR);
82 int rv = WSAStringToAddress((LPSTR)src, af, NULL, (LPSOCKADDR)&sa, &len);
85 if(WSAGetLastError() == 10022) // Invalid Argument
90 memcpy(dst, &sa.sin_addr, sizeof(struct in_addr));
94 void setcolor(int color_code)
96 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color_code);
99 DIR * opendir(const char * path)
101 std::string search_path = string(path) + "\\*.*";
103 HANDLE f = FindFirstFile(search_path.c_str(), &fd);
104 if (f != INVALID_HANDLE_VALUE)
107 memcpy(&d->find_data, &fd, sizeof(WIN32_FIND_DATA));
118 dirent * readdir(DIR * handle)
121 handle->first = false;
124 if (!FindNextFile(handle->find_handle, &handle->find_data))
128 strncpy(handle->dirent_pointer.d_name, handle->find_data.cFileName, MAX_PATH);
129 return &handle->dirent_pointer;
132 void closedir(DIR * handle)
134 FindClose(handle->find_handle);
138 const char * dlerror()
140 static char errormessage[500];
141 DWORD error = GetLastError();
146 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)errormessage, 500, 0);
150 #define TRED FOREGROUND_RED | FOREGROUND_INTENSITY
151 #define TGREEN FOREGROUND_GREEN | FOREGROUND_INTENSITY
152 #define TYELLOW FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY
153 #define TNORMAL FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE
154 #define TWHITE TNORMAL | FOREGROUND_INTENSITY
155 #define TBLUE FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY
157 /* Handles colors in printf */
158 int printf_c(const char * format, ...)
160 // Better hope we're not multithreaded, otherwise we'll have chickens crossing the road other side to get the to :P
161 static char message[MAXBUF];
162 static char temp[MAXBUF];
165 /* parse arguments */
167 va_start(ap, format);
168 vsnprintf(message, 500, format, ap);
171 /* search for unix-style escape sequences */
174 const char * p = message;
179 // Escape sequence -> copy into the temp buffer, and parse the color.
182 while ((*p) && (*p != 'm'))
193 if (sscanf(temp, "[%u;%u", &color1, &color2) == 2)
198 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN | FOREGROUND_INTENSITY); // Yellow
203 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
212 // Returning to normal colour.
213 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
218 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), TWHITE);
223 sprintf(message, "Unknown color code: %s", temp);
224 MessageBox(0, message, message, MB_OK);
241 int getopt_long_only(int ___argc, char *const *___argv, const char *__shortopts, const struct option *__longopts, int *__longind)
243 // burlex todo: handle the shortops, at the moment it only works with longopts.
245 if (___argc == 1 || arg_counter == ___argc) // No arguments (apart from filename)
248 const char * opt = ___argv[arg_counter];
250 // if we're not an option, return an error.
251 if (strnicmp(opt, "--", 2) != 0)
257 // parse argument list
259 for (; __longopts[i].name != 0; ++i)
261 if (!strnicmp(__longopts[i].name, opt, strlen(__longopts[i].name)))
263 // woot, found a valid argument =)
265 if ((arg_counter + 1) != ___argc)
267 // grab the parameter from the next argument (if its not another argument)
268 if (strnicmp(___argv[arg_counter+1], "--", 2) != 0)
270 arg_counter++; // Trash this next argument, we won't be needing it.
271 par = ___argv[arg_counter];
275 // increment the argument for next time
278 // determine action based on type
279 if (__longopts[i].has_arg == required_argument && !par)
281 // parameter missing and its a required parameter option
285 // store argument in optarg
287 strncpy(optarg, par, 514);
289 if (__longopts[i].flag != 0)
291 // this is a variable, we have to set it if this argument is found.
292 *__longopts[i].flag = 1;
297 if (__longopts[i].val == -1 || par == 0)
300 return __longopts[i].val;
306 // return 1 (invalid argument)
310 /* These three functions were created from looking at how ares does it
311 * (...and they look far tidier in C++)
314 /* Get active nameserver */
315 bool GetNameServer(HKEY regkey, const char *key, char* &output)
318 DWORD result = RegQueryValueEx(regkey, key, 0, NULL, NULL, &size);
319 if (((result != ERROR_SUCCESS) && (result != ERROR_MORE_DATA)) || (!size))
322 output = new char[size+1];
324 if ((RegQueryValueEx(regkey, key, 0, NULL, (LPBYTE)output, &size) != ERROR_SUCCESS) || (!*output))
332 /* Check a network interface for its nameserver */
333 bool GetInterface(HKEY regkey, const char *key, char* &output)
340 while (RegEnumKeyEx(regkey, idx++, buf, &size, 0, NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
343 if (RegOpenKeyEx(regkey, buf, 0, KEY_QUERY_VALUE, &top) != ERROR_SUCCESS)
345 int rc = GetNameServer(top, key, output);
354 std::string FindNameServerWin()
356 std::string returnval = "127.0.0.1";
360 /* Lets see if the correct registry hive and tree exist */
361 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\Tcpip\\Parameters", 0, KEY_READ, &top) == ERROR_SUCCESS)
363 /* If they do, attempt to get the nameserver name */
364 RegOpenKeyEx(top, "Interfaces", 0, KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &key);
365 if ((GetNameServer(top, "NameServer", dns)) || (GetNameServer(top, "DhcpNameServer", dns))
366 || (GetInterface(key, "NameServer", dns)) || (GetInterface(key, "DhcpNameServer", dns)))
383 COORD coordScreen = { 0, 0 }; /* here's where we'll home the cursor */
384 HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
386 CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */
387 DWORD dwConSize; /* number of character cells in the current buffer */
389 /* get the number of character cells in the current buffer */
391 if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
393 dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
394 /* fill the entire screen with blanks */
395 if (FillConsoleOutputCharacter( hConsole, (TCHAR) ' ', dwConSize, coordScreen, &cCharsWritten ))
397 /* get the current text attribute */
398 if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
400 /* now set the buffer's attributes accordingly */
401 if (FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten ))
403 /* put the cursor at (0, 0) */
404 SetConsoleCursorPosition( hConsole, coordScreen );
412 /* Many inspircd classes contain function pointers/functors which can be changed to point at platform specific implementations
413 * of code. This function repoints these pointers and functors so that calls are windows specific.
415 void ChangeWindowsSpecificPointers(InspIRCd* Instance)
417 Instance->Logs->Log("win32",DEBUG,"Changing to windows specific pointer and functor set");
418 Instance->Config->DNSServerValidator = &ValidateWindowsDnsServer;
421 DWORD WindowsForkStart(InspIRCd* Instance)
423 /* Windows implementation of fork() :P */
427 char module[MAX_PATH];
428 if(!GetModuleFileName(NULL, module, MAX_PATH))
430 printf("GetModuleFileName() failed.\n");
434 STARTUPINFO startupinfo;
435 PROCESS_INFORMATION procinfo;
436 ZeroMemory(&startupinfo, sizeof(STARTUPINFO));
437 ZeroMemory(&procinfo, sizeof(PROCESS_INFORMATION));
439 // Fill in the startup info struct
440 GetStartupInfo(&startupinfo);
442 /* Default creation flags create the processes suspended */
443 DWORD startupflags = CREATE_SUSPENDED;
445 /* On windows 2003/XP and above, we can use the value
446 * CREATE_PRESERVE_CODE_AUTHZ_LEVEL which gives more access
447 * to the process which we may require on these operating systems.
450 vi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
452 if ((vi.dwMajorVersion >= 5) && (vi.dwMinorVersion > 0))
453 startupflags |= CREATE_PRESERVE_CODE_AUTHZ_LEVEL;
455 // Launch our "forked" process.
456 BOOL bSuccess = CreateProcess ( module, // Module (exe) filename
457 strdup(GetCommandLine()), // Command line (exe plus parameters from the OS)
458 // NOTE: We cannot return the direct value of the
459 // GetCommandLine function here, as the pointer is
460 // passed straight to the child process, and will be
461 // invalid once we exit as it goes out of context.
462 // strdup() seems ok, though.
463 0, // PROCESS_SECURITY_ATTRIBUTES
464 0, // THREAD_SECURITY_ATTRIBUTES
465 TRUE, // We went to inherit handles.
466 startupflags, // Allow us full access to the process and suspend it.
468 0, // CURRENT_DIRECTORY
469 &startupinfo, // startup info
470 &procinfo); // process info
474 printf("CreateProcess() error: %s\n", dlerror());
478 // Set the owner process id in the target process.
480 DWORD pid = GetCurrentProcessId();
481 if(!WriteProcessMemory(procinfo.hProcess, &owner_processid, &pid, sizeof(DWORD), &written) || written != sizeof(DWORD))
483 printf("WriteProcessMemory() failed: %s\n", dlerror());
487 // Resume the other thread (let it start)
488 ResumeThread(procinfo.hThread);
490 // 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.
491 WaitForSingleObject(procinfo.hProcess, INFINITE);
493 // If we hit this it means startup failed, default to 14 if this fails.
495 GetExitCodeProcess(procinfo.hProcess, &ExitCode);
496 CloseHandle(procinfo.hThread);
497 CloseHandle(procinfo.hProcess);
501 void WindowsForkKillOwner(InspIRCd * Instance)
503 HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, owner_processid);
504 if(!hProcess || !owner_processid)
506 printf("Could not open process id %u: %s.\n", owner_processid, dlerror());
511 if(!TerminateProcess(hProcess, 0))
513 printf("Could not TerminateProcess(): %s\n", dlerror());
517 CloseHandle(hProcess);
520 bool ValidateWindowsDnsServer(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
522 if (!*(data.GetString()))
524 std::string nameserver;
525 conf->GetInstance()->Logs->Log("win32",DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in the registry...");
526 nameserver = FindNameServerWin();
527 /* Windows stacks multiple nameservers in one registry key, seperated by commas.
528 * Spotted by Cataclysm.
530 if (nameserver.find(',') != std::string::npos)
531 nameserver = nameserver.substr(0, nameserver.find(','));
532 /* Just to be FUCKING AKWARD, windows fister... err i mean vista...
533 * seperates the nameservers with spaces instead.
535 if (nameserver.find(' ') != std::string::npos)
536 nameserver = nameserver.substr(0, nameserver.find(' '));
537 data.Set(nameserver.c_str());
538 conf->GetInstance()->Logs->Log("win32",DEFAULT,"<dns:server> set to '%s' as first active resolver in registry.", nameserver.c_str());
543 int gettimeofday(struct timeval * tv, void * tz)
548 DWORD mstime = timeGetTime();
549 tv->tv_sec = time(NULL);
550 tv->tv_usec = (mstime - (tv->tv_sec * 1000)) * 1000;
554 /* Initialise WMI. Microsoft have the silliest ideas about easy ways to
555 * obtain the CPU percentage of a running process!
556 * The whole API for this uses evil DCOM and is entirely unicode, giving
557 * all results and accepting queries as wide strings.
563 /* Initialise COM. This can kill babies. */
564 hres = CoInitializeEx(0, COINIT_MULTITHREADED);
568 /* COM security. This stuff kills kittens */
569 hres = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT,
570 RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL);
578 /* Instance to COM object */
580 hres = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID*)&pLoc);
590 /* Connect to DCOM server */
591 hres = pLoc->ConnectServer(_bstr_t(L"ROOT\\CIMV2"), NULL, NULL, 0, NULL, 0, 0, &pSvc);
593 /* That didn't work, maybe no kittens found to kill? */
601 /* Don't even ASK what this does. I'm still not too sure myself. */
602 hres = CoSetProxyBlanket(pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL,
603 RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE);
622 /* Return the CPU usage in percent of this process */
628 /* Use WQL, similar to SQL, to construct a query that lists the cpu usage and pid of all processes */
629 IEnumWbemClassObject* pEnumerator = NULL;
631 BSTR Language = SysAllocString(L"WQL");
632 BSTR Query = SysAllocString(L"Select PercentProcessorTime,IDProcess from Win32_PerfFormattedData_PerfProc_Process");
634 hres = pSvc->ExecQuery(Language, Query, WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
636 /* Query didn't work */
639 IWbemClassObject *pclsObj = NULL;
642 /* Iterate the query results */
647 HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
649 /* No more items left */
653 /* Find process ID */
654 hr = pclsObj->Get(L"IDProcess", 0, &vtProp, 0, 0);
657 /* Matches our process ID? */
658 if (vtProp.uintVal == GetCurrentProcessId())
660 VariantClear(&vtProp);
661 /* Get CPU percentage for this process */
662 hr = pclsObj->Get(L"PercentProcessorTime", 0, &vtProp, 0, 0);
665 /* Deal with wide string ickyness. Who in their right
666 * mind puts a number in a bstrVal wide string item?!
668 VariantClear(&vtProp);
670 std::wstringstream out(vtProp.bstrVal);
678 pEnumerator->Release();
682 SysFreeString(Language);
683 SysFreeString(Query);
688 void usleep(unsigned long usecs)
692 unsigned long millis = ((usecs + 999UL) / 1000UL);
693 SleepEx(millis, false);