]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - win/inspircd_win32wrapper.cpp
* Fix inspsocket to not include uio.h on windows.
[user/henk/code/inspircd.git] / win / inspircd_win32wrapper.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2009 InspIRCd Development Team
6  * See: http://wiki.inspircd.org/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 *insp_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 insp_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 ssize_t writev(int fd, const struct iovec* iov, int iovcnt)
151 {
152     ssize_t ret;
153     size_t tot = 0;
154     int i;
155     char *buf, *p;
156
157     for(i = 0; i < iovcnt; ++i)
158         tot += iov[i].iov_len;
159     buf = (char*)malloc(tot);
160     if (tot != 0 && buf == NULL) {
161         errno = ENOMEM;
162         return -1;
163     }
164     p = buf;
165     for (i = 0; i < iovcnt; ++i) {
166         memcpy (p, iov[i].iov_base, iov[i].iov_len);
167         p += iov[i].iov_len;
168     }
169     ret = send((SOCKET)fd, buf, tot, 0);
170     free (buf);
171     return ret;
172 }
173
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
180
181 /* Handles colors in printf */
182 int printf_c(const char * format, ...)
183 {
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];
187         int color1, color2;
188
189         /* parse arguments */
190         va_list ap;
191         va_start(ap, format);
192         vsnprintf(message, 500, format, ap);
193         va_end(ap);
194
195         /* search for unix-style escape sequences */
196         int t;
197         int c = 0;
198         const char * p = message;
199         while (*p != 0)
200         {
201                 if (*p == '\033')
202                 {
203                         // Escape sequence -> copy into the temp buffer, and parse the color.
204                         p++;
205                         t = 0;
206                         while ((*p) && (*p != 'm'))
207                         {
208                                 temp[t++] = *p;
209                                 ++p;
210                         }
211
212                         temp[t] = 0;
213                         p++;
214
215                         if (*temp == '[')
216                         {
217                                 if (sscanf(temp, "[%u;%u", &color1, &color2) == 2)
218                                 {
219                                         switch(color2)
220                                         {
221                                         case 32:                // Green
222                                                 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN | FOREGROUND_INTENSITY);              // Yellow
223                                                 break;
224
225                                         default:                // Unknown
226                                                 // White
227                                                 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
228                                                 break;
229                                         }
230                                 }
231                                 else
232                                 {
233                                         switch (*(temp+1))
234                                         {
235                                                 case '0':
236                                                         // Returning to normal colour.
237                                                         SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
238                                                         break;
239
240                                                 case '1':
241                                                         // White
242                                                         SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), TWHITE);
243                                                         break;
244
245                                                 default:
246                                                         char message[50];
247                                                         sprintf(message, "Unknown color code: %s", temp);
248                                                         MessageBox(0, message, message, MB_OK);
249                                                         break;
250                                         }
251                                 }
252                         }
253                 }
254
255                 putchar(*p);
256                 ++c;
257                 ++p;
258         }
259
260         return c;
261 }
262
263 int optind = 1;
264 char optarg[514];
265 int getopt_long_only(int ___argc, char *const *___argv, const char *__shortopts, const struct option *__longopts, int *__longind)
266 {
267         // burlex todo: handle the shortops, at the moment it only works with longopts.
268
269         if (___argc == 1 || optind == ___argc)                  // No arguments (apart from filename)
270                 return -1;
271
272         const char * opt = ___argv[optind];
273         optind++;
274
275         // if we're not an option, return an error.
276         if (strnicmp(opt, "--", 2) != 0)
277                 return 1;
278         else
279                 opt += 2;
280
281
282         // parse argument list
283         int i = 0;
284         for (; __longopts[i].name != 0; ++i)
285         {
286                 if (!strnicmp(__longopts[i].name, opt, strlen(__longopts[i].name)))
287                 {
288                         // woot, found a valid argument =)
289                         char * par = 0;
290                         if ((optind) != ___argc)
291                         {
292                                 // grab the parameter from the next argument (if its not another argument)
293                                 if (strnicmp(___argv[optind], "--", 2) != 0)
294                                 {
295 //                                      optind++;               // Trash this next argument, we won't be needing it.
296                                         par = ___argv[optind-1];
297                                 }
298                         }                       
299
300                         // increment the argument for next time
301 //                      optind++;
302
303                         // determine action based on type
304                         if (__longopts[i].has_arg == required_argument && !par)
305                         {
306                                 // parameter missing and its a required parameter option
307                                 return 1;
308                         }
309
310                         // store argument in optarg
311                         if (par)
312                                 strncpy(optarg, par, 514);
313
314                         if (__longopts[i].flag != 0)
315                         {
316                                 // this is a variable, we have to set it if this argument is found.
317                                 *__longopts[i].flag = 1;
318                                 return 0;
319                         }
320                         else
321                         {
322                                 if (__longopts[i].val == -1 || par == 0)
323                                         return 1;
324                                 
325                                 return __longopts[i].val;
326                         }                       
327                         break;
328                 }
329         }
330
331         // return 1 (invalid argument)
332         return 1;
333 }
334
335 /* These three functions were created from looking at how ares does it
336  * (...and they look far tidier in C++)
337  */
338
339 /* Get active nameserver */
340 bool GetNameServer(HKEY regkey, const char *key, char* &output)
341 {
342         DWORD size = 0;
343         DWORD result = RegQueryValueEx(regkey, key, 0, NULL, NULL, &size);
344         if (((result != ERROR_SUCCESS) && (result != ERROR_MORE_DATA)) || (!size))
345                 return false;
346
347         output = new char[size+1];
348
349         if ((RegQueryValueEx(regkey, key, 0, NULL, (LPBYTE)output, &size) != ERROR_SUCCESS) || (!*output))
350         {
351                 delete output;
352                 return false;
353         }
354         return true;
355 }
356
357 /* Check a network interface for its nameserver */
358 bool GetInterface(HKEY regkey, const char *key, char* &output)
359 {
360         char buf[39];
361         DWORD size = 39;
362         int idx = 0;
363         HKEY top;
364
365         while (RegEnumKeyEx(regkey, idx++, buf, &size, 0, NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
366         {
367                 size = 39;
368                 if (RegOpenKeyEx(regkey, buf, 0, KEY_QUERY_VALUE, &top) != ERROR_SUCCESS)
369                         continue;
370                 int rc = GetNameServer(top, key, output);
371                 RegCloseKey(top);
372                 if (rc)
373                         return true;
374         }
375         return false;
376 }
377
378
379 std::string FindNameServerWin()
380 {
381         std::string returnval = "127.0.0.1";
382         HKEY top, key;
383         char* dns = NULL;
384
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)
387         {
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)))
392                 {
393                         if (dns)
394                         {
395                                 returnval = dns;
396                                 delete dns;
397                         }
398                 }
399                 RegCloseKey(key);
400                 RegCloseKey(top);
401         }
402         return returnval;
403 }
404
405
406 void ClearConsole()
407 {
408         COORD coordScreen = { 0, 0 };    /* here's where we'll home the cursor */
409         HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
410         DWORD cCharsWritten;
411         CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */ 
412         DWORD dwConSize;                 /* number of character cells in the current buffer */ 
413
414         /* get the number of character cells in the current buffer */ 
415
416         if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
417         {
418                 dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
419                 /* fill the entire screen with blanks */ 
420                 if (FillConsoleOutputCharacter( hConsole, (TCHAR) ' ', dwConSize, coordScreen, &cCharsWritten ))
421                 {
422                         /* get the current text attribute */ 
423                         if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
424                         {
425                                 /* now set the buffer's attributes accordingly */
426                                 if (FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten ))
427                                 {
428                                         /* put the cursor at (0, 0) */
429                                         SetConsoleCursorPosition( hConsole, coordScreen );
430                                 }
431                         }
432                 }
433         }
434         return;
435 }
436
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.
439  */
440 void ChangeWindowsSpecificPointers()
441 {
442         ServerInstance->Logs->Log("win32",DEBUG,"Changing to windows specific pointer and functor set");
443 }
444
445 DWORD WindowsForkStart()
446 {
447         /* Windows implementation of fork() :P */
448         if (owner_processid)
449                 return 0;
450
451         char module[MAX_PATH];
452         if(!GetModuleFileName(NULL, module, MAX_PATH))
453         {
454                 printf("GetModuleFileName() failed.\n");
455                 return false;
456         }
457
458         STARTUPINFO startupinfo;
459         PROCESS_INFORMATION procinfo;
460         ZeroMemory(&startupinfo, sizeof(STARTUPINFO));
461         ZeroMemory(&procinfo, sizeof(PROCESS_INFORMATION));
462
463         // Fill in the startup info struct
464         GetStartupInfo(&startupinfo);
465
466         /* Default creation flags create the processes suspended */
467         DWORD startupflags = CREATE_SUSPENDED;
468
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.
472          */
473         OSVERSIONINFO vi;
474         vi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
475         GetVersionEx(&vi);
476         if ((vi.dwMajorVersion >= 5) && (vi.dwMinorVersion > 0))
477                 startupflags |= CREATE_PRESERVE_CODE_AUTHZ_LEVEL;
478
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.
491                 0,                              // ENVIRONMENT
492                 0,                              // CURRENT_DIRECTORY
493                 &startupinfo,                   // startup info
494                 &procinfo);                     // process info
495
496         if(!bSuccess)
497         {
498                 printf("CreateProcess() error: %s\n", dlerror());
499                 return false;
500         }
501
502         // Set the owner process id in the target process.
503         SIZE_T written = 0;
504         DWORD pid = GetCurrentProcessId();
505         if(!WriteProcessMemory(procinfo.hProcess, &owner_processid, &pid, sizeof(DWORD), &written) || written != sizeof(DWORD))
506         {
507                 printf("WriteProcessMemory() failed: %s\n", dlerror());
508                 return false;
509         }
510
511         // Resume the other thread (let it start)
512         ResumeThread(procinfo.hThread);
513
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);
516
517         // If we hit this it means startup failed, default to 14 if this fails.
518         DWORD ExitCode = 14;
519         GetExitCodeProcess(procinfo.hProcess, &ExitCode);
520         CloseHandle(procinfo.hThread);
521         CloseHandle(procinfo.hProcess);
522         return ExitCode;
523 }
524
525 void WindowsForkKillOwner()
526 {
527         HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, owner_processid);
528         if(!hProcess || !owner_processid)
529         {
530                 printf("Could not open process id %u: %s.\n", owner_processid, dlerror());
531                 ServerInstance->Exit(14);
532         }
533
534         // die die die
535         if(!TerminateProcess(hProcess, 0))
536         {
537                 printf("Could not TerminateProcess(): %s\n", dlerror());
538                 ServerInstance->Exit(14);
539         }
540
541         CloseHandle(hProcess);
542 }
543
544 bool ValidateDnsServer(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
545 {
546         if (!*(data.GetString()))
547         {
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.
553                  */
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.
558                  */
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());
563         }
564         return true;
565 }
566
567 int gettimeofday(struct timeval * tv, void * tz)
568 {
569         if(tv == NULL)
570                 return -1;
571
572         DWORD mstime = timeGetTime();
573         tv->tv_sec   = time(NULL);
574         tv->tv_usec  = (mstime - (tv->tv_sec * 1000)) * 1000;
575         return 0;       
576 }
577
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.
582  */
583 bool initwmi()
584 {
585         HRESULT hres;
586
587         /* Initialise COM. This can kill babies. */
588         hres =  CoInitializeEx(0, COINIT_MULTITHREADED); 
589         if (FAILED(hres))
590                 return false;
591
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);
595
596         if (FAILED(hres))
597         {
598                 CoUninitialize();
599                 return false;
600         }
601     
602         /* Instance to COM object */
603         pLoc = NULL;
604         hres = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID*)&pLoc);
605  
606         if (FAILED(hres))
607         {
608                 CoUninitialize();
609                 return false;
610         }
611
612         pSvc = NULL;
613
614         /* Connect to DCOM server */
615         hres = pLoc->ConnectServer(_bstr_t(L"ROOT\\CIMV2"), NULL, NULL, 0, NULL, 0, 0, &pSvc);
616     
617         /* That didn't work, maybe no kittens found to kill? */
618         if (FAILED(hres))
619         {
620                 pLoc->Release();
621                 CoUninitialize();
622                 return false;
623         }
624
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);
628
629         if (FAILED(hres))
630         {
631                 pSvc->Release();
632                 pLoc->Release();     
633                 CoUninitialize();
634                 return false;
635         }
636         return true;
637 }
638
639 void donewmi()
640 {
641         pSvc->Release();
642         pLoc->Release();
643         CoUninitialize();
644 }
645
646 /* Return the CPU usage in percent of this process */
647 int getcpu()
648 {
649         HRESULT hres;
650         int cpu = -1;
651
652         /* Use WQL, similar to SQL, to construct a query that lists the cpu usage and pid of all processes */
653         IEnumWbemClassObject* pEnumerator = NULL;
654
655         BSTR Language = SysAllocString(L"WQL");
656         BSTR Query    = SysAllocString(L"Select PercentProcessorTime,IDProcess from Win32_PerfFormattedData_PerfProc_Process");
657
658         hres = pSvc->ExecQuery(Language, Query, WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
659
660         /* Query didn't work */
661         if (!FAILED(hres))
662         {
663                 IWbemClassObject *pclsObj = NULL;
664                 ULONG uReturn = 0;
665
666                 /* Iterate the query results */
667                 while (pEnumerator)
668                 {
669                         VARIANT vtProp;
670                         /* Next item */
671                         HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
672
673                         /* No more items left */
674                         if (uReturn == 0)
675                                 break;
676
677                         /* Find process ID */
678                         hr = pclsObj->Get(L"IDProcess", 0, &vtProp, 0, 0);
679                         if (!FAILED(hr))
680                         {
681                                 /* Matches our process ID? */
682                                 if (vtProp.uintVal == GetCurrentProcessId())
683                                 {
684                                         VariantClear(&vtProp);
685                                         /* Get CPU percentage for this process */
686                                         hr = pclsObj->Get(L"PercentProcessorTime", 0, &vtProp, 0, 0);
687                                         if (!FAILED(hr))
688                                         {
689                                                 /* Deal with wide string ickyness. Who in their right
690                                                  * mind puts a number in a bstrVal wide string item?!
691                                                  */
692                                                 VariantClear(&vtProp);
693                                                 cpu = 0;
694                                                 std::wstringstream out(vtProp.bstrVal);
695                                                 out >> cpu;
696                                                 break;
697                                         }
698                                 }
699                         }
700                 }
701
702                 pEnumerator->Release();
703                 pclsObj->Release();
704         }
705
706         SysFreeString(Language);
707         SysFreeString(Query);
708
709         return cpu;
710 }