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"
37 #pragma comment(lib, "wbemuuid.lib")
38 #pragma comment(lib, "comsuppwd.lib")
39 #pragma comment(lib, "winmm.lib")
40 #pragma comment(lib, "Iphlpapi.lib")
44 #define INADDR_NONE 0xffffffff
49 IWbemLocator *pLoc = NULL;
50 IWbemServices *pSvc = NULL;
52 /* This MUST remain static and delcared outside the class, so that WriteProcessMemory can reference it properly */
53 static DWORD owner_processid = 0;
56 int inet_aton(const char *cp, struct in_addr *addr)
58 unsigned long ip = inet_addr(cp);
60 return (addr->s_addr == INADDR_NONE) ? 0 : 1;
63 const char *insp_inet_ntop(int af, const void *src, char *dst, socklen_t cnt)
68 struct sockaddr_in in;
69 memset(&in, 0, sizeof(in));
70 in.sin_family = AF_INET;
71 memcpy(&in.sin_addr, src, sizeof(struct in_addr));
72 getnameinfo((struct sockaddr *)&in, sizeof(struct sockaddr_in), dst, cnt, NULL, 0, NI_NUMERICHOST);
75 else if (af == AF_INET6)
77 struct sockaddr_in6 in;
78 memset(&in, 0, sizeof(in));
79 in.sin6_family = AF_INET6;
80 memcpy(&in.sin6_addr, src, sizeof(struct in_addr6));
81 getnameinfo((struct sockaddr *)&in, sizeof(struct sockaddr_in6), dst, cnt, NULL, 0, NI_NUMERICHOST);
92 int insp_inet_pton(int af, const char *src, void *dst)
95 int len = sizeof(SOCKADDR);
96 int rv = WSAStringToAddress((LPSTR)src, af, NULL, (LPSOCKADDR)&sa, &len);
99 if(WSAGetLastError() == 10022) // Invalid Argument
104 memcpy(dst, &sa.sin_addr, sizeof(struct in_addr));
108 void setcolor(int color_code)
110 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color_code);
113 DIR * opendir(const char * path)
115 std::string search_path = string(path) + "\\*.*";
117 HANDLE f = FindFirstFile(search_path.c_str(), &fd);
118 if (f != INVALID_HANDLE_VALUE)
121 memcpy(&d->find_data, &fd, sizeof(WIN32_FIND_DATA));
132 dirent * readdir(DIR * handle)
135 handle->first = false;
138 if (!FindNextFile(handle->find_handle, &handle->find_data))
142 strncpy(handle->dirent_pointer.d_name, handle->find_data.cFileName, MAX_PATH);
143 return &handle->dirent_pointer;
146 void closedir(DIR * handle)
148 FindClose(handle->find_handle);
152 const char * dlerror()
154 static char errormessage[500];
155 DWORD error = GetLastError();
160 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)errormessage, 500, 0);
164 #define TRED FOREGROUND_RED | FOREGROUND_INTENSITY
165 #define TGREEN FOREGROUND_GREEN | FOREGROUND_INTENSITY
166 #define TYELLOW FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY
167 #define TNORMAL FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE
168 #define TWHITE TNORMAL | FOREGROUND_INTENSITY
169 #define TBLUE FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY
171 /* Handles colors in printf */
172 int printf_c(const char * format, ...)
174 // Better hope we're not multithreaded, otherwise we'll have chickens crossing the road other side to get the to :P
175 static char message[MAXBUF];
176 static char temp[MAXBUF];
179 /* parse arguments */
181 va_start(ap, format);
182 vsnprintf(message, 500, format, ap);
185 /* search for unix-style escape sequences */
188 const char * p = message;
193 // Escape sequence -> copy into the temp buffer, and parse the color.
196 while ((*p) && (*p != 'm'))
207 if (sscanf(temp, "[%u;%u", &color1, &color2) == 2)
212 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN | FOREGROUND_INTENSITY); // Yellow
217 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
226 // Returning to normal colour.
227 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
232 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), TWHITE);
237 sprintf(message, "Unknown color code: %s", temp);
238 MessageBox(0, message, message, MB_OK);
255 int getopt_long(int ___argc, char *const *___argv, const char *__shortopts, const struct option *__longopts, int *__longind)
257 // burlex todo: handle the shortops, at the moment it only works with longopts.
259 if (___argc == 1 || optind == ___argc) // No arguments (apart from filename)
262 const char * opt = ___argv[optind];
265 // if we're not an option, return an error.
266 if (strnicmp(opt, "--", 2) != 0)
272 // parse argument list
274 for (; __longopts[i].name != 0; ++i)
276 if (!strnicmp(__longopts[i].name, opt, strlen(__longopts[i].name)))
278 // woot, found a valid argument =)
280 if ((optind) != ___argc)
282 // grab the parameter from the next argument (if its not another argument)
283 if (strnicmp(___argv[optind], "--", 2) != 0)
285 // optind++; // Trash this next argument, we won't be needing it.
286 par = ___argv[optind-1];
290 // increment the argument for next time
293 // determine action based on type
294 if (__longopts[i].has_arg == required_argument && !par)
296 // parameter missing and its a required parameter option
300 // store argument in optarg
302 strncpy(optarg, par, 514);
304 if (__longopts[i].flag != 0)
306 // this is a variable, we have to set it if this argument is found.
307 *__longopts[i].flag = 1;
312 if (__longopts[i].val == -1 || par == 0)
315 return __longopts[i].val;
321 // return 1 (invalid argument)
327 COORD coordScreen = { 0, 0 }; /* here's where we'll home the cursor */
328 HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
330 CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */
331 DWORD dwConSize; /* number of character cells in the current buffer */
333 /* get the number of character cells in the current buffer */
335 if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
337 dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
338 /* fill the entire screen with blanks */
339 if (FillConsoleOutputCharacter( hConsole, (TCHAR) ' ', dwConSize, coordScreen, &cCharsWritten ))
341 /* get the current text attribute */
342 if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
344 /* now set the buffer's attributes accordingly */
345 if (FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten ))
347 /* put the cursor at (0, 0) */
348 SetConsoleCursorPosition( hConsole, coordScreen );
356 /* Many inspircd classes contain function pointers/functors which can be changed to point at platform specific implementations
357 * of code. This function repoints these pointers and functors so that calls are windows specific.
359 void ChangeWindowsSpecificPointers()
361 ServerInstance->Logs->Log("win32",DEBUG,"Changing to windows specific pointer and functor set");
364 DWORD WindowsForkStart()
366 /* Windows implementation of fork() :P */
370 char module[MAX_PATH];
371 if(!GetModuleFileName(NULL, module, MAX_PATH))
373 printf("GetModuleFileName() failed.\n");
377 STARTUPINFO startupinfo;
378 PROCESS_INFORMATION procinfo;
379 ZeroMemory(&startupinfo, sizeof(STARTUPINFO));
380 ZeroMemory(&procinfo, sizeof(PROCESS_INFORMATION));
382 // Fill in the startup info struct
383 GetStartupInfo(&startupinfo);
385 /* Default creation flags create the processes suspended */
386 DWORD startupflags = CREATE_SUSPENDED;
388 /* On windows 2003/XP and above, we can use the value
389 * CREATE_PRESERVE_CODE_AUTHZ_LEVEL which gives more access
390 * to the process which we may require on these operating systems.
393 vi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
395 if ((vi.dwMajorVersion >= 5) && (vi.dwMinorVersion > 0))
396 startupflags |= CREATE_PRESERVE_CODE_AUTHZ_LEVEL;
398 // Launch our "forked" process.
399 BOOL bSuccess = CreateProcess ( module, // Module (exe) filename
400 strdup(GetCommandLine()), // Command line (exe plus parameters from the OS)
401 // NOTE: We cannot return the direct value of the
402 // GetCommandLine function here, as the pointer is
403 // passed straight to the child process, and will be
404 // invalid once we exit as it goes out of context.
405 // strdup() seems ok, though.
406 0, // PROCESS_SECURITY_ATTRIBUTES
407 0, // THREAD_SECURITY_ATTRIBUTES
408 TRUE, // We went to inherit handles.
409 startupflags, // Allow us full access to the process and suspend it.
411 0, // CURRENT_DIRECTORY
412 &startupinfo, // startup info
413 &procinfo); // process info
417 printf("CreateProcess() error: %s\n", dlerror());
421 // Set the owner process id in the target process.
423 DWORD pid = GetCurrentProcessId();
424 if(!WriteProcessMemory(procinfo.hProcess, &owner_processid, &pid, sizeof(DWORD), &written) || written != sizeof(DWORD))
426 printf("WriteProcessMemory() failed: %s\n", dlerror());
430 // Resume the other thread (let it start)
431 ResumeThread(procinfo.hThread);
433 // 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.
434 WaitForSingleObject(procinfo.hProcess, INFINITE);
436 // If we hit this it means startup failed, default to 14 if this fails.
438 GetExitCodeProcess(procinfo.hProcess, &ExitCode);
439 CloseHandle(procinfo.hThread);
440 CloseHandle(procinfo.hProcess);
444 void WindowsForkKillOwner()
446 HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, owner_processid);
447 if(!hProcess || !owner_processid)
449 printf("Could not open process id %u: %s.\n", owner_processid, dlerror());
450 ServerInstance->Exit(14);
454 if(!TerminateProcess(hProcess, 0))
456 printf("Could not TerminateProcess(): %s\n", dlerror());
457 ServerInstance->Exit(14);
460 CloseHandle(hProcess);
463 void FindDNS(std::string& server)
468 PFIXED_INFO pFixedInfo;
469 DWORD dwBufferSize = sizeof(FIXED_INFO);
470 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, sizeof(FIXED_INFO));
474 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == ERROR_BUFFER_OVERFLOW) {
475 HeapFree(GetProcessHeap(), 0, pFixedInfo);
476 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, dwBufferSize);
480 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == NO_ERROR)
481 server = pFixedInfo->DnsServerList.IpAddress.String;
483 HeapFree(GetProcessHeap(), 0, pFixedInfo);
487 /* If empty use default to 127.0.0.1 */
490 ServerInstance->Logs->Log("CONFIG",DEFAULT,"No viable nameserver found! Defaulting to nameserver '127.0.0.1'!");
491 server = "127.0.0.1";
495 ServerInstance->Logs->Log("CONFIG",DEFAULT,"<dns:server> set to '%s' as first active resolver.", server.c_str());
499 int clock_gettime(int clock, struct timespec * tv)
504 DWORD mstime = timeGetTime();
505 tv->tv_sec = time(NULL);
506 tv->tv_nsec = (mstime - (tv->tv_sec * 1000)) * 1000000;
510 /* Initialise WMI. Microsoft have the silliest ideas about easy ways to
511 * obtain the CPU percentage of a running process!
512 * The whole API for this uses evil DCOM and is entirely unicode, giving
513 * all results and accepting queries as wide strings.
519 /* Initialise COM. This can kill babies. */
520 hres = CoInitializeEx(0, COINIT_MULTITHREADED);
524 /* COM security. This stuff kills kittens */
525 hres = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT,
526 RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL);
534 /* Instance to COM object */
536 hres = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID*)&pLoc);
546 /* Connect to DCOM server */
547 hres = pLoc->ConnectServer(_bstr_t(L"ROOT\\CIMV2"), NULL, NULL, 0, NULL, 0, 0, &pSvc);
549 /* That didn't work, maybe no kittens found to kill? */
557 /* Don't even ASK what this does. I'm still not too sure myself. */
558 hres = CoSetProxyBlanket(pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL,
559 RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE);
578 /* Return the CPU usage in percent of this process */
584 /* Use WQL, similar to SQL, to construct a query that lists the cpu usage and pid of all processes */
585 IEnumWbemClassObject* pEnumerator = NULL;
587 BSTR Language = SysAllocString(L"WQL");
588 BSTR Query = SysAllocString(L"Select PercentProcessorTime,IDProcess from Win32_PerfFormattedData_PerfProc_Process");
590 hres = pSvc->ExecQuery(Language, Query, WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
592 /* Query didn't work */
595 IWbemClassObject *pclsObj = NULL;
598 /* Iterate the query results */
602 VariantInit(&vtProp);
604 HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
606 /* No more items left */
610 /* Find process ID */
611 hr = pclsObj->Get(L"IDProcess", 0, &vtProp, 0, 0);
614 /* Matches our process ID? */
615 UINT pid = vtProp.uintVal;
616 VariantClear(&vtProp);
617 if (pid == GetCurrentProcessId())
619 /* Get CPU percentage for this process */
620 hr = pclsObj->Get(L"PercentProcessorTime", 0, &vtProp, 0, 0);
623 /* Deal with wide string ickyness. Who in their right
624 * mind puts a number in a bstrVal wide string item?!
627 std::wstringstream out(vtProp.bstrVal);
629 VariantClear(&vtProp);
638 pEnumerator->Release();
641 SysFreeString(Language);
642 SysFreeString(Query);
652 void srandom(unsigned int seed)
657 int gettimeofday(timeval *tv, void *)
662 tv->tv_sec = time(NULL);
663 tv->tv_usec = st.wMilliseconds;
668 /* World's largest hack to make reference<> work */
669 #include "../src/modules/m_spanningtree/link.h"
670 #include "../src/modules/ssl.h"
671 static void unused_function()
673 reference<Link> unused_Link;
674 reference<Autoconnect> unused_Autoconnect;
675 reference<ssl_cert> unused_Cert;
676 reference<OperInfo> unused_OperInfo;
679 unused_Link->Port = -1;
680 if (unused_Autoconnect)
681 unused_Autoconnect->NextConnectTime = -1;
683 unused_Cert->dn = "";
685 unused_OperInfo->name = "";
687 Autoconnect *a = unused_Autoconnect;
688 Link *l = unused_Link;
689 ssl_cert *s = unused_Cert;
690 OperInfo *o = unused_OperInfo;
692 unused_Link = reference<Link>(unused_Link);
693 unused_Autoconnect = reference<Autoconnect>(unused_Autoconnect);
694 unused_Cert = reference<ssl_cert>(unused_Cert);
695 unused_OperInfo = reference<OperInfo>(unused_OperInfo);
697 unused_Link = reference<Link>(l);
698 unused_Autoconnect = reference<Autoconnect>(a);
699 unused_Cert = reference<ssl_cert>(s);
700 unused_OperInfo = reference<OperInfo>(o);
703 unused_Autoconnect = a;
708 delete unused_Autoconnect;
710 delete unused_OperInfo;