]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - win/inspircd_win32wrapper.cpp
Fix typo opermoth -> opermotd. Thanks Ankit.
[user/henk/code/inspircd.git] / win / inspircd_win32wrapper.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2008 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include "inspircd_win32wrapper.h"
15 #include "inspircd.h"
16 #include "configreader.h"
17 #include <string>
18 #include <errno.h>
19 #include <assert.h>
20 #define _WIN32_DCOM
21 #include <comdef.h>
22 #include <Wbemidl.h>
23
24 #pragma comment(lib, "wbemuuid.lib")
25 #pragma comment(lib, "comsuppwd.lib")
26 #pragma comment(lib, "winmm.lib")
27 using namespace std;
28
29 #ifndef INADDR_NONE
30 #define INADDR_NONE 0xffffffff
31 #endif
32
33 #include <mmsystem.h>
34
35 IWbemLocator *pLoc = NULL;
36 IWbemServices *pSvc = NULL;
37
38 /* This MUST remain static and delcared outside the class, so that WriteProcessMemory can reference it properly */
39 static DWORD owner_processid = 0;
40
41
42 int inet_aton(const char *cp, struct in_addr *addr)
43 {
44         unsigned long ip = inet_addr(cp);
45         addr->s_addr = ip;
46         return (addr->s_addr == INADDR_NONE) ? 0 : 1;
47 }
48
49 const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt)
50 {
51
52         if (af == AF_INET)
53         {
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);
59                 return dst;
60         }
61         else if (af == AF_INET6)
62         {
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);
68                 return dst;
69         }
70         return NULL;
71 }
72
73 int geteuid()
74 {
75         return 1;
76 }
77
78 int inet_pton(int af, const char *src, void *dst)
79 {
80         sockaddr_in sa;
81         int len = sizeof(SOCKADDR);
82         int rv = WSAStringToAddress((LPSTR)src, af, NULL, (LPSOCKADDR)&sa, &len);
83         if(rv >= 0)
84         {
85                 if(WSAGetLastError() == 10022)                  // Invalid Argument
86                         rv = 0;
87                 else
88                         rv = 1;
89         }
90         memcpy(dst, &sa.sin_addr, sizeof(struct in_addr));
91         return rv;
92 }
93
94 void setcolor(int color_code)
95 {
96         SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color_code);
97 }
98
99 DIR * opendir(const char * path)
100 {
101         std::string search_path = string(path) + "\\*.*";
102         WIN32_FIND_DATA fd;
103         HANDLE f = FindFirstFile(search_path.c_str(), &fd);
104         if (f != INVALID_HANDLE_VALUE)
105         {
106                 DIR * d = new DIR;
107                 memcpy(&d->find_data, &fd, sizeof(WIN32_FIND_DATA));
108                 d->find_handle = f;
109                 d->first = true;
110                 return d;
111         }
112         else
113         {
114                 return 0;
115         }
116 }
117
118 dirent * readdir(DIR * handle)
119 {
120         if (handle->first)
121                 handle->first = false;
122         else
123         {
124                 if (!FindNextFile(handle->find_handle, &handle->find_data))
125                         return 0;
126         }
127
128         strncpy(handle->dirent_pointer.d_name, handle->find_data.cFileName, MAX_PATH);
129         return &handle->dirent_pointer;
130 }
131
132 void closedir(DIR * handle)
133 {
134         FindClose(handle->find_handle);
135         delete handle;
136 }
137
138 const char * dlerror()
139 {
140         static char errormessage[500];
141         DWORD error = GetLastError();
142         SetLastError(0);
143         if (error == 0)
144                 return 0;
145
146         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)errormessage, 500, 0);
147         return errormessage;
148 }
149
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
156
157 /* Handles colors in printf */
158 int printf_c(const char * format, ...)
159 {
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];
163         int color1, color2;
164
165         /* parse arguments */
166         va_list ap;
167         va_start(ap, format);
168         vsnprintf(message, 500, format, ap);
169         va_end(ap);
170
171         /* search for unix-style escape sequences */
172         int t;
173         int c = 0;
174         const char * p = message;
175         while (*p != 0)
176         {
177                 if (*p == '\033')
178                 {
179                         // Escape sequence -> copy into the temp buffer, and parse the color.
180                         p++;
181                         t = 0;
182                         while ((*p) && (*p != 'm'))
183                         {
184                                 temp[t++] = *p;
185                                 ++p;
186                         }
187
188                         temp[t] = 0;
189                         p++;
190
191                         if (*temp == '[')
192                         {
193                                 if (sscanf(temp, "[%u;%u", &color1, &color2) == 2)
194                                 {
195                                         switch(color2)
196                                         {
197                                         case 32:                // Green
198                                                 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN | FOREGROUND_INTENSITY);              // Yellow
199                                                 break;
200
201                                         default:                // Unknown
202                                                 // White
203                                                 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
204                                                 break;
205                                         }
206                                 }
207                                 else
208                                 {
209                                         switch (*(temp+1))
210                                         {
211                                                 case '0':
212                                                         // Returning to normal colour.
213                                                         SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
214                                                         break;
215
216                                                 case '1':
217                                                         // White
218                                                         SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), TWHITE);
219                                                         break;
220
221                                                 default:
222                                                         char message[50];
223                                                         sprintf(message, "Unknown color code: %s", temp);
224                                                         MessageBox(0, message, message, MB_OK);
225                                                         break;
226                                         }
227                                 }
228                         }
229                 }
230
231                 putchar(*p);
232                 ++c;
233                 ++p;
234         }
235
236         return c;
237 }
238
239 int arg_counter = 1;
240 char optarg[514];
241 int getopt_long_only(int ___argc, char *const *___argv, const char *__shortopts, const struct option *__longopts, int *__longind)
242 {
243         // burlex todo: handle the shortops, at the moment it only works with longopts.
244
245         if (___argc == 1 || arg_counter == ___argc)                     // No arguments (apart from filename)
246                 return -1;
247
248         const char * opt = ___argv[arg_counter];
249
250         // if we're not an option, return an error.
251         if (strnicmp(opt, "--", 2) != 0)
252                 return 1;
253         else
254                 opt += 2;
255
256
257         // parse argument list
258         int i = 0;
259         for (; __longopts[i].name != 0; ++i)
260         {
261                 if (!strnicmp(__longopts[i].name, opt, strlen(__longopts[i].name)))
262                 {
263                         // woot, found a valid argument =)
264                         char * par = 0;
265                         if ((arg_counter + 1) != ___argc)
266                         {
267                                 // grab the parameter from the next argument (if its not another argument)
268                                 if (strnicmp(___argv[arg_counter+1], "--", 2) != 0)
269                                 {
270                                         arg_counter++;          // Trash this next argument, we won't be needing it.
271                                         par = ___argv[arg_counter];
272                                 }
273                         }                       
274
275                         // increment the argument for next time
276                         arg_counter++;
277
278                         // determine action based on type
279                         if (__longopts[i].has_arg == required_argument && !par)
280                         {
281                                 // parameter missing and its a required parameter option
282                                 return 1;
283                         }
284
285                         // store argument in optarg
286                         if (par)
287                                 strncpy(optarg, par, 514);
288
289                         if (__longopts[i].flag != 0)
290                         {
291                                 // this is a variable, we have to set it if this argument is found.
292                                 *__longopts[i].flag = 1;
293                                 return 0;
294                         }
295                         else
296                         {
297                                 if (__longopts[i].val == -1 || par == 0)
298                                         return 1;
299                                 
300                                 return __longopts[i].val;
301                         }                       
302                         break;
303                 }
304         }
305
306         // return 1 (invalid argument)
307         return 1;
308 }
309
310 /*void IPC::Check()
311 {
312         if (hIPCPipe == INVALID_HANDLE_VALUE)
313                 return;
314
315         DWORD bytes;
316         DWORD action;
317
318         BOOL res = ReadFile(hIPCPipe, &action, sizeof(DWORD), &bytes, 0);
319         if (!res)
320         {
321                 if (GetLastError() != ERROR_SEM_TIMEOUT)
322                         Instance->Logs->Log("win32",DEFAULT, "IPC Pipe Error %u: %s", GetLastError(), dlerror());
323                 return;
324         }
325
326         switch (action)
327         {
328                 case IPC_MESSAGE_REHASH:
329                         Instance->Rehash("due to IPC message");
330                 break;
331                 
332                 case IPC_MESSAGE_DIE:
333                         Instance->Exit(0);
334                 break;
335
336                 case IPC_MESSAGE_RESTART:
337                         Instance->Restart("IPC_MESSAGE_RESTART received by mailslot.");
338                 break;
339         }
340 }*/
341
342
343 /* These three functions were created from looking at how ares does it
344  * (...and they look far tidier in C++)
345  */
346
347 /* Get active nameserver */
348 bool GetNameServer(HKEY regkey, const char *key, char* &output)
349 {
350         DWORD size = 0;
351         DWORD result = RegQueryValueEx(regkey, key, 0, NULL, NULL, &size);
352         if (((result != ERROR_SUCCESS) && (result != ERROR_MORE_DATA)) || (!size))
353                 return false;
354
355         output = new char[size+1];
356
357         if ((RegQueryValueEx(regkey, key, 0, NULL, (LPBYTE)output, &size) != ERROR_SUCCESS) || (!*output))
358         {
359                 delete output;
360                 return false;
361         }
362         return true;
363 }
364
365 /* Check a network interface for its nameserver */
366 bool GetInterface(HKEY regkey, const char *key, char* &output)
367 {
368         char buf[39];
369         DWORD size = 39;
370         int idx = 0;
371         HKEY top;
372
373         while (RegEnumKeyEx(regkey, idx++, buf, &size, 0, NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
374         {
375                 size = 39;
376                 if (RegOpenKeyEx(regkey, buf, 0, KEY_QUERY_VALUE, &top) != ERROR_SUCCESS)
377                         continue;
378                 int rc = GetNameServer(top, key, output);
379                 RegCloseKey(top);
380                 if (rc)
381                         return true;
382         }
383         return false;
384 }
385
386
387 std::string FindNameServerWin()
388 {
389         std::string returnval = "127.0.0.1";
390         HKEY top, key;
391         char* dns = NULL;
392
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)
395         {
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)))
400                 {
401                         if (dns)
402                         {
403                                 returnval = dns;
404                                 delete dns;
405                         }
406                 }
407                 RegCloseKey(key);
408                 RegCloseKey(top);
409         }
410         return returnval;
411 }
412
413
414 void ClearConsole()
415 {
416         COORD coordScreen = { 0, 0 };    /* here's where we'll home the cursor */
417         HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
418         DWORD cCharsWritten;
419         CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */ 
420         DWORD dwConSize;                 /* number of character cells in the current buffer */ 
421
422         /* get the number of character cells in the current buffer */ 
423
424         if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
425         {
426                 dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
427                 /* fill the entire screen with blanks */ 
428                 if (FillConsoleOutputCharacter( hConsole, (TCHAR) ' ', dwConSize, coordScreen, &cCharsWritten ))
429                 {
430                         /* get the current text attribute */ 
431                         if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
432                         {
433                                 /* now set the buffer's attributes accordingly */
434                                 if (FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten ))
435                                 {
436                                         /* put the cursor at (0, 0) */
437                                         SetConsoleCursorPosition( hConsole, coordScreen );
438                                 }
439                         }
440                 }
441         }
442         return;
443 }
444
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.
447  */
448 void ChangeWindowsSpecificPointers(InspIRCd* Instance)
449 {
450         Instance->Logs->Log("win32",DEBUG,"Changing to windows specific pointer and functor set");
451         Instance->Config->DNSServerValidator = &ValidateWindowsDnsServer;
452 }
453
454 DWORD WindowsForkStart(InspIRCd* Instance)
455 {
456         /* Windows implementation of fork() :P */
457         if (owner_processid)
458                 return 0;
459
460         char module[MAX_PATH];
461         if(!GetModuleFileName(NULL, module, MAX_PATH))
462         {
463                 printf("GetModuleFileName() failed.\n");
464                 return false;
465         }
466
467         STARTUPINFO startupinfo;
468         PROCESS_INFORMATION procinfo;
469         ZeroMemory(&startupinfo, sizeof(STARTUPINFO));
470         ZeroMemory(&procinfo, sizeof(PROCESS_INFORMATION));
471
472         // Fill in the startup info struct
473         GetStartupInfo(&startupinfo);
474
475         /* Default creation flags create the processes suspended */
476         DWORD startupflags = CREATE_SUSPENDED;
477
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.
481          */
482         OSVERSIONINFO vi;
483         vi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
484         GetVersionEx(&vi);
485         if ((vi.dwMajorVersion >= 5) && (vi.dwMinorVersion > 0))
486                 startupflags |= CREATE_PRESERVE_CODE_AUTHZ_LEVEL;
487
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.
500                 0,                              // ENVIRONMENT
501                 0,                              // CURRENT_DIRECTORY
502                 &startupinfo,                   // startup info
503                 &procinfo);                     // process info
504
505         if(!bSuccess)
506         {
507                 printf("CreateProcess() error: %s\n", dlerror());
508                 return false;
509         }
510
511         // Set the owner process id in the target process.
512         SIZE_T written = 0;
513         DWORD pid = GetCurrentProcessId();
514         if(!WriteProcessMemory(procinfo.hProcess, &owner_processid, &pid, sizeof(DWORD), &written) || written != sizeof(DWORD))
515         {
516                 printf("WriteProcessMemory() failed: %s\n", dlerror());
517                 return false;
518         }
519
520         // Resume the other thread (let it start)
521         ResumeThread(procinfo.hThread);
522
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);
525
526         // If we hit this it means startup failed, default to 14 if this fails.
527         DWORD ExitCode = 14;
528         GetExitCodeProcess(procinfo.hProcess, &ExitCode);
529         CloseHandle(procinfo.hThread);
530         CloseHandle(procinfo.hProcess);
531         return ExitCode;
532 }
533
534 void WindowsForkKillOwner(InspIRCd * Instance)
535 {
536         HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, owner_processid);
537         if(!hProcess || !owner_processid)
538         {
539                 printf("Could not open process id %u: %s.\n", owner_processid, dlerror());
540                 Instance->Exit(14);
541         }
542
543         // die die die
544         if(!TerminateProcess(hProcess, 0))
545         {
546                 printf("Could not TerminateProcess(): %s\n", dlerror());
547                 Instance->Exit(14);
548         }
549
550         CloseHandle(hProcess);
551 }
552
553 bool ValidateWindowsDnsServer(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
554 {
555         if (!*(data.GetString()))
556         {
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.
562                  */
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.
567                  */
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());
572         }
573         return true;
574 }
575
576 int gettimeofday(struct timeval * tv, void * tz)
577 {
578         if(tv == NULL)
579                 return -1;
580
581         DWORD mstime = timeGetTime();
582         tv->tv_sec   = time(NULL);
583         tv->tv_usec  = (mstime - (tv->tv_sec * 1000)) * 1000;
584         return 0;       
585 }
586
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.
591  */
592 bool initwmi()
593 {
594         HRESULT hres;
595
596         /* Initialise COM. This can kill babies. */
597         hres =  CoInitializeEx(0, COINIT_MULTITHREADED); 
598         if (FAILED(hres))
599                 return false;
600
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);
604
605         if (FAILED(hres))
606         {
607                 CoUninitialize();
608                 return false;
609         }
610     
611         /* Instance to COM object */
612         pLoc = NULL;
613         hres = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID*)&pLoc);
614  
615         if (FAILED(hres))
616         {
617                 CoUninitialize();
618                 return false;
619         }
620
621         pSvc = NULL;
622
623         /* Connect to DCOM server */
624         hres = pLoc->ConnectServer(_bstr_t(L"ROOT\\CIMV2"), NULL, NULL, 0, NULL, 0, 0, &pSvc);
625     
626         /* That didn't work, maybe no kittens found to kill? */
627         if (FAILED(hres))
628         {
629                 pLoc->Release();
630                 CoUninitialize();
631                 return false;
632         }
633
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);
637
638         if (FAILED(hres))
639         {
640                 pSvc->Release();
641                 pLoc->Release();     
642                 CoUninitialize();
643                 return false;
644         }
645         return true;
646 }
647
648 void donewmi()
649 {
650         pSvc->Release();
651         pLoc->Release();
652         CoUninitialize();
653 }
654
655 /* Return the CPU usage in percent of this process */
656 int getcpu()
657 {
658         HRESULT hres;
659
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);
665     
666         /* Query didn't work */
667         if (FAILED(hres))
668                 return -1;
669
670         IWbemClassObject *pclsObj = NULL;
671         ULONG uReturn = 0;
672    
673         /* Iterate the query results */
674         while (pEnumerator)
675         {
676                 VARIANT vtProp;
677                 /* Next item */
678                 HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
679
680                 /* No more items left */
681                 if (uReturn == 0)
682                         break;
683
684                 /* Find process ID */
685                 hr = pclsObj->Get(L"IDProcess", 0, &vtProp, 0, 0);
686                 if (!FAILED(hr))
687                 {
688                         /* Matches our process ID? */
689                         if (vtProp.uintVal == GetCurrentProcessId())
690                         {
691                                 VariantClear(&vtProp);
692                                 /* Get CPU percentage for this process */
693                                 hr = pclsObj->Get(L"PercentProcessorTime", 0, &vtProp, 0, 0);
694                                 if (!FAILED(hr))
695                                 {
696                                         /* Deal with wide string ickyness. Who in their right
697                                          * mind puts a number in a bstrVal wide string item?!
698                                          */
699                                         VariantClear(&vtProp);
700                                         int cpu = 0;
701                                         std::wstringstream out(vtProp.bstrVal);
702                                         out >> cpu;
703                                         pEnumerator->Release();
704                                         pclsObj->Release();
705                                         return cpu;
706                                 }
707                         }
708                 }
709         }
710         pEnumerator->Release();
711         pclsObj->Release();
712         return -1;
713 }
714
715 void usleep(unsigned long usecs)
716 {
717         if (usecs > 0UL)
718         {
719                 unsigned long millis = ((usecs + 999UL) / 1000UL);
720                 SleepEx(millis, false);
721         }
722 }