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 char * strtok_r(char *_String, const char *_Control, char **_Context)
97 const unsigned char *ctl = (const unsigned char*)_Control;
98 unsigned char map[32];
100 if (_Context == 0 || !_Control)
103 if (!(_String != NULL || *_Context != NULL))
109 map[*ctl >> 3] |= (1 << (*ctl & 7));
112 /* If string is NULL, set str to the saved
113 * pointer (i.e., continue breaking tokens out of the string
114 * from the last strtok call) */
117 str = (unsigned char*)_String;
121 str = (unsigned char*)*_Context;
124 /* Find beginning of token (skip over leading delimiters). Note that
125 * there is no token iff this loop sets str to point to the terminal
126 * null (*str == 0) */
127 while ((map[*str >> 3] & (1 << (*str & 7))) && *str != 0)
132 _String = (char*)str;
134 /* Find the end of the token. If it is not the end of the string,
135 * put a null there. */
136 for ( ; *str != 0 ; str++ )
138 if (map[*str >> 3] & (1 << (*str & 7)))
146 *_Context = (char*)str;
148 /* Determine if a token has been found. */
149 if (_String == (char*)str)
159 void setcolor(int color_code)
161 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color_code);
164 DIR * opendir(const char * path)
166 std::string search_path = string(path) + "\\*.*";
168 HANDLE f = FindFirstFile(search_path.c_str(), &fd);
169 if (f != INVALID_HANDLE_VALUE)
172 memcpy(&d->find_data, &fd, sizeof(WIN32_FIND_DATA));
183 dirent * readdir(DIR * handle)
186 handle->first = false;
189 if (!FindNextFile(handle->find_handle, &handle->find_data))
193 strncpy(handle->dirent_pointer.d_name, handle->find_data.cFileName, MAX_PATH);
194 return &handle->dirent_pointer;
197 void closedir(DIR * handle)
199 FindClose(handle->find_handle);
203 const char * dlerror()
205 static char errormessage[500];
206 DWORD error = GetLastError();
211 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)errormessage, 500, 0);
215 #define TRED FOREGROUND_RED | FOREGROUND_INTENSITY
216 #define TGREEN FOREGROUND_GREEN | FOREGROUND_INTENSITY
217 #define TYELLOW FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY
218 #define TNORMAL FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE
219 #define TWHITE TNORMAL | FOREGROUND_INTENSITY
220 #define TBLUE FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY
222 /* Handles colors in printf */
223 int printf_c(const char * format, ...)
225 // Better hope we're not multithreaded, otherwise we'll have chickens crossing the road other side to get the to :P
226 static char message[MAXBUF];
227 static char temp[MAXBUF];
230 /* parse arguments */
232 va_start(ap, format);
233 vsnprintf(message, 500, format, ap);
236 /* search for unix-style escape sequences */
239 const char * p = message;
244 // Escape sequence -> copy into the temp buffer, and parse the color.
247 while ((*p) && (*p != 'm'))
258 if (sscanf(temp, "[%u;%u", &color1, &color2) == 2)
263 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN | FOREGROUND_INTENSITY); // Yellow
268 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
277 // Returning to normal colour.
278 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
283 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), TWHITE);
288 sprintf(message, "Unknown color code: %s", temp);
289 MessageBox(0, message, message, MB_OK);
306 int getopt_long_only(int ___argc, char *const *___argv, const char *__shortopts, const struct option *__longopts, int *__longind)
308 // burlex todo: handle the shortops, at the moment it only works with longopts.
310 if (___argc == 1 || arg_counter == ___argc) // No arguments (apart from filename)
313 const char * opt = ___argv[arg_counter];
315 // if we're not an option, return an error.
316 if (strnicmp(opt, "--", 2) != 0)
322 // parse argument list
324 for (; __longopts[i].name != 0; ++i)
326 if (!strnicmp(__longopts[i].name, opt, strlen(__longopts[i].name)))
328 // woot, found a valid argument =)
330 if ((arg_counter + 1) != ___argc)
332 // grab the parameter from the next argument (if its not another argument)
333 if (strnicmp(___argv[arg_counter+1], "--", 2) != 0)
335 arg_counter++; // Trash this next argument, we won't be needing it.
336 par = ___argv[arg_counter];
340 // increment the argument for next time
343 // determine action based on type
344 if (__longopts[i].has_arg == required_argument && !par)
346 // parameter missing and its a required parameter option
350 // store argument in optarg
352 strncpy(optarg, par, 514);
354 if (__longopts[i].flag != 0)
356 // this is a variable, we have to set it if this argument is found.
357 *__longopts[i].flag = 1;
362 if (__longopts[i].val == -1 || par == 0)
365 return __longopts[i].val;
371 // return 1 (invalid argument)
377 if (hIPCPipe == INVALID_HANDLE_VALUE)
383 BOOL res = ReadFile(hIPCPipe, &action, sizeof(DWORD), &bytes, 0);
386 if (GetLastError() != ERROR_SEM_TIMEOUT)
387 Instance->Logs->Log("win32",DEFAULT, "IPC Pipe Error %u: %s", GetLastError(), dlerror());
393 case IPC_MESSAGE_REHASH:
394 Instance->Rehash("due to IPC message");
397 case IPC_MESSAGE_DIE:
401 case IPC_MESSAGE_RESTART:
402 Instance->Restart("IPC_MESSAGE_RESTART received by mailslot.");
408 /* These three functions were created from looking at how ares does it
409 * (...and they look far tidier in C++)
412 /* Get active nameserver */
413 bool GetNameServer(HKEY regkey, const char *key, char* &output)
416 DWORD result = RegQueryValueEx(regkey, key, 0, NULL, NULL, &size);
417 if (((result != ERROR_SUCCESS) && (result != ERROR_MORE_DATA)) || (!size))
420 output = new char[size+1];
422 if ((RegQueryValueEx(regkey, key, 0, NULL, (LPBYTE)output, &size) != ERROR_SUCCESS) || (!*output))
430 /* Check a network interface for its nameserver */
431 bool GetInterface(HKEY regkey, const char *key, char* &output)
438 while (RegEnumKeyEx(regkey, idx++, buf, &size, 0, NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
441 if (RegOpenKeyEx(regkey, buf, 0, KEY_QUERY_VALUE, &top) != ERROR_SUCCESS)
443 int rc = GetNameServer(top, key, output);
452 std::string FindNameServerWin()
454 std::string returnval = "127.0.0.1";
458 /* Lets see if the correct registry hive and tree exist */
459 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\Tcpip\\Parameters", 0, KEY_READ, &top) == ERROR_SUCCESS)
461 /* If they do, attempt to get the nameserver name */
462 RegOpenKeyEx(top, "Interfaces", 0, KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &key);
463 if ((GetNameServer(top, "NameServer", dns)) || (GetNameServer(top, "DhcpNameServer", dns))
464 || (GetInterface(key, "NameServer", dns)) || (GetInterface(key, "DhcpNameServer", dns)))
481 COORD coordScreen = { 0, 0 }; /* here's where we'll home the cursor */
482 HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
484 CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */
485 DWORD dwConSize; /* number of character cells in the current buffer */
487 /* get the number of character cells in the current buffer */
489 if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
491 dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
492 /* fill the entire screen with blanks */
493 if (FillConsoleOutputCharacter( hConsole, (TCHAR) ' ', dwConSize, coordScreen, &cCharsWritten ))
495 /* get the current text attribute */
496 if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
498 /* now set the buffer's attributes accordingly */
499 if (FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten ))
501 /* put the cursor at (0, 0) */
502 SetConsoleCursorPosition( hConsole, coordScreen );
510 /* Many inspircd classes contain function pointers/functors which can be changed to point at platform specific implementations
511 * of code. This function repoints these pointers and functors so that calls are windows specific.
513 void ChangeWindowsSpecificPointers(InspIRCd* Instance)
515 Instance->Logs->Log("win32",DEBUG,"Changing to windows specific pointer and functor set");
516 Instance->Config->DNSServerValidator = &ValidateWindowsDnsServer;
519 DWORD WindowsForkStart(InspIRCd* Instance)
521 /* Windows implementation of fork() :P */
525 char module[MAX_PATH];
526 if(!GetModuleFileName(NULL, module, MAX_PATH))
528 printf("GetModuleFileName() failed.\n");
532 STARTUPINFO startupinfo;
533 PROCESS_INFORMATION procinfo;
534 ZeroMemory(&startupinfo, sizeof(STARTUPINFO));
535 ZeroMemory(&procinfo, sizeof(PROCESS_INFORMATION));
537 // Fill in the startup info struct
538 GetStartupInfo(&startupinfo);
540 /* Default creation flags create the processes suspended */
541 DWORD startupflags = CREATE_SUSPENDED;
543 /* On windows 2003/XP and above, we can use the value
544 * CREATE_PRESERVE_CODE_AUTHZ_LEVEL which gives more access
545 * to the process which we may require on these operating systems.
548 vi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
550 if ((vi.dwMajorVersion >= 5) && (vi.dwMinorVersion > 0))
551 startupflags |= CREATE_PRESERVE_CODE_AUTHZ_LEVEL;
553 // Launch our "forked" process.
554 BOOL bSuccess = CreateProcess ( module, // Module (exe) filename
555 strdup(GetCommandLine()), // Command line (exe plus parameters from the OS)
556 // NOTE: We cannot return the direct value of the
557 // GetCommandLine function here, as the pointer is
558 // passed straight to the child process, and will be
559 // invalid once we exit as it goes out of context.
560 // strdup() seems ok, though.
561 0, // PROCESS_SECURITY_ATTRIBUTES
562 0, // THREAD_SECURITY_ATTRIBUTES
563 TRUE, // We went to inherit handles.
564 startupflags, // Allow us full access to the process and suspend it.
566 0, // CURRENT_DIRECTORY
567 &startupinfo, // startup info
568 &procinfo); // process info
572 printf("CreateProcess() error: %s\n", dlerror());
576 // Set the owner process id in the target process.
578 DWORD pid = GetCurrentProcessId();
579 if(!WriteProcessMemory(procinfo.hProcess, &owner_processid, &pid, sizeof(DWORD), &written) || written != sizeof(DWORD))
581 printf("WriteProcessMemory() failed: %s\n", dlerror());
585 // Resume the other thread (let it start)
586 ResumeThread(procinfo.hThread);
588 // 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.
589 WaitForSingleObject(procinfo.hProcess, INFINITE);
591 // If we hit this it means startup failed, default to 14 if this fails.
593 GetExitCodeProcess(procinfo.hProcess, &ExitCode);
594 CloseHandle(procinfo.hThread);
595 CloseHandle(procinfo.hProcess);
599 void WindowsForkKillOwner(InspIRCd * Instance)
601 HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, owner_processid);
602 if(!hProcess || !owner_processid)
604 printf("Could not open process id %u: %s.\n", owner_processid, dlerror());
609 if(!TerminateProcess(hProcess, 0))
611 printf("Could not TerminateProcess(): %s\n", dlerror());
615 CloseHandle(hProcess);
618 bool ValidateWindowsDnsServer(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
620 if (!*(data.GetString()))
622 std::string nameserver;
623 conf->GetInstance()->Logs->Log("win32",DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in the registry...");
624 nameserver = FindNameServerWin();
625 /* Windows stacks multiple nameservers in one registry key, seperated by commas.
626 * Spotted by Cataclysm.
628 if (nameserver.find(',') != std::string::npos)
629 nameserver = nameserver.substr(0, nameserver.find(','));
630 /* Just to be FUCKING AKWARD, windows fister... err i mean vista...
631 * seperates the nameservers with spaces instead.
633 if (nameserver.find(' ') != std::string::npos)
634 nameserver = nameserver.substr(0, nameserver.find(' '));
635 data.Set(nameserver.c_str());
636 conf->GetInstance()->Logs->Log("win32",DEFAULT,"<dns:server> set to '%s' as first active resolver in registry.", nameserver.c_str());
641 int gettimeofday(struct timeval * tv, void * tz)
646 DWORD mstime = timeGetTime();
647 tv->tv_sec = time(NULL);
648 tv->tv_usec = (mstime - (tv->tv_sec * 1000)) * 1000;
652 /* Initialise WMI. Microsoft have the silliest ideas about easy ways to
653 * obtain the CPU percentage of a running process!
654 * The whole API for this uses evil DCOM and is entirely unicode, giving
655 * all results and accepting queries as wide strings.
661 /* Initialise COM. This can kill babies. */
662 hres = CoInitializeEx(0, COINIT_MULTITHREADED);
666 /* COM security. This stuff kills kittens */
667 hres = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT,
668 RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL);
676 /* Instance to COM object */
678 hres = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID*)&pLoc);
688 /* Connect to DCOM server */
689 hres = pLoc->ConnectServer(_bstr_t(L"ROOT\\CIMV2"), NULL, NULL, 0, NULL, 0, 0, &pSvc);
691 /* That didn't work, maybe no kittens found to kill? */
699 /* Don't even ASK what this does. I'm still not too sure myself. */
700 hres = CoSetProxyBlanket(pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL,
701 RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE);
720 /* Return the CPU usage in percent of this process */
725 /* Use WQL, similar to SQL, to construct a query that lists the cpu usage and pid of all processes */
726 IEnumWbemClassObject* pEnumerator = NULL;
727 hres = pSvc->ExecQuery(bstr_t("WQL"),
728 bstr_t("Select PercentProcessorTime,IDProcess from Win32_PerfFormattedData_PerfProc_Process"),
729 WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
731 /* Query didn't work */
735 IWbemClassObject *pclsObj = NULL;
738 /* Iterate the query results */
743 HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
745 /* No more items left */
749 /* Find process ID */
750 hr = pclsObj->Get(L"IDProcess", 0, &vtProp, 0, 0);
753 /* Matches our process ID? */
754 if (vtProp.uintVal == GetCurrentProcessId())
756 VariantClear(&vtProp);
757 /* Get CPU percentage for this process */
758 hr = pclsObj->Get(L"PercentProcessorTime", 0, &vtProp, 0, 0);
761 /* Deal with wide string ickyness. Who in their right
762 * mind puts a number in a bstrVal wide string item?!
764 VariantClear(&vtProp);
766 std::wstringstream out(vtProp.bstrVal);
768 pEnumerator->Release();
775 pEnumerator->Release();
780 void usleep(unsigned long usecs)
784 unsigned long millis = ((usecs + 999UL) / 1000UL);
785 SleepEx(millis, false);