]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - win/inspircd_win32wrapper.cpp
No names for the service specific errors, probably wont ever name them as theyre...
[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 char * strtok_r(char *_String, const char *_Control, char **_Context)
95 {
96         unsigned char *str;
97         const unsigned char *ctl = (const unsigned char*)_Control;
98         unsigned char map[32];
99
100         if (_Context == 0 || !_Control)
101                 return 0;
102
103         if (!(_String != NULL || *_Context != NULL))
104                 return 0;
105
106         memset(map, 0, 32);
107
108         do {
109                 map[*ctl >> 3] |= (1 << (*ctl & 7));
110         } while (*ctl++);
111
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) */
115         if (_String != NULL)
116         {
117                 str = (unsigned char*)_String;
118         }
119         else
120         {
121                 str = (unsigned char*)*_Context;
122         }
123
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)
128         {
129                 str++;
130         }
131
132         _String = (char*)str;
133
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++ )
137         {
138                 if (map[*str >> 3] & (1 << (*str & 7)))
139                 {
140                         *str++ = 0;
141                         break;
142                 }
143         }
144
145         /* Update context */
146         *_Context = (char*)str;
147
148         /* Determine if a token has been found. */
149         if (_String == (char*)str)
150         {
151                 return NULL;
152         }
153         else
154         {
155                 return _String;
156         }
157 }
158
159 void setcolor(int color_code)
160 {
161         SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color_code);
162 }
163
164 DIR * opendir(const char * path)
165 {
166         std::string search_path = string(path) + "\\*.*";
167         WIN32_FIND_DATA fd;
168         HANDLE f = FindFirstFile(search_path.c_str(), &fd);
169         if (f != INVALID_HANDLE_VALUE)
170         {
171                 DIR * d = new DIR;
172                 memcpy(&d->find_data, &fd, sizeof(WIN32_FIND_DATA));
173                 d->find_handle = f;
174                 d->first = true;
175                 return d;
176         }
177         else
178         {
179                 return 0;
180         }
181 }
182
183 dirent * readdir(DIR * handle)
184 {
185         if (handle->first)
186                 handle->first = false;
187         else
188         {
189                 if (!FindNextFile(handle->find_handle, &handle->find_data))
190                         return 0;
191         }
192
193         strncpy(handle->dirent_pointer.d_name, handle->find_data.cFileName, MAX_PATH);
194         return &handle->dirent_pointer;
195 }
196
197 void closedir(DIR * handle)
198 {
199         FindClose(handle->find_handle);
200         delete handle;
201 }
202
203 const char * dlerror()
204 {
205         static char errormessage[500];
206         DWORD error = GetLastError();
207         SetLastError(0);
208         if (error == 0)
209                 return 0;
210
211         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)errormessage, 500, 0);
212         return errormessage;
213 }
214
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
221
222 /* Handles colors in printf */
223 int printf_c(const char * format, ...)
224 {
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];
228         int color1, color2;
229
230         /* parse arguments */
231         va_list ap;
232         va_start(ap, format);
233         vsnprintf(message, 500, format, ap);
234         va_end(ap);
235
236         /* search for unix-style escape sequences */
237         int t;
238         int c = 0;
239         const char * p = message;
240         while (*p != 0)
241         {
242                 if (*p == '\033')
243                 {
244                         // Escape sequence -> copy into the temp buffer, and parse the color.
245                         p++;
246                         t = 0;
247                         while ((*p) && (*p != 'm'))
248                         {
249                                 temp[t++] = *p;
250                                 ++p;
251                         }
252
253                         temp[t] = 0;
254                         p++;
255
256                         if (*temp == '[')
257                         {
258                                 if (sscanf(temp, "[%u;%u", &color1, &color2) == 2)
259                                 {
260                                         switch(color2)
261                                         {
262                                         case 32:                // Green
263                                                 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN | FOREGROUND_INTENSITY);              // Yellow
264                                                 break;
265
266                                         default:                // Unknown
267                                                 // White
268                                                 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
269                                                 break;
270                                         }
271                                 }
272                                 else
273                                 {
274                                         switch (*(temp+1))
275                                         {
276                                                 case '0':
277                                                         // Returning to normal colour.
278                                                         SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
279                                                         break;
280
281                                                 case '1':
282                                                         // White
283                                                         SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), TWHITE);
284                                                         break;
285
286                                                 default:
287                                                         char message[50];
288                                                         sprintf(message, "Unknown color code: %s", temp);
289                                                         MessageBox(0, message, message, MB_OK);
290                                                         break;
291                                         }
292                                 }
293                         }
294                 }
295
296                 putchar(*p);
297                 ++c;
298                 ++p;
299         }
300
301         return c;
302 }
303
304 int arg_counter = 1;
305 char optarg[514];
306 int getopt_long_only(int ___argc, char *const *___argv, const char *__shortopts, const struct option *__longopts, int *__longind)
307 {
308         // burlex todo: handle the shortops, at the moment it only works with longopts.
309
310         if (___argc == 1 || arg_counter == ___argc)                     // No arguments (apart from filename)
311                 return -1;
312
313         const char * opt = ___argv[arg_counter];
314
315         // if we're not an option, return an error.
316         if (strnicmp(opt, "--", 2) != 0)
317                 return 1;
318         else
319                 opt += 2;
320
321
322         // parse argument list
323         int i = 0;
324         for (; __longopts[i].name != 0; ++i)
325         {
326                 if (!strnicmp(__longopts[i].name, opt, strlen(__longopts[i].name)))
327                 {
328                         // woot, found a valid argument =)
329                         char * par = 0;
330                         if ((arg_counter + 1) != ___argc)
331                         {
332                                 // grab the parameter from the next argument (if its not another argument)
333                                 if (strnicmp(___argv[arg_counter+1], "--", 2) != 0)
334                                 {
335                                         arg_counter++;          // Trash this next argument, we won't be needing it.
336                                         par = ___argv[arg_counter];
337                                 }
338                         }                       
339
340                         // increment the argument for next time
341                         arg_counter++;
342
343                         // determine action based on type
344                         if (__longopts[i].has_arg == required_argument && !par)
345                         {
346                                 // parameter missing and its a required parameter option
347                                 return 1;
348                         }
349
350                         // store argument in optarg
351                         if (par)
352                                 strncpy(optarg, par, 514);
353
354                         if (__longopts[i].flag != 0)
355                         {
356                                 // this is a variable, we have to set it if this argument is found.
357                                 *__longopts[i].flag = 1;
358                                 return 0;
359                         }
360                         else
361                         {
362                                 if (__longopts[i].val == -1 || par == 0)
363                                         return 1;
364                                 
365                                 return __longopts[i].val;
366                         }                       
367                         break;
368                 }
369         }
370
371         // return 1 (invalid argument)
372         return 1;
373 }
374
375 /*void IPC::Check()
376 {
377         if (hIPCPipe == INVALID_HANDLE_VALUE)
378                 return;
379
380         DWORD bytes;
381         DWORD action;
382
383         BOOL res = ReadFile(hIPCPipe, &action, sizeof(DWORD), &bytes, 0);
384         if (!res)
385         {
386                 if (GetLastError() != ERROR_SEM_TIMEOUT)
387                         Instance->Logs->Log("win32",DEFAULT, "IPC Pipe Error %u: %s", GetLastError(), dlerror());
388                 return;
389         }
390
391         switch (action)
392         {
393                 case IPC_MESSAGE_REHASH:
394                         Instance->Rehash("due to IPC message");
395                 break;
396                 
397                 case IPC_MESSAGE_DIE:
398                         Instance->Exit(0);
399                 break;
400
401                 case IPC_MESSAGE_RESTART:
402                         Instance->Restart("IPC_MESSAGE_RESTART received by mailslot.");
403                 break;
404         }
405 }*/
406
407
408 /* These three functions were created from looking at how ares does it
409  * (...and they look far tidier in C++)
410  */
411
412 /* Get active nameserver */
413 bool GetNameServer(HKEY regkey, const char *key, char* &output)
414 {
415         DWORD size = 0;
416         DWORD result = RegQueryValueEx(regkey, key, 0, NULL, NULL, &size);
417         if (((result != ERROR_SUCCESS) && (result != ERROR_MORE_DATA)) || (!size))
418                 return false;
419
420         output = new char[size+1];
421
422         if ((RegQueryValueEx(regkey, key, 0, NULL, (LPBYTE)output, &size) != ERROR_SUCCESS) || (!*output))
423         {
424                 delete output;
425                 return false;
426         }
427         return true;
428 }
429
430 /* Check a network interface for its nameserver */
431 bool GetInterface(HKEY regkey, const char *key, char* &output)
432 {
433         char buf[39];
434         DWORD size = 39;
435         int idx = 0;
436         HKEY top;
437
438         while (RegEnumKeyEx(regkey, idx++, buf, &size, 0, NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
439         {
440                 size = 39;
441                 if (RegOpenKeyEx(regkey, buf, 0, KEY_QUERY_VALUE, &top) != ERROR_SUCCESS)
442                         continue;
443                 int rc = GetNameServer(top, key, output);
444                 RegCloseKey(top);
445                 if (rc)
446                         return true;
447         }
448         return false;
449 }
450
451
452 std::string FindNameServerWin()
453 {
454         std::string returnval = "127.0.0.1";
455         HKEY top, key;
456         char* dns = NULL;
457
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)
460         {
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)))
465                 {
466                         if (dns)
467                         {
468                                 returnval = dns;
469                                 delete dns;
470                         }
471                 }
472                 RegCloseKey(key);
473                 RegCloseKey(top);
474         }
475         return returnval;
476 }
477
478
479 void ClearConsole()
480 {
481         COORD coordScreen = { 0, 0 };    /* here's where we'll home the cursor */
482         HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
483         DWORD cCharsWritten;
484         CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */ 
485         DWORD dwConSize;                 /* number of character cells in the current buffer */ 
486
487         /* get the number of character cells in the current buffer */ 
488
489         if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
490         {
491                 dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
492                 /* fill the entire screen with blanks */ 
493                 if (FillConsoleOutputCharacter( hConsole, (TCHAR) ' ', dwConSize, coordScreen, &cCharsWritten ))
494                 {
495                         /* get the current text attribute */ 
496                         if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
497                         {
498                                 /* now set the buffer's attributes accordingly */
499                                 if (FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten ))
500                                 {
501                                         /* put the cursor at (0, 0) */
502                                         SetConsoleCursorPosition( hConsole, coordScreen );
503                                 }
504                         }
505                 }
506         }
507         return;
508 }
509
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.
512  */
513 void ChangeWindowsSpecificPointers(InspIRCd* Instance)
514 {
515         Instance->Logs->Log("win32",DEBUG,"Changing to windows specific pointer and functor set");
516         Instance->Config->DNSServerValidator = &ValidateWindowsDnsServer;
517 }
518
519 DWORD WindowsForkStart(InspIRCd* Instance)
520 {
521         /* Windows implementation of fork() :P */
522         if (owner_processid)
523                 return 0;
524
525         char module[MAX_PATH];
526         if(!GetModuleFileName(NULL, module, MAX_PATH))
527         {
528                 printf("GetModuleFileName() failed.\n");
529                 return false;
530         }
531
532         STARTUPINFO startupinfo;
533         PROCESS_INFORMATION procinfo;
534         ZeroMemory(&startupinfo, sizeof(STARTUPINFO));
535         ZeroMemory(&procinfo, sizeof(PROCESS_INFORMATION));
536
537         // Fill in the startup info struct
538         GetStartupInfo(&startupinfo);
539
540         /* Default creation flags create the processes suspended */
541         DWORD startupflags = CREATE_SUSPENDED;
542
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.
546          */
547         OSVERSIONINFO vi;
548         vi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
549         GetVersionEx(&vi);
550         if ((vi.dwMajorVersion >= 5) && (vi.dwMinorVersion > 0))
551                 startupflags |= CREATE_PRESERVE_CODE_AUTHZ_LEVEL;
552
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.
565                 0,                              // ENVIRONMENT
566                 0,                              // CURRENT_DIRECTORY
567                 &startupinfo,                   // startup info
568                 &procinfo);                     // process info
569
570         if(!bSuccess)
571         {
572                 printf("CreateProcess() error: %s\n", dlerror());
573                 return false;
574         }
575
576         // Set the owner process id in the target process.
577         SIZE_T written = 0;
578         DWORD pid = GetCurrentProcessId();
579         if(!WriteProcessMemory(procinfo.hProcess, &owner_processid, &pid, sizeof(DWORD), &written) || written != sizeof(DWORD))
580         {
581                 printf("WriteProcessMemory() failed: %s\n", dlerror());
582                 return false;
583         }
584
585         // Resume the other thread (let it start)
586         ResumeThread(procinfo.hThread);
587
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);
590
591         // If we hit this it means startup failed, default to 14 if this fails.
592         DWORD ExitCode = 14;
593         GetExitCodeProcess(procinfo.hProcess, &ExitCode);
594         CloseHandle(procinfo.hThread);
595         CloseHandle(procinfo.hProcess);
596         return ExitCode;
597 }
598
599 void WindowsForkKillOwner(InspIRCd * Instance)
600 {
601         HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, owner_processid);
602         if(!hProcess || !owner_processid)
603         {
604                 printf("Could not open process id %u: %s.\n", owner_processid, dlerror());
605                 Instance->Exit(14);
606         }
607
608         // die die die
609         if(!TerminateProcess(hProcess, 0))
610         {
611                 printf("Could not TerminateProcess(): %s\n", dlerror());
612                 Instance->Exit(14);
613         }
614
615         CloseHandle(hProcess);
616 }
617
618 bool ValidateWindowsDnsServer(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
619 {
620         if (!*(data.GetString()))
621         {
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.
627                  */
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.
632                  */
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());
637         }
638         return true;
639 }
640
641 int gettimeofday(struct timeval * tv, void * tz)
642 {
643         if(tv == NULL)
644                 return -1;
645
646         DWORD mstime = timeGetTime();
647         tv->tv_sec   = time(NULL);
648         tv->tv_usec  = (mstime - (tv->tv_sec * 1000)) * 1000;
649         return 0;       
650 }
651
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.
656  */
657 bool initwmi()
658 {
659         HRESULT hres;
660
661         /* Initialise COM. This can kill babies. */
662         hres =  CoInitializeEx(0, COINIT_MULTITHREADED); 
663         if (FAILED(hres))
664                 return false;
665
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);
669
670         if (FAILED(hres))
671         {
672                 CoUninitialize();
673                 return false;
674         }
675     
676         /* Instance to COM object */
677         pLoc = NULL;
678         hres = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID*)&pLoc);
679  
680         if (FAILED(hres))
681         {
682                 CoUninitialize();
683                 return false;
684         }
685
686         pSvc = NULL;
687
688         /* Connect to DCOM server */
689         hres = pLoc->ConnectServer(_bstr_t(L"ROOT\\CIMV2"), NULL, NULL, 0, NULL, 0, 0, &pSvc);
690     
691         /* That didn't work, maybe no kittens found to kill? */
692         if (FAILED(hres))
693         {
694                 pLoc->Release();
695                 CoUninitialize();
696                 return false;
697         }
698
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);
702
703         if (FAILED(hres))
704         {
705                 pSvc->Release();
706                 pLoc->Release();     
707                 CoUninitialize();
708                 return false;
709         }
710         return true;
711 }
712
713 void donewmi()
714 {
715         pSvc->Release();
716         pLoc->Release();
717         CoUninitialize();
718 }
719
720 /* Return the CPU usage in percent of this process */
721 int getcpu()
722 {
723         HRESULT hres;
724
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);
730     
731         /* Query didn't work */
732         if (FAILED(hres))
733                 return -1;
734
735         IWbemClassObject *pclsObj = NULL;
736         ULONG uReturn = 0;
737    
738         /* Iterate the query results */
739         while (pEnumerator)
740         {
741                 VARIANT vtProp;
742                 /* Next item */
743                 HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
744
745                 /* No more items left */
746                 if (uReturn == 0)
747                         break;
748
749                 /* Find process ID */
750                 hr = pclsObj->Get(L"IDProcess", 0, &vtProp, 0, 0);
751                 if (!FAILED(hr))
752                 {
753                         /* Matches our process ID? */
754                         if (vtProp.uintVal == GetCurrentProcessId())
755                         {
756                                 VariantClear(&vtProp);
757                                 /* Get CPU percentage for this process */
758                                 hr = pclsObj->Get(L"PercentProcessorTime", 0, &vtProp, 0, 0);
759                                 if (!FAILED(hr))
760                                 {
761                                         /* Deal with wide string ickyness. Who in their right
762                                          * mind puts a number in a bstrVal wide string item?!
763                                          */
764                                         VariantClear(&vtProp);
765                                         int cpu = 0;
766                                         std::wstringstream out(vtProp.bstrVal);
767                                         out >> cpu;
768                                         pEnumerator->Release();
769                                         pclsObj->Release();
770                                         return cpu;
771                                 }
772                         }
773                 }
774         }
775         pEnumerator->Release();
776         pclsObj->Release();
777         return -1;
778 }