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 *insp_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 insp_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 ssize_t writev(int fd, const struct iovec* iov, int iovcnt)
157 for(i = 0; i < iovcnt; ++i)
158 tot += iov[i].iov_len;
159 buf = (char*)malloc(tot);
160 if (tot != 0 && buf == NULL) {
165 for (i = 0; i < iovcnt; ++i) {
166 memcpy (p, iov[i].iov_base, iov[i].iov_len);
169 ret = send((SOCKET)fd, buf, tot, 0);
174 #define TRED FOREGROUND_RED | FOREGROUND_INTENSITY
175 #define TGREEN FOREGROUND_GREEN | FOREGROUND_INTENSITY
176 #define TYELLOW FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY
177 #define TNORMAL FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE
178 #define TWHITE TNORMAL | FOREGROUND_INTENSITY
179 #define TBLUE FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY
181 /* Handles colors in printf */
182 int printf_c(const char * format, ...)
184 // Better hope we're not multithreaded, otherwise we'll have chickens crossing the road other side to get the to :P
185 static char message[MAXBUF];
186 static char temp[MAXBUF];
189 /* parse arguments */
191 va_start(ap, format);
192 vsnprintf(message, 500, format, ap);
195 /* search for unix-style escape sequences */
198 const char * p = message;
203 // Escape sequence -> copy into the temp buffer, and parse the color.
206 while ((*p) && (*p != 'm'))
217 if (sscanf(temp, "[%u;%u", &color1, &color2) == 2)
222 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN | FOREGROUND_INTENSITY); // Yellow
227 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
236 // Returning to normal colour.
237 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
242 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), TWHITE);
247 sprintf(message, "Unknown color code: %s", temp);
248 MessageBox(0, message, message, MB_OK);
265 int getopt_long_only(int ___argc, char *const *___argv, const char *__shortopts, const struct option *__longopts, int *__longind)
267 // burlex todo: handle the shortops, at the moment it only works with longopts.
269 if (___argc == 1 || optind == ___argc) // No arguments (apart from filename)
272 const char * opt = ___argv[optind];
275 // if we're not an option, return an error.
276 if (strnicmp(opt, "--", 2) != 0)
282 // parse argument list
284 for (; __longopts[i].name != 0; ++i)
286 if (!strnicmp(__longopts[i].name, opt, strlen(__longopts[i].name)))
288 // woot, found a valid argument =)
290 if ((optind) != ___argc)
292 // grab the parameter from the next argument (if its not another argument)
293 if (strnicmp(___argv[optind], "--", 2) != 0)
295 // optind++; // Trash this next argument, we won't be needing it.
296 par = ___argv[optind-1];
300 // increment the argument for next time
303 // determine action based on type
304 if (__longopts[i].has_arg == required_argument && !par)
306 // parameter missing and its a required parameter option
310 // store argument in optarg
312 strncpy(optarg, par, 514);
314 if (__longopts[i].flag != 0)
316 // this is a variable, we have to set it if this argument is found.
317 *__longopts[i].flag = 1;
322 if (__longopts[i].val == -1 || par == 0)
325 return __longopts[i].val;
331 // return 1 (invalid argument)
335 /* These three functions were created from looking at how ares does it
336 * (...and they look far tidier in C++)
339 /* Get active nameserver */
340 bool GetNameServer(HKEY regkey, const char *key, char* &output)
343 DWORD result = RegQueryValueEx(regkey, key, 0, NULL, NULL, &size);
344 if (((result != ERROR_SUCCESS) && (result != ERROR_MORE_DATA)) || (!size))
347 output = new char[size+1];
349 if ((RegQueryValueEx(regkey, key, 0, NULL, (LPBYTE)output, &size) != ERROR_SUCCESS) || (!*output))
357 /* Check a network interface for its nameserver */
358 bool GetInterface(HKEY regkey, const char *key, char* &output)
365 while (RegEnumKeyEx(regkey, idx++, buf, &size, 0, NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
368 if (RegOpenKeyEx(regkey, buf, 0, KEY_QUERY_VALUE, &top) != ERROR_SUCCESS)
370 int rc = GetNameServer(top, key, output);
379 std::string FindNameServerWin()
381 std::string returnval = "127.0.0.1";
385 /* Lets see if the correct registry hive and tree exist */
386 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\Tcpip\\Parameters", 0, KEY_READ, &top) == ERROR_SUCCESS)
388 /* If they do, attempt to get the nameserver name */
389 RegOpenKeyEx(top, "Interfaces", 0, KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &key);
390 if ((GetNameServer(top, "NameServer", dns)) || (GetNameServer(top, "DhcpNameServer", dns))
391 || (GetInterface(key, "NameServer", dns)) || (GetInterface(key, "DhcpNameServer", dns)))
408 COORD coordScreen = { 0, 0 }; /* here's where we'll home the cursor */
409 HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
411 CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */
412 DWORD dwConSize; /* number of character cells in the current buffer */
414 /* get the number of character cells in the current buffer */
416 if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
418 dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
419 /* fill the entire screen with blanks */
420 if (FillConsoleOutputCharacter( hConsole, (TCHAR) ' ', dwConSize, coordScreen, &cCharsWritten ))
422 /* get the current text attribute */
423 if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
425 /* now set the buffer's attributes accordingly */
426 if (FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten ))
428 /* put the cursor at (0, 0) */
429 SetConsoleCursorPosition( hConsole, coordScreen );
437 /* Many inspircd classes contain function pointers/functors which can be changed to point at platform specific implementations
438 * of code. This function repoints these pointers and functors so that calls are windows specific.
440 void ChangeWindowsSpecificPointers()
442 ServerInstance->Logs->Log("win32",DEBUG,"Changing to windows specific pointer and functor set");
445 DWORD WindowsForkStart()
447 /* Windows implementation of fork() :P */
451 char module[MAX_PATH];
452 if(!GetModuleFileName(NULL, module, MAX_PATH))
454 printf("GetModuleFileName() failed.\n");
458 STARTUPINFO startupinfo;
459 PROCESS_INFORMATION procinfo;
460 ZeroMemory(&startupinfo, sizeof(STARTUPINFO));
461 ZeroMemory(&procinfo, sizeof(PROCESS_INFORMATION));
463 // Fill in the startup info struct
464 GetStartupInfo(&startupinfo);
466 /* Default creation flags create the processes suspended */
467 DWORD startupflags = CREATE_SUSPENDED;
469 /* On windows 2003/XP and above, we can use the value
470 * CREATE_PRESERVE_CODE_AUTHZ_LEVEL which gives more access
471 * to the process which we may require on these operating systems.
474 vi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
476 if ((vi.dwMajorVersion >= 5) && (vi.dwMinorVersion > 0))
477 startupflags |= CREATE_PRESERVE_CODE_AUTHZ_LEVEL;
479 // Launch our "forked" process.
480 BOOL bSuccess = CreateProcess ( module, // Module (exe) filename
481 strdup(GetCommandLine()), // Command line (exe plus parameters from the OS)
482 // NOTE: We cannot return the direct value of the
483 // GetCommandLine function here, as the pointer is
484 // passed straight to the child process, and will be
485 // invalid once we exit as it goes out of context.
486 // strdup() seems ok, though.
487 0, // PROCESS_SECURITY_ATTRIBUTES
488 0, // THREAD_SECURITY_ATTRIBUTES
489 TRUE, // We went to inherit handles.
490 startupflags, // Allow us full access to the process and suspend it.
492 0, // CURRENT_DIRECTORY
493 &startupinfo, // startup info
494 &procinfo); // process info
498 printf("CreateProcess() error: %s\n", dlerror());
502 // Set the owner process id in the target process.
504 DWORD pid = GetCurrentProcessId();
505 if(!WriteProcessMemory(procinfo.hProcess, &owner_processid, &pid, sizeof(DWORD), &written) || written != sizeof(DWORD))
507 printf("WriteProcessMemory() failed: %s\n", dlerror());
511 // Resume the other thread (let it start)
512 ResumeThread(procinfo.hThread);
514 // 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.
515 WaitForSingleObject(procinfo.hProcess, INFINITE);
517 // If we hit this it means startup failed, default to 14 if this fails.
519 GetExitCodeProcess(procinfo.hProcess, &ExitCode);
520 CloseHandle(procinfo.hThread);
521 CloseHandle(procinfo.hProcess);
525 void WindowsForkKillOwner()
527 HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, owner_processid);
528 if(!hProcess || !owner_processid)
530 printf("Could not open process id %u: %s.\n", owner_processid, dlerror());
531 ServerInstance->Exit(14);
535 if(!TerminateProcess(hProcess, 0))
537 printf("Could not TerminateProcess(): %s\n", dlerror());
538 ServerInstance->Exit(14);
541 CloseHandle(hProcess);
544 bool ValidateDnsServer(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
546 if (!*(data.GetString()))
548 std::string nameserver;
549 ServerInstance->Logs->Log("win32",DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in the registry...");
550 nameserver = FindNameServerWin();
551 /* Windows stacks multiple nameservers in one registry key, seperated by commas.
552 * Spotted by Cataclysm.
554 if (nameserver.find(',') != std::string::npos)
555 nameserver = nameserver.substr(0, nameserver.find(','));
556 /* Just to be FUCKING AKWARD, windows fister... err i mean vista...
557 * seperates the nameservers with spaces instead.
559 if (nameserver.find(' ') != std::string::npos)
560 nameserver = nameserver.substr(0, nameserver.find(' '));
561 data.Set(nameserver.c_str());
562 ServerInstance->Logs->Log("win32",DEFAULT,"<dns:server> set to '%s' as first active resolver in registry.", nameserver.c_str());
567 int gettimeofday(struct timeval * tv, void * tz)
572 DWORD mstime = timeGetTime();
573 tv->tv_sec = time(NULL);
574 tv->tv_usec = (mstime - (tv->tv_sec * 1000)) * 1000;
578 /* Initialise WMI. Microsoft have the silliest ideas about easy ways to
579 * obtain the CPU percentage of a running process!
580 * The whole API for this uses evil DCOM and is entirely unicode, giving
581 * all results and accepting queries as wide strings.
587 /* Initialise COM. This can kill babies. */
588 hres = CoInitializeEx(0, COINIT_MULTITHREADED);
592 /* COM security. This stuff kills kittens */
593 hres = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT,
594 RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL);
602 /* Instance to COM object */
604 hres = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID*)&pLoc);
614 /* Connect to DCOM server */
615 hres = pLoc->ConnectServer(_bstr_t(L"ROOT\\CIMV2"), NULL, NULL, 0, NULL, 0, 0, &pSvc);
617 /* That didn't work, maybe no kittens found to kill? */
625 /* Don't even ASK what this does. I'm still not too sure myself. */
626 hres = CoSetProxyBlanket(pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL,
627 RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE);
646 /* Return the CPU usage in percent of this process */
652 /* Use WQL, similar to SQL, to construct a query that lists the cpu usage and pid of all processes */
653 IEnumWbemClassObject* pEnumerator = NULL;
655 BSTR Language = SysAllocString(L"WQL");
656 BSTR Query = SysAllocString(L"Select PercentProcessorTime,IDProcess from Win32_PerfFormattedData_PerfProc_Process");
658 hres = pSvc->ExecQuery(Language, Query, WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
660 /* Query didn't work */
663 IWbemClassObject *pclsObj = NULL;
666 /* Iterate the query results */
671 HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
673 /* No more items left */
677 /* Find process ID */
678 hr = pclsObj->Get(L"IDProcess", 0, &vtProp, 0, 0);
681 /* Matches our process ID? */
682 if (vtProp.uintVal == GetCurrentProcessId())
684 VariantClear(&vtProp);
685 /* Get CPU percentage for this process */
686 hr = pclsObj->Get(L"PercentProcessorTime", 0, &vtProp, 0, 0);
689 /* Deal with wide string ickyness. Who in their right
690 * mind puts a number in a bstrVal wide string item?!
692 VariantClear(&vtProp);
694 std::wstringstream out(vtProp.bstrVal);
702 pEnumerator->Release();
706 SysFreeString(Language);
707 SysFreeString(Query);