]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - win/inspircd_win32wrapper.cpp
1008cb83874b2ead07b7b66beb13b2c9fabce635
[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 #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 optind = 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 || optind == ___argc)                  // No arguments (apart from filename)
246                 return -1;
247
248         const char * opt = ___argv[optind];
249         optind++;
250
251         // if we're not an option, return an error.
252         if (strnicmp(opt, "--", 2) != 0)
253                 return 1;
254         else
255                 opt += 2;
256
257
258         // parse argument list
259         int i = 0;
260         for (; __longopts[i].name != 0; ++i)
261         {
262                 if (!strnicmp(__longopts[i].name, opt, strlen(__longopts[i].name)))
263                 {
264                         // woot, found a valid argument =)
265                         char * par = 0;
266                         if ((optind) != ___argc)
267                         {
268                                 // grab the parameter from the next argument (if its not another argument)
269                                 if (strnicmp(___argv[optind], "--", 2) != 0)
270                                 {
271 //                                      optind++;               // Trash this next argument, we won't be needing it.
272                                         par = ___argv[optind-1];
273                                 }
274                         }                       
275
276                         // increment the argument for next time
277 //                      optind++;
278
279                         // determine action based on type
280                         if (__longopts[i].has_arg == required_argument && !par)
281                         {
282                                 // parameter missing and its a required parameter option
283                                 return 1;
284                         }
285
286                         // store argument in optarg
287                         if (par)
288                                 strncpy(optarg, par, 514);
289
290                         if (__longopts[i].flag != 0)
291                         {
292                                 // this is a variable, we have to set it if this argument is found.
293                                 *__longopts[i].flag = 1;
294                                 return 0;
295                         }
296                         else
297                         {
298                                 if (__longopts[i].val == -1 || par == 0)
299                                         return 1;
300                                 
301                                 return __longopts[i].val;
302                         }                       
303                         break;
304                 }
305         }
306
307         // return 1 (invalid argument)
308         return 1;
309 }
310
311 /* These three functions were created from looking at how ares does it
312  * (...and they look far tidier in C++)
313  */
314
315 /* Get active nameserver */
316 bool GetNameServer(HKEY regkey, const char *key, char* &output)
317 {
318         DWORD size = 0;
319         DWORD result = RegQueryValueEx(regkey, key, 0, NULL, NULL, &size);
320         if (((result != ERROR_SUCCESS) && (result != ERROR_MORE_DATA)) || (!size))
321                 return false;
322
323         output = new char[size+1];
324
325         if ((RegQueryValueEx(regkey, key, 0, NULL, (LPBYTE)output, &size) != ERROR_SUCCESS) || (!*output))
326         {
327                 delete output;
328                 return false;
329         }
330         return true;
331 }
332
333 /* Check a network interface for its nameserver */
334 bool GetInterface(HKEY regkey, const char *key, char* &output)
335 {
336         char buf[39];
337         DWORD size = 39;
338         int idx = 0;
339         HKEY top;
340
341         while (RegEnumKeyEx(regkey, idx++, buf, &size, 0, NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
342         {
343                 size = 39;
344                 if (RegOpenKeyEx(regkey, buf, 0, KEY_QUERY_VALUE, &top) != ERROR_SUCCESS)
345                         continue;
346                 int rc = GetNameServer(top, key, output);
347                 RegCloseKey(top);
348                 if (rc)
349                         return true;
350         }
351         return false;
352 }
353
354
355 std::string FindNameServerWin()
356 {
357         std::string returnval = "127.0.0.1";
358         HKEY top, key;
359         char* dns = NULL;
360
361         /* Lets see if the correct registry hive and tree exist */
362         if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\Tcpip\\Parameters", 0, KEY_READ, &top) == ERROR_SUCCESS)
363         {
364                 /* If they do, attempt to get the nameserver name */
365                 RegOpenKeyEx(top, "Interfaces", 0, KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &key);
366                 if ((GetNameServer(top, "NameServer", dns)) || (GetNameServer(top, "DhcpNameServer", dns))
367                         || (GetInterface(key, "NameServer", dns)) || (GetInterface(key, "DhcpNameServer", dns)))
368                 {
369                         if (dns)
370                         {
371                                 returnval = dns;
372                                 delete dns;
373                         }
374                 }
375                 RegCloseKey(key);
376                 RegCloseKey(top);
377         }
378         return returnval;
379 }
380
381
382 void ClearConsole()
383 {
384         COORD coordScreen = { 0, 0 };    /* here's where we'll home the cursor */
385         HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
386         DWORD cCharsWritten;
387         CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */ 
388         DWORD dwConSize;                 /* number of character cells in the current buffer */ 
389
390         /* get the number of character cells in the current buffer */ 
391
392         if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
393         {
394                 dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
395                 /* fill the entire screen with blanks */ 
396                 if (FillConsoleOutputCharacter( hConsole, (TCHAR) ' ', dwConSize, coordScreen, &cCharsWritten ))
397                 {
398                         /* get the current text attribute */ 
399                         if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
400                         {
401                                 /* now set the buffer's attributes accordingly */
402                                 if (FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten ))
403                                 {
404                                         /* put the cursor at (0, 0) */
405                                         SetConsoleCursorPosition( hConsole, coordScreen );
406                                 }
407                         }
408                 }
409         }
410         return;
411 }
412
413 /* Many inspircd classes contain function pointers/functors which can be changed to point at platform specific implementations
414  * of code. This function repoints these pointers and functors so that calls are windows specific.
415  */
416 void ChangeWindowsSpecificPointers(InspIRCd* Instance)
417 {
418         Instance->Logs->Log("win32",DEBUG,"Changing to windows specific pointer and functor set");
419 }
420
421 DWORD WindowsForkStart(InspIRCd* Instance)
422 {
423         /* Windows implementation of fork() :P */
424         if (owner_processid)
425                 return 0;
426
427         char module[MAX_PATH];
428         if(!GetModuleFileName(NULL, module, MAX_PATH))
429         {
430                 printf("GetModuleFileName() failed.\n");
431                 return false;
432         }
433
434         STARTUPINFO startupinfo;
435         PROCESS_INFORMATION procinfo;
436         ZeroMemory(&startupinfo, sizeof(STARTUPINFO));
437         ZeroMemory(&procinfo, sizeof(PROCESS_INFORMATION));
438
439         // Fill in the startup info struct
440         GetStartupInfo(&startupinfo);
441
442         /* Default creation flags create the processes suspended */
443         DWORD startupflags = CREATE_SUSPENDED;
444
445         /* On windows 2003/XP and above, we can use the value
446          * CREATE_PRESERVE_CODE_AUTHZ_LEVEL which gives more access
447          * to the process which we may require on these operating systems.
448          */
449         OSVERSIONINFO vi;
450         vi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
451         GetVersionEx(&vi);
452         if ((vi.dwMajorVersion >= 5) && (vi.dwMinorVersion > 0))
453                 startupflags |= CREATE_PRESERVE_CODE_AUTHZ_LEVEL;
454
455         // Launch our "forked" process.
456         BOOL bSuccess = CreateProcess ( module, // Module (exe) filename
457                 strdup(GetCommandLine()),       // Command line (exe plus parameters from the OS)
458                                                 // NOTE: We cannot return the direct value of the
459                                                 // GetCommandLine function here, as the pointer is
460                                                 // passed straight to the child process, and will be
461                                                 // invalid once we exit as it goes out of context.
462                                                 // strdup() seems ok, though.
463                 0,                              // PROCESS_SECURITY_ATTRIBUTES
464                 0,                              // THREAD_SECURITY_ATTRIBUTES
465                 TRUE,                           // We went to inherit handles.
466                 startupflags,                   // Allow us full access to the process and suspend it.
467                 0,                              // ENVIRONMENT
468                 0,                              // CURRENT_DIRECTORY
469                 &startupinfo,                   // startup info
470                 &procinfo);                     // process info
471
472         if(!bSuccess)
473         {
474                 printf("CreateProcess() error: %s\n", dlerror());
475                 return false;
476         }
477
478         // Set the owner process id in the target process.
479         SIZE_T written = 0;
480         DWORD pid = GetCurrentProcessId();
481         if(!WriteProcessMemory(procinfo.hProcess, &owner_processid, &pid, sizeof(DWORD), &written) || written != sizeof(DWORD))
482         {
483                 printf("WriteProcessMemory() failed: %s\n", dlerror());
484                 return false;
485         }
486
487         // Resume the other thread (let it start)
488         ResumeThread(procinfo.hThread);
489
490         // 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.
491         WaitForSingleObject(procinfo.hProcess, INFINITE);
492
493         // If we hit this it means startup failed, default to 14 if this fails.
494         DWORD ExitCode = 14;
495         GetExitCodeProcess(procinfo.hProcess, &ExitCode);
496         CloseHandle(procinfo.hThread);
497         CloseHandle(procinfo.hProcess);
498         return ExitCode;
499 }
500
501 void WindowsForkKillOwner(InspIRCd * Instance)
502 {
503         HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, owner_processid);
504         if(!hProcess || !owner_processid)
505         {
506                 printf("Could not open process id %u: %s.\n", owner_processid, dlerror());
507                 Instance->Exit(14);
508         }
509
510         // die die die
511         if(!TerminateProcess(hProcess, 0))
512         {
513                 printf("Could not TerminateProcess(): %s\n", dlerror());
514                 Instance->Exit(14);
515         }
516
517         CloseHandle(hProcess);
518 }
519
520 bool ValidateDnsServer(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
521 {
522         if (!*(data.GetString()))
523         {
524                 std::string nameserver;
525                 conf->GetInstance()->Logs->Log("win32",DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in the registry...");
526                 nameserver = FindNameServerWin();
527                 /* Windows stacks multiple nameservers in one registry key, seperated by commas.
528                  * Spotted by Cataclysm.
529                  */
530                 if (nameserver.find(',') != std::string::npos)
531                         nameserver = nameserver.substr(0, nameserver.find(','));
532                 /* Just to be FUCKING AKWARD, windows fister... err i mean vista...
533                  * seperates the nameservers with spaces instead.
534                  */
535                 if (nameserver.find(' ') != std::string::npos)
536                         nameserver = nameserver.substr(0, nameserver.find(' '));
537                 data.Set(nameserver.c_str());
538                 conf->GetInstance()->Logs->Log("win32",DEFAULT,"<dns:server> set to '%s' as first active resolver in registry.", nameserver.c_str());
539         }
540         return true;
541 }
542
543 int gettimeofday(struct timeval * tv, void * tz)
544 {
545         if(tv == NULL)
546                 return -1;
547
548         DWORD mstime = timeGetTime();
549         tv->tv_sec   = time(NULL);
550         tv->tv_usec  = (mstime - (tv->tv_sec * 1000)) * 1000;
551         return 0;       
552 }
553
554 /* Initialise WMI. Microsoft have the silliest ideas about easy ways to
555  * obtain the CPU percentage of a running process!
556  * The whole API for this uses evil DCOM and is entirely unicode, giving
557  * all results and accepting queries as wide strings.
558  */
559 bool initwmi()
560 {
561         HRESULT hres;
562
563         /* Initialise COM. This can kill babies. */
564         hres =  CoInitializeEx(0, COINIT_MULTITHREADED); 
565         if (FAILED(hres))
566                 return false;
567
568         /* COM security. This stuff kills kittens */
569         hres =  CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT,
570                 RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL);
571
572         if (FAILED(hres))
573         {
574                 CoUninitialize();
575                 return false;
576         }
577     
578         /* Instance to COM object */
579         pLoc = NULL;
580         hres = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID*)&pLoc);
581  
582         if (FAILED(hres))
583         {
584                 CoUninitialize();
585                 return false;
586         }
587
588         pSvc = NULL;
589
590         /* Connect to DCOM server */
591         hres = pLoc->ConnectServer(_bstr_t(L"ROOT\\CIMV2"), NULL, NULL, 0, NULL, 0, 0, &pSvc);
592     
593         /* That didn't work, maybe no kittens found to kill? */
594         if (FAILED(hres))
595         {
596                 pLoc->Release();
597                 CoUninitialize();
598                 return false;
599         }
600
601         /* Don't even ASK what this does. I'm still not too sure myself. */
602         hres = CoSetProxyBlanket(pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL,
603                 RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE);
604
605         if (FAILED(hres))
606         {
607                 pSvc->Release();
608                 pLoc->Release();     
609                 CoUninitialize();
610                 return false;
611         }
612         return true;
613 }
614
615 void donewmi()
616 {
617         pSvc->Release();
618         pLoc->Release();
619         CoUninitialize();
620 }
621
622 /* Return the CPU usage in percent of this process */
623 int getcpu()
624 {
625         HRESULT hres;
626         int cpu = -1;
627
628         /* Use WQL, similar to SQL, to construct a query that lists the cpu usage and pid of all processes */
629         IEnumWbemClassObject* pEnumerator = NULL;
630
631         BSTR Language = SysAllocString(L"WQL");
632         BSTR Query    = SysAllocString(L"Select PercentProcessorTime,IDProcess from Win32_PerfFormattedData_PerfProc_Process");
633
634         hres = pSvc->ExecQuery(Language, Query, WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
635
636         /* Query didn't work */
637         if (!FAILED(hres))
638         {
639                 IWbemClassObject *pclsObj = NULL;
640                 ULONG uReturn = 0;
641
642                 /* Iterate the query results */
643                 while (pEnumerator)
644                 {
645                         VARIANT vtProp;
646                         /* Next item */
647                         HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
648
649                         /* No more items left */
650                         if (uReturn == 0)
651                                 break;
652
653                         /* Find process ID */
654                         hr = pclsObj->Get(L"IDProcess", 0, &vtProp, 0, 0);
655                         if (!FAILED(hr))
656                         {
657                                 /* Matches our process ID? */
658                                 if (vtProp.uintVal == GetCurrentProcessId())
659                                 {
660                                         VariantClear(&vtProp);
661                                         /* Get CPU percentage for this process */
662                                         hr = pclsObj->Get(L"PercentProcessorTime", 0, &vtProp, 0, 0);
663                                         if (!FAILED(hr))
664                                         {
665                                                 /* Deal with wide string ickyness. Who in their right
666                                                  * mind puts a number in a bstrVal wide string item?!
667                                                  */
668                                                 VariantClear(&vtProp);
669                                                 cpu = 0;
670                                                 std::wstringstream out(vtProp.bstrVal);
671                                                 out >> cpu;
672                                                 break;
673                                         }
674                                 }
675                         }
676                 }
677
678                 pEnumerator->Release();
679                 pclsObj->Release();
680         }
681
682         SysFreeString(Language);
683         SysFreeString(Query);
684
685         return cpu;
686 }