]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - win/inspircd_win32wrapper.cpp
Fixed Windows build
[user/henk/code/inspircd.git] / win / inspircd_win32wrapper.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
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>
11  *
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.
15  *
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
19  * details.
20  *
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/>.
23  */
24
25
26 #include "inspircd_win32wrapper.h"
27 #include "inspircd.h"
28 #include "configreader.h"
29 #include <string>
30 #include <errno.h>
31 #include <assert.h>
32 #define _WIN32_DCOM
33 #include <comdef.h>
34 #include <Wbemidl.h>
35
36 #pragma comment(lib, "wbemuuid.lib")
37 #pragma comment(lib, "comsuppwd.lib")
38 #pragma comment(lib, "winmm.lib")
39 using namespace std;
40
41 #ifndef INADDR_NONE
42 #define INADDR_NONE 0xffffffff
43 #endif
44
45 #include <mmsystem.h>
46
47 IWbemLocator *pLoc = NULL;
48 IWbemServices *pSvc = NULL;
49
50 /* This MUST remain static and delcared outside the class, so that WriteProcessMemory can reference it properly */
51 static DWORD owner_processid = 0;
52
53
54 int inet_aton(const char *cp, struct in_addr *addr)
55 {
56         unsigned long ip = inet_addr(cp);
57         addr->s_addr = ip;
58         return (addr->s_addr == INADDR_NONE) ? 0 : 1;
59 }
60
61 const char *insp_inet_ntop(int af, const void *src, char *dst, socklen_t cnt)
62 {
63
64         if (af == AF_INET)
65         {
66                 struct sockaddr_in in;
67                 memset(&in, 0, sizeof(in));
68                 in.sin_family = AF_INET;
69                 memcpy(&in.sin_addr, src, sizeof(struct in_addr));
70                 getnameinfo((struct sockaddr *)&in, sizeof(struct sockaddr_in), dst, cnt, NULL, 0, NI_NUMERICHOST);
71                 return dst;
72         }
73         else if (af == AF_INET6)
74         {
75                 struct sockaddr_in6 in;
76                 memset(&in, 0, sizeof(in));
77                 in.sin6_family = AF_INET6;
78                 memcpy(&in.sin6_addr, src, sizeof(struct in_addr6));
79                 getnameinfo((struct sockaddr *)&in, sizeof(struct sockaddr_in6), dst, cnt, NULL, 0, NI_NUMERICHOST);
80                 return dst;
81         }
82         return NULL;
83 }
84
85 int geteuid()
86 {
87         return 1;
88 }
89
90 int insp_inet_pton(int af, const char *src, void *dst)
91 {
92         sockaddr_in sa;
93         int len = sizeof(SOCKADDR);
94         int rv = WSAStringToAddress((LPSTR)src, af, NULL, (LPSOCKADDR)&sa, &len);
95         if(rv >= 0)
96         {
97                 if(WSAGetLastError() == 10022)                  // Invalid Argument
98                         rv = 0;
99                 else
100                         rv = 1;
101         }
102         memcpy(dst, &sa.sin_addr, sizeof(struct in_addr));
103         return rv;
104 }
105
106 void setcolor(int color_code)
107 {
108         SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color_code);
109 }
110
111 DIR * opendir(const char * path)
112 {
113         std::string search_path = string(path) + "\\*.*";
114         WIN32_FIND_DATA fd;
115         HANDLE f = FindFirstFile(search_path.c_str(), &fd);
116         if (f != INVALID_HANDLE_VALUE)
117         {
118                 DIR * d = new DIR;
119                 memcpy(&d->find_data, &fd, sizeof(WIN32_FIND_DATA));
120                 d->find_handle = f;
121                 d->first = true;
122                 return d;
123         }
124         else
125         {
126                 return 0;
127         }
128 }
129
130 dirent * readdir(DIR * handle)
131 {
132         if (handle->first)
133                 handle->first = false;
134         else
135         {
136                 if (!FindNextFile(handle->find_handle, &handle->find_data))
137                         return 0;
138         }
139
140         strncpy(handle->dirent_pointer.d_name, handle->find_data.cFileName, MAX_PATH);
141         return &handle->dirent_pointer;
142 }
143
144 void closedir(DIR * handle)
145 {
146         FindClose(handle->find_handle);
147         delete handle;
148 }
149
150 const char * dlerror()
151 {
152         static char errormessage[500];
153         DWORD error = GetLastError();
154         SetLastError(0);
155         if (error == 0)
156                 return 0;
157
158         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)errormessage, 500, 0);
159         return errormessage;
160 }
161
162 #define TRED FOREGROUND_RED | FOREGROUND_INTENSITY
163 #define TGREEN FOREGROUND_GREEN | FOREGROUND_INTENSITY
164 #define TYELLOW FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY
165 #define TNORMAL FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE
166 #define TWHITE TNORMAL | FOREGROUND_INTENSITY
167 #define TBLUE FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY
168
169 /* Handles colors in printf */
170 int printf_c(const char * format, ...)
171 {
172         // Better hope we're not multithreaded, otherwise we'll have chickens crossing the road other side to get the to :P
173         static char message[MAXBUF];
174         static char temp[MAXBUF];
175         int color1, color2;
176
177         /* parse arguments */
178         va_list ap;
179         va_start(ap, format);
180         vsnprintf(message, 500, format, ap);
181         va_end(ap);
182
183         /* search for unix-style escape sequences */
184         int t;
185         int c = 0;
186         const char * p = message;
187         while (*p != 0)
188         {
189                 if (*p == '\033')
190                 {
191                         // Escape sequence -> copy into the temp buffer, and parse the color.
192                         p++;
193                         t = 0;
194                         while ((*p) && (*p != 'm'))
195                         {
196                                 temp[t++] = *p;
197                                 ++p;
198                         }
199
200                         temp[t] = 0;
201                         p++;
202
203                         if (*temp == '[')
204                         {
205                                 if (sscanf(temp, "[%u;%u", &color1, &color2) == 2)
206                                 {
207                                         switch(color2)
208                                         {
209                                         case 32:                // Green
210                                                 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN | FOREGROUND_INTENSITY);              // Yellow
211                                                 break;
212
213                                         default:                // Unknown
214                                                 // White
215                                                 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
216                                                 break;
217                                         }
218                                 }
219                                 else
220                                 {
221                                         switch (*(temp+1))
222                                         {
223                                                 case '0':
224                                                         // Returning to normal colour.
225                                                         SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
226                                                         break;
227
228                                                 case '1':
229                                                         // White
230                                                         SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), TWHITE);
231                                                         break;
232
233                                                 default:
234                                                         char message[50];
235                                                         sprintf(message, "Unknown color code: %s", temp);
236                                                         MessageBox(0, message, message, MB_OK);
237                                                         break;
238                                         }
239                                 }
240                         }
241                 }
242
243                 putchar(*p);
244                 ++c;
245                 ++p;
246         }
247
248         return c;
249 }
250
251 int optind = 1;
252 char optarg[514];
253 int getopt_long(int ___argc, char *const *___argv, const char *__shortopts, const struct option *__longopts, int *__longind)
254 {
255         // burlex todo: handle the shortops, at the moment it only works with longopts.
256
257         if (___argc == 1 || optind == ___argc)                  // No arguments (apart from filename)
258                 return -1;
259
260         const char * opt = ___argv[optind];
261         optind++;
262
263         // if we're not an option, return an error.
264         if (strnicmp(opt, "--", 2) != 0)
265                 return 1;
266         else
267                 opt += 2;
268
269
270         // parse argument list
271         int i = 0;
272         for (; __longopts[i].name != 0; ++i)
273         {
274                 if (!strnicmp(__longopts[i].name, opt, strlen(__longopts[i].name)))
275                 {
276                         // woot, found a valid argument =)
277                         char * par = 0;
278                         if ((optind) != ___argc)
279                         {
280                                 // grab the parameter from the next argument (if its not another argument)
281                                 if (strnicmp(___argv[optind], "--", 2) != 0)
282                                 {
283 //                                      optind++;               // Trash this next argument, we won't be needing it.
284                                         par = ___argv[optind-1];
285                                 }
286                         }                       
287
288                         // increment the argument for next time
289 //                      optind++;
290
291                         // determine action based on type
292                         if (__longopts[i].has_arg == required_argument && !par)
293                         {
294                                 // parameter missing and its a required parameter option
295                                 return 1;
296                         }
297
298                         // store argument in optarg
299                         if (par)
300                                 strncpy(optarg, par, 514);
301
302                         if (__longopts[i].flag != 0)
303                         {
304                                 // this is a variable, we have to set it if this argument is found.
305                                 *__longopts[i].flag = 1;
306                                 return 0;
307                         }
308                         else
309                         {
310                                 if (__longopts[i].val == -1 || par == 0)
311                                         return 1;
312                                 
313                                 return __longopts[i].val;
314                         }                       
315                         break;
316                 }
317         }
318
319         // return 1 (invalid argument)
320         return 1;
321 }
322
323 /* These three functions were created from looking at how ares does it
324  * (...and they look far tidier in C++)
325  */
326
327 /* Get active nameserver */
328 bool GetNameServer(HKEY regkey, const char *key, char* &output)
329 {
330         DWORD size = 0;
331         DWORD result = RegQueryValueEx(regkey, key, 0, NULL, NULL, &size);
332         if (((result != ERROR_SUCCESS) && (result != ERROR_MORE_DATA)) || (!size))
333                 return false;
334
335         output = new char[size+1];
336
337         if ((RegQueryValueEx(regkey, key, 0, NULL, (LPBYTE)output, &size) != ERROR_SUCCESS) || (!*output))
338         {
339                 delete output;
340                 return false;
341         }
342         return true;
343 }
344
345 /* Check a network interface for its nameserver */
346 bool GetInterface(HKEY regkey, const char *key, char* &output)
347 {
348         char buf[39];
349         DWORD size = 39;
350         int idx = 0;
351         HKEY top;
352
353         while (RegEnumKeyEx(regkey, idx++, buf, &size, 0, NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
354         {
355                 size = 39;
356                 if (RegOpenKeyEx(regkey, buf, 0, KEY_QUERY_VALUE, &top) != ERROR_SUCCESS)
357                         continue;
358                 int rc = GetNameServer(top, key, output);
359                 RegCloseKey(top);
360                 if (rc)
361                         return true;
362         }
363         return false;
364 }
365
366
367 std::string FindNameServerWin()
368 {
369         std::string returnval;
370         HKEY top, key;
371         char* dns = NULL;
372
373         /* Lets see if the correct registry hive and tree exist */
374         if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\Tcpip\\Parameters", 0, KEY_READ, &top) == ERROR_SUCCESS)
375         {
376                 /* If they do, attempt to get the nameserver name */
377                 RegOpenKeyEx(top, "Interfaces", 0, KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &key);
378                 if ((GetNameServer(top, "NameServer", dns)) || (GetNameServer(top, "DhcpNameServer", dns))
379                         || (GetInterface(key, "NameServer", dns)) || (GetInterface(key, "DhcpNameServer", dns)))
380                 {
381                         if (dns)
382                         {
383                                 returnval = dns;
384                                 delete dns;
385                         }
386                 }
387                 RegCloseKey(key);
388                 RegCloseKey(top);
389         }
390         return returnval;
391 }
392
393
394 void ClearConsole()
395 {
396         COORD coordScreen = { 0, 0 };    /* here's where we'll home the cursor */
397         HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
398         DWORD cCharsWritten;
399         CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */ 
400         DWORD dwConSize;                 /* number of character cells in the current buffer */ 
401
402         /* get the number of character cells in the current buffer */ 
403
404         if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
405         {
406                 dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
407                 /* fill the entire screen with blanks */ 
408                 if (FillConsoleOutputCharacter( hConsole, (TCHAR) ' ', dwConSize, coordScreen, &cCharsWritten ))
409                 {
410                         /* get the current text attribute */ 
411                         if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
412                         {
413                                 /* now set the buffer's attributes accordingly */
414                                 if (FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten ))
415                                 {
416                                         /* put the cursor at (0, 0) */
417                                         SetConsoleCursorPosition( hConsole, coordScreen );
418                                 }
419                         }
420                 }
421         }
422         return;
423 }
424
425 /* Many inspircd classes contain function pointers/functors which can be changed to point at platform specific implementations
426  * of code. This function repoints these pointers and functors so that calls are windows specific.
427  */
428 void ChangeWindowsSpecificPointers()
429 {
430         ServerInstance->Logs->Log("win32",DEBUG,"Changing to windows specific pointer and functor set");
431 }
432
433 DWORD WindowsForkStart()
434 {
435         /* Windows implementation of fork() :P */
436         if (owner_processid)
437                 return 0;
438
439         char module[MAX_PATH];
440         if(!GetModuleFileName(NULL, module, MAX_PATH))
441         {
442                 printf("GetModuleFileName() failed.\n");
443                 return false;
444         }
445
446         STARTUPINFO startupinfo;
447         PROCESS_INFORMATION procinfo;
448         ZeroMemory(&startupinfo, sizeof(STARTUPINFO));
449         ZeroMemory(&procinfo, sizeof(PROCESS_INFORMATION));
450
451         // Fill in the startup info struct
452         GetStartupInfo(&startupinfo);
453
454         /* Default creation flags create the processes suspended */
455         DWORD startupflags = CREATE_SUSPENDED;
456
457         /* On windows 2003/XP and above, we can use the value
458          * CREATE_PRESERVE_CODE_AUTHZ_LEVEL which gives more access
459          * to the process which we may require on these operating systems.
460          */
461         OSVERSIONINFO vi;
462         vi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
463         GetVersionEx(&vi);
464         if ((vi.dwMajorVersion >= 5) && (vi.dwMinorVersion > 0))
465                 startupflags |= CREATE_PRESERVE_CODE_AUTHZ_LEVEL;
466
467         // Launch our "forked" process.
468         BOOL bSuccess = CreateProcess ( module, // Module (exe) filename
469                 strdup(GetCommandLine()),       // Command line (exe plus parameters from the OS)
470                                                 // NOTE: We cannot return the direct value of the
471                                                 // GetCommandLine function here, as the pointer is
472                                                 // passed straight to the child process, and will be
473                                                 // invalid once we exit as it goes out of context.
474                                                 // strdup() seems ok, though.
475                 0,                              // PROCESS_SECURITY_ATTRIBUTES
476                 0,                              // THREAD_SECURITY_ATTRIBUTES
477                 TRUE,                           // We went to inherit handles.
478                 startupflags,                   // Allow us full access to the process and suspend it.
479                 0,                              // ENVIRONMENT
480                 0,                              // CURRENT_DIRECTORY
481                 &startupinfo,                   // startup info
482                 &procinfo);                     // process info
483
484         if(!bSuccess)
485         {
486                 printf("CreateProcess() error: %s\n", dlerror());
487                 return false;
488         }
489
490         // Set the owner process id in the target process.
491         SIZE_T written = 0;
492         DWORD pid = GetCurrentProcessId();
493         if(!WriteProcessMemory(procinfo.hProcess, &owner_processid, &pid, sizeof(DWORD), &written) || written != sizeof(DWORD))
494         {
495                 printf("WriteProcessMemory() failed: %s\n", dlerror());
496                 return false;
497         }
498
499         // Resume the other thread (let it start)
500         ResumeThread(procinfo.hThread);
501
502         // 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.
503         WaitForSingleObject(procinfo.hProcess, INFINITE);
504
505         // If we hit this it means startup failed, default to 14 if this fails.
506         DWORD ExitCode = 14;
507         GetExitCodeProcess(procinfo.hProcess, &ExitCode);
508         CloseHandle(procinfo.hThread);
509         CloseHandle(procinfo.hProcess);
510         return ExitCode;
511 }
512
513 void WindowsForkKillOwner()
514 {
515         HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, owner_processid);
516         if(!hProcess || !owner_processid)
517         {
518                 printf("Could not open process id %u: %s.\n", owner_processid, dlerror());
519                 ServerInstance->Exit(14);
520         }
521
522         // die die die
523         if(!TerminateProcess(hProcess, 0))
524         {
525                 printf("Could not TerminateProcess(): %s\n", dlerror());
526                 ServerInstance->Exit(14);
527         }
528
529         CloseHandle(hProcess);
530 }
531
532 void FindDNS(std::string& server)
533 {
534         if (!server.empty())
535                 return;
536
537         ServerInstance->Logs->Log("CONFIG",DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in the registry...");
538         std::string nameserver = FindNameServerWin();
539
540         /* If empty use default to 127.0.0.1 */
541         if (nameserver.empty())
542         {
543                 ServerInstance->Logs->Log("CONFIG",DEFAULT,"No viable nameserver found in registry! Defaulting to nameserver '127.0.0.1'!");
544                 server = "127.0.0.1";
545                 return;
546         }
547
548         /* Windows stacks multiple nameservers in one registry key, seperated by commas.
549          * Spotted by Cataclysm.
550          */
551         if (nameserver.find(',') != std::string::npos)
552                 nameserver = nameserver.substr(0, nameserver.find(','));
553
554         /* Just to be FUCKING AKWARD, windows fister... err i mean vista...
555          * seperates the nameservers with spaces instead.
556          */
557         if (nameserver.find(' ') != std::string::npos)
558                 nameserver = nameserver.substr(0, nameserver.find(' '));
559
560         server = nameserver;
561         ServerInstance->Logs->Log("CONFIG",DEFAULT,"<dns:server> set to '%s' as first active resolver in registry.", nameserver.c_str());
562 }
563
564 int clock_gettime(int clock, struct timespec * tv)
565 {
566         if(tv == NULL)
567                 return -1;
568
569         DWORD mstime = timeGetTime();
570         tv->tv_sec   = time(NULL);
571         tv->tv_nsec  = (mstime - (tv->tv_sec * 1000)) * 1000000;
572         return 0;       
573 }
574
575 /* Initialise WMI. Microsoft have the silliest ideas about easy ways to
576  * obtain the CPU percentage of a running process!
577  * The whole API for this uses evil DCOM and is entirely unicode, giving
578  * all results and accepting queries as wide strings.
579  */
580 bool initwmi()
581 {
582         HRESULT hres;
583
584         /* Initialise COM. This can kill babies. */
585         hres =  CoInitializeEx(0, COINIT_MULTITHREADED); 
586         if (FAILED(hres))
587                 return false;
588
589         /* COM security. This stuff kills kittens */
590         hres =  CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT,
591                 RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL);
592
593         if (FAILED(hres))
594         {
595                 CoUninitialize();
596                 return false;
597         }
598     
599         /* Instance to COM object */
600         pLoc = NULL;
601         hres = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID*)&pLoc);
602  
603         if (FAILED(hres))
604         {
605                 CoUninitialize();
606                 return false;
607         }
608
609         pSvc = NULL;
610
611         /* Connect to DCOM server */
612         hres = pLoc->ConnectServer(_bstr_t(L"ROOT\\CIMV2"), NULL, NULL, 0, NULL, 0, 0, &pSvc);
613     
614         /* That didn't work, maybe no kittens found to kill? */
615         if (FAILED(hres))
616         {
617                 pLoc->Release();
618                 CoUninitialize();
619                 return false;
620         }
621
622         /* Don't even ASK what this does. I'm still not too sure myself. */
623         hres = CoSetProxyBlanket(pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL,
624                 RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE);
625
626         if (FAILED(hres))
627         {
628                 pSvc->Release();
629                 pLoc->Release();     
630                 CoUninitialize();
631                 return false;
632         }
633         return true;
634 }
635
636 void donewmi()
637 {
638         pSvc->Release();
639         pLoc->Release();
640         CoUninitialize();
641 }
642
643 /* Return the CPU usage in percent of this process */
644 int getcpu()
645 {
646         HRESULT hres;
647         int cpu = -1;
648
649         /* Use WQL, similar to SQL, to construct a query that lists the cpu usage and pid of all processes */
650         IEnumWbemClassObject* pEnumerator = NULL;
651
652         BSTR Language = SysAllocString(L"WQL");
653         BSTR Query    = SysAllocString(L"Select PercentProcessorTime,IDProcess from Win32_PerfFormattedData_PerfProc_Process");
654
655         hres = pSvc->ExecQuery(Language, Query, WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
656
657         /* Query didn't work */
658         if (!FAILED(hres))
659         {
660                 IWbemClassObject *pclsObj = NULL;
661                 ULONG uReturn = 0;
662
663                 /* Iterate the query results */
664                 while (pEnumerator)
665                 {
666                         VARIANT vtProp;
667                         VariantInit(&vtProp);
668                         /* Next item */
669                         HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
670
671                         /* No more items left */
672                         if (uReturn == 0)
673                                 break;
674
675                         /* Find process ID */
676                         hr = pclsObj->Get(L"IDProcess", 0, &vtProp, 0, 0);
677                         if (!FAILED(hr))
678                         {
679                                 /* Matches our process ID? */
680                                 UINT pid = vtProp.uintVal;
681                                 VariantClear(&vtProp);
682                                 if (pid == GetCurrentProcessId())
683                                 {                                       
684                                         /* Get CPU percentage for this process */
685                                         hr = pclsObj->Get(L"PercentProcessorTime", 0, &vtProp, 0, 0);
686                                         if (!FAILED(hr))
687                                         {
688                                                 /* Deal with wide string ickyness. Who in their right
689                                                  * mind puts a number in a bstrVal wide string item?!
690                                                  */
691                                                 cpu = 0;
692                                                 std::wstringstream out(vtProp.bstrVal);
693                                                 out >> cpu;
694                                                 VariantClear(&vtProp);
695                                         }
696                                         pclsObj->Release();
697                                         break;
698                                 }
699                                 pclsObj->Release();
700                         }
701                 }
702
703                 pEnumerator->Release();
704         }
705
706         SysFreeString(Language);
707         SysFreeString(Query);
708
709         return cpu;
710 }
711
712 int random()
713 {
714         return rand();
715 }
716
717 void srandom(unsigned int seed)
718 {
719         srand(seed);
720 }
721
722 int gettimeofday(timeval *tv, void *)
723 {
724         SYSTEMTIME st;
725         GetSystemTime(&st);
726
727         tv->tv_sec = time(NULL);
728         tv->tv_usec = st.wMilliseconds;
729
730         return 0;
731 }
732
733 /* World's largest hack to make reference<> work */
734 #include "../src/modules/m_spanningtree/link.h"
735 #include "../src/modules/ssl.h"
736 static void unused_function()
737 {
738         reference<Link> unused_Link;
739         reference<Autoconnect> unused_Autoconnect;
740         reference<ssl_cert> unused_Cert;
741         reference<OperInfo> unused_OperInfo;
742
743         if (unused_Link)
744                 unused_Link->Port = -1;
745         if (unused_Autoconnect)
746                 unused_Autoconnect->NextConnectTime = -1;
747         if (unused_Cert)
748                 unused_Cert->dn = "";
749         if (unused_OperInfo)
750                 unused_OperInfo->name = "";
751
752         Autoconnect *a = unused_Autoconnect;
753         Link *l = unused_Link;
754         ssl_cert *s = unused_Cert;
755         OperInfo *o = unused_OperInfo;
756
757         unused_Link = reference<Link>(unused_Link);
758         unused_Autoconnect = reference<Autoconnect>(unused_Autoconnect);
759         unused_Cert = reference<ssl_cert>(unused_Cert);
760         unused_OperInfo = reference<OperInfo>(unused_OperInfo);
761
762         unused_Link = reference<Link>(l);
763         unused_Autoconnect = reference<Autoconnect>(a);
764         unused_Cert = reference<ssl_cert>(s);
765         unused_OperInfo = reference<OperInfo>(o);
766
767         delete unused_Link;
768         delete unused_Autoconnect;
769         delete unused_Cert;
770         delete unused_OperInfo;
771 }