1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2008 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/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)
312 if (hIPCPipe == INVALID_HANDLE_VALUE)
318 BOOL res = ReadFile(hIPCPipe, &action, sizeof(DWORD), &bytes, 0);
321 if (GetLastError() != ERROR_SEM_TIMEOUT)
322 Instance->Logs->Log("win32",DEFAULT, "IPC Pipe Error %u: %s", GetLastError(), dlerror());
328 case IPC_MESSAGE_REHASH:
329 Instance->Rehash("due to IPC message");
332 case IPC_MESSAGE_DIE:
336 case IPC_MESSAGE_RESTART:
337 Instance->Restart("IPC_MESSAGE_RESTART received by mailslot.");
343 /* These three functions were created from looking at how ares does it
344 * (...and they look far tidier in C++)
347 /* Get active nameserver */
348 bool GetNameServer(HKEY regkey, const char *key, char* &output)
351 DWORD result = RegQueryValueEx(regkey, key, 0, NULL, NULL, &size);
352 if (((result != ERROR_SUCCESS) && (result != ERROR_MORE_DATA)) || (!size))
355 output = new char[size+1];
357 if ((RegQueryValueEx(regkey, key, 0, NULL, (LPBYTE)output, &size) != ERROR_SUCCESS) || (!*output))
365 /* Check a network interface for its nameserver */
366 bool GetInterface(HKEY regkey, const char *key, char* &output)
373 while (RegEnumKeyEx(regkey, idx++, buf, &size, 0, NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
376 if (RegOpenKeyEx(regkey, buf, 0, KEY_QUERY_VALUE, &top) != ERROR_SUCCESS)
378 int rc = GetNameServer(top, key, output);
387 std::string FindNameServerWin()
389 std::string returnval = "127.0.0.1";
393 /* Lets see if the correct registry hive and tree exist */
394 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\Tcpip\\Parameters", 0, KEY_READ, &top) == ERROR_SUCCESS)
396 /* If they do, attempt to get the nameserver name */
397 RegOpenKeyEx(top, "Interfaces", 0, KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &key);
398 if ((GetNameServer(top, "NameServer", dns)) || (GetNameServer(top, "DhcpNameServer", dns))
399 || (GetInterface(key, "NameServer", dns)) || (GetInterface(key, "DhcpNameServer", dns)))
416 COORD coordScreen = { 0, 0 }; /* here's where we'll home the cursor */
417 HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
419 CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */
420 DWORD dwConSize; /* number of character cells in the current buffer */
422 /* get the number of character cells in the current buffer */
424 if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
426 dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
427 /* fill the entire screen with blanks */
428 if (FillConsoleOutputCharacter( hConsole, (TCHAR) ' ', dwConSize, coordScreen, &cCharsWritten ))
430 /* get the current text attribute */
431 if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
433 /* now set the buffer's attributes accordingly */
434 if (FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten ))
436 /* put the cursor at (0, 0) */
437 SetConsoleCursorPosition( hConsole, coordScreen );
445 /* Many inspircd classes contain function pointers/functors which can be changed to point at platform specific implementations
446 * of code. This function repoints these pointers and functors so that calls are windows specific.
448 void ChangeWindowsSpecificPointers(InspIRCd* Instance)
450 Instance->Logs->Log("win32",DEBUG,"Changing to windows specific pointer and functor set");
451 Instance->Config->DNSServerValidator = &ValidateWindowsDnsServer;
454 DWORD WindowsForkStart(InspIRCd* Instance)
456 /* Windows implementation of fork() :P */
460 char module[MAX_PATH];
461 if(!GetModuleFileName(NULL, module, MAX_PATH))
463 printf("GetModuleFileName() failed.\n");
467 STARTUPINFO startupinfo;
468 PROCESS_INFORMATION procinfo;
469 ZeroMemory(&startupinfo, sizeof(STARTUPINFO));
470 ZeroMemory(&procinfo, sizeof(PROCESS_INFORMATION));
472 // Fill in the startup info struct
473 GetStartupInfo(&startupinfo);
475 /* Default creation flags create the processes suspended */
476 DWORD startupflags = CREATE_SUSPENDED;
478 /* On windows 2003/XP and above, we can use the value
479 * CREATE_PRESERVE_CODE_AUTHZ_LEVEL which gives more access
480 * to the process which we may require on these operating systems.
483 vi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
485 if ((vi.dwMajorVersion >= 5) && (vi.dwMinorVersion > 0))
486 startupflags |= CREATE_PRESERVE_CODE_AUTHZ_LEVEL;
488 // Launch our "forked" process.
489 BOOL bSuccess = CreateProcess ( module, // Module (exe) filename
490 strdup(GetCommandLine()), // Command line (exe plus parameters from the OS)
491 // NOTE: We cannot return the direct value of the
492 // GetCommandLine function here, as the pointer is
493 // passed straight to the child process, and will be
494 // invalid once we exit as it goes out of context.
495 // strdup() seems ok, though.
496 0, // PROCESS_SECURITY_ATTRIBUTES
497 0, // THREAD_SECURITY_ATTRIBUTES
498 TRUE, // We went to inherit handles.
499 startupflags, // Allow us full access to the process and suspend it.
501 0, // CURRENT_DIRECTORY
502 &startupinfo, // startup info
503 &procinfo); // process info
507 printf("CreateProcess() error: %s\n", dlerror());
511 // Set the owner process id in the target process.
513 DWORD pid = GetCurrentProcessId();
514 if(!WriteProcessMemory(procinfo.hProcess, &owner_processid, &pid, sizeof(DWORD), &written) || written != sizeof(DWORD))
516 printf("WriteProcessMemory() failed: %s\n", dlerror());
520 // Resume the other thread (let it start)
521 ResumeThread(procinfo.hThread);
523 // 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.
524 WaitForSingleObject(procinfo.hProcess, INFINITE);
526 // If we hit this it means startup failed, default to 14 if this fails.
528 GetExitCodeProcess(procinfo.hProcess, &ExitCode);
529 CloseHandle(procinfo.hThread);
530 CloseHandle(procinfo.hProcess);
534 void WindowsForkKillOwner(InspIRCd * Instance)
536 HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, owner_processid);
537 if(!hProcess || !owner_processid)
539 printf("Could not open process id %u: %s.\n", owner_processid, dlerror());
544 if(!TerminateProcess(hProcess, 0))
546 printf("Could not TerminateProcess(): %s\n", dlerror());
550 CloseHandle(hProcess);
553 bool ValidateWindowsDnsServer(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
555 if (!*(data.GetString()))
557 std::string nameserver;
558 conf->GetInstance()->Logs->Log("win32",DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in the registry...");
559 nameserver = FindNameServerWin();
560 /* Windows stacks multiple nameservers in one registry key, seperated by commas.
561 * Spotted by Cataclysm.
563 if (nameserver.find(',') != std::string::npos)
564 nameserver = nameserver.substr(0, nameserver.find(','));
565 /* Just to be FUCKING AKWARD, windows fister... err i mean vista...
566 * seperates the nameservers with spaces instead.
568 if (nameserver.find(' ') != std::string::npos)
569 nameserver = nameserver.substr(0, nameserver.find(' '));
570 data.Set(nameserver.c_str());
571 conf->GetInstance()->Logs->Log("win32",DEFAULT,"<dns:server> set to '%s' as first active resolver in registry.", nameserver.c_str());
576 int gettimeofday(struct timeval * tv, void * tz)
581 DWORD mstime = timeGetTime();
582 tv->tv_sec = time(NULL);
583 tv->tv_usec = (mstime - (tv->tv_sec * 1000)) * 1000;
587 /* Initialise WMI. Microsoft have the silliest ideas about easy ways to
588 * obtain the CPU percentage of a running process!
589 * The whole API for this uses evil DCOM and is entirely unicode, giving
590 * all results and accepting queries as wide strings.
596 /* Initialise COM. This can kill babies. */
597 hres = CoInitializeEx(0, COINIT_MULTITHREADED);
601 /* COM security. This stuff kills kittens */
602 hres = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT,
603 RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL);
611 /* Instance to COM object */
613 hres = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID*)&pLoc);
623 /* Connect to DCOM server */
624 hres = pLoc->ConnectServer(_bstr_t(L"ROOT\\CIMV2"), NULL, NULL, 0, NULL, 0, 0, &pSvc);
626 /* That didn't work, maybe no kittens found to kill? */
634 /* Don't even ASK what this does. I'm still not too sure myself. */
635 hres = CoSetProxyBlanket(pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL,
636 RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE);
655 /* Return the CPU usage in percent of this process */
660 /* Use WQL, similar to SQL, to construct a query that lists the cpu usage and pid of all processes */
661 IEnumWbemClassObject* pEnumerator = NULL;
662 hres = pSvc->ExecQuery(bstr_t("WQL"),
663 bstr_t("Select PercentProcessorTime,IDProcess from Win32_PerfFormattedData_PerfProc_Process"),
664 WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
666 /* Query didn't work */
670 IWbemClassObject *pclsObj = NULL;
673 /* Iterate the query results */
678 HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
680 /* No more items left */
684 /* Find process ID */
685 hr = pclsObj->Get(L"IDProcess", 0, &vtProp, 0, 0);
688 /* Matches our process ID? */
689 if (vtProp.uintVal == GetCurrentProcessId())
691 VariantClear(&vtProp);
692 /* Get CPU percentage for this process */
693 hr = pclsObj->Get(L"PercentProcessorTime", 0, &vtProp, 0, 0);
696 /* Deal with wide string ickyness. Who in their right
697 * mind puts a number in a bstrVal wide string item?!
699 VariantClear(&vtProp);
701 std::wstringstream out(vtProp.bstrVal);
703 pEnumerator->Release();
710 pEnumerator->Release();
715 void usleep(unsigned long usecs)
719 unsigned long millis = ((usecs + 999UL) / 1000UL);
720 SleepEx(millis, false);