]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - win/inspircd_win32wrapper.cpp
more fixes
[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 #pragma comment(lib, "winmm.lib")
21 using namespace std;
22
23 #ifndef INADDR_NONE
24 #define INADDR_NONE 0xffffffff
25 #endif
26
27 #include <mmsystem.h>
28
29 /* This MUST remain static and delcared outside the class, so that WriteProcessMemory can reference it properly */
30 static DWORD owner_processid = 0;
31
32
33 int inet_aton(const char *cp, struct in_addr *addr)
34 {
35         unsigned long ip = inet_addr(cp);
36         addr->s_addr = ip;
37         return (addr->s_addr == INADDR_NONE) ? 0 : 1;
38 }
39
40 const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt)
41 {
42
43         if (af == AF_INET)
44         {
45                 struct sockaddr_in in;
46                 memset(&in, 0, sizeof(in));
47                 in.sin_family = AF_INET;
48                 memcpy(&in.sin_addr, src, sizeof(struct in_addr));
49                 getnameinfo((struct sockaddr *)&in, sizeof(struct sockaddr_in), dst, cnt, NULL, 0, NI_NUMERICHOST);
50                 return dst;
51         }
52         else if (af == AF_INET6)
53         {
54                 struct sockaddr_in6 in;
55                 memset(&in, 0, sizeof(in));
56                 in.sin6_family = AF_INET6;
57                 memcpy(&in.sin6_addr, src, sizeof(struct in_addr6));
58                 getnameinfo((struct sockaddr *)&in, sizeof(struct sockaddr_in6), dst, cnt, NULL, 0, NI_NUMERICHOST);
59                 return dst;
60         }
61         return NULL;
62 }
63
64 int geteuid()
65 {
66         return 1;
67 }
68
69 int inet_pton(int af, const char *src, void *dst)
70 {
71         sockaddr_in sa;
72         int len = sizeof(SOCKADDR);
73         int rv = WSAStringToAddress((LPSTR)src, af, NULL, (LPSOCKADDR)&sa, &len);
74         if(rv >= 0)
75         {
76                 if(WSAGetLastError() == 10022)                  // Invalid Argument
77                         rv = 0;
78                 else
79                         rv = 1;
80         }
81         memcpy(dst, &sa.sin_addr, sizeof(struct in_addr));
82         return rv;
83 }
84
85 char * strtok_r(char *_String, const char *_Control, char **_Context)
86 {
87         unsigned char *str;
88         const unsigned char *ctl = (const unsigned char*)_Control;
89         unsigned char map[32];
90
91         if (_Context == 0 || !_Control)
92                 return 0;
93
94         if (!(_String != NULL || *_Context != NULL))
95                 return 0;
96
97         memset(map, 0, 32);
98
99         do {
100                 map[*ctl >> 3] |= (1 << (*ctl & 7));
101         } while (*ctl++);
102
103         /* If string is NULL, set str to the saved
104         * pointer (i.e., continue breaking tokens out of the string
105         * from the last strtok call) */
106         if (_String != NULL)
107         {
108                 str = (unsigned char*)_String;
109         }
110         else
111         {
112                 str = (unsigned char*)*_Context;
113         }
114
115         /* Find beginning of token (skip over leading delimiters). Note that
116         * there is no token iff this loop sets str to point to the terminal
117         * null (*str == 0) */
118         while ((map[*str >> 3] & (1 << (*str & 7))) && *str != 0)
119         {
120                 str++;
121         }
122
123         _String = (char*)str;
124
125         /* Find the end of the token. If it is not the end of the string,
126         * put a null there. */
127         for ( ; *str != 0 ; str++ )
128         {
129                 if (map[*str >> 3] & (1 << (*str & 7)))
130                 {
131                         *str++ = 0;
132                         break;
133                 }
134         }
135
136         /* Update context */
137         *_Context = (char*)str;
138
139         /* Determine if a token has been found. */
140         if (_String == (char*)str)
141         {
142                 return NULL;
143         }
144         else
145         {
146                 return _String;
147         }
148 }
149
150 void setcolor(int color_code)
151 {
152         SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color_code);
153 }
154
155 DIR * opendir(const char * path)
156 {
157         std::string search_path = string(path) + "\\*.*";
158         WIN32_FIND_DATA fd;
159         HANDLE f = FindFirstFile(search_path.c_str(), &fd);
160         if (f != INVALID_HANDLE_VALUE)
161         {
162                 DIR * d = new DIR;
163                 memcpy(&d->find_data, &fd, sizeof(WIN32_FIND_DATA));
164                 d->find_handle = f;
165                 d->first = true;
166                 return d;
167         }
168         else
169         {
170                 return 0;
171         }
172 }
173
174 dirent * readdir(DIR * handle)
175 {
176         if (handle->first)
177                 handle->first = false;
178         else
179         {
180                 if (!FindNextFile(handle->find_handle, &handle->find_data))
181                         return 0;
182         }
183
184         strncpy(handle->dirent_pointer.d_name, handle->find_data.cFileName, MAX_PATH);
185         return &handle->dirent_pointer;
186 }
187
188 void closedir(DIR * handle)
189 {
190         FindClose(handle->find_handle);
191         delete handle;
192 }
193
194 const char * dlerror()
195 {
196         static char errormessage[500];
197         DWORD error = GetLastError();
198         SetLastError(0);
199         if (error == 0)
200                 return 0;
201
202         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)errormessage, 500, 0);
203         return errormessage;
204 }
205
206 #define TRED FOREGROUND_RED | FOREGROUND_INTENSITY
207 #define TGREEN FOREGROUND_GREEN | FOREGROUND_INTENSITY
208 #define TYELLOW FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY
209 #define TNORMAL FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE
210 #define TWHITE TNORMAL | FOREGROUND_INTENSITY
211 #define TBLUE FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY
212
213 /* Handles colors in printf */
214 int printf_c(const char * format, ...)
215 {
216         // Better hope we're not multithreaded, otherwise we'll have chickens crossing the road other side to get the to :P
217         static char message[MAXBUF];
218         static char temp[MAXBUF];
219         int color1, color2;
220
221         /* parse arguments */
222         va_list ap;
223         va_start(ap, format);
224         vsnprintf(message, 500, format, ap);
225         va_end(ap);
226
227         /* search for unix-style escape sequences */
228         int t;
229         int c = 0;
230         const char * p = message;
231         while (*p != 0)
232         {
233                 if (*p == '\033')
234                 {
235                         // Escape sequence -> copy into the temp buffer, and parse the color.
236                         p++;
237                         t = 0;
238                         while ((*p) && (*p != 'm'))
239                         {
240                                 temp[t++] = *p;
241                                 ++p;
242                         }
243
244                         temp[t] = 0;
245                         p++;
246
247                         if (*temp == '[')
248                         {
249                                 if (sscanf(temp, "[%u;%u", &color1, &color2) == 2)
250                                 {
251                                         switch(color2)
252                                         {
253                                         case 32:                // Green
254                                                 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN | FOREGROUND_INTENSITY);              // Yellow
255                                                 break;
256
257                                         default:                // Unknown
258                                                 // White
259                                                 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
260                                                 break;
261                                         }
262                                 }
263                                 else
264                                 {
265                                         switch (*(temp+1))
266                                         {
267                                                 case '0':
268                                                         // Returning to normal colour.
269                                                         SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
270                                                         break;
271
272                                                 case '1':
273                                                         // White
274                                                         SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), TWHITE);
275                                                         break;
276
277                                                 default:
278                                                         char message[50];
279                                                         sprintf(message, "Unknown color code: %s", temp);
280                                                         MessageBox(0, message, message, MB_OK);
281                                                         break;
282                                         }
283                                 }
284                         }
285                 }
286
287                 putchar(*p);
288                 ++c;
289                 ++p;
290         }
291
292         return c;
293 }
294
295 int arg_counter = 1;
296 char optarg[514];
297 int getopt_long_only(int ___argc, char *const *___argv, const char *__shortopts, const struct option *__longopts, int *__longind)
298 {
299         // burlex todo: handle the shortops, at the moment it only works with longopts.
300
301         if (___argc == 1 || arg_counter == ___argc)                     // No arguments (apart from filename)
302                 return -1;
303
304         const char * opt = ___argv[arg_counter];
305
306         // if we're not an option, return an error.
307         if (strnicmp(opt, "--", 2) != 0)
308                 return 1;
309         else
310                 opt += 2;
311
312
313         // parse argument list
314         int i = 0;
315         for (; __longopts[i].name != 0; ++i)
316         {
317                 if (!strnicmp(__longopts[i].name, opt, strlen(__longopts[i].name)))
318                 {
319                         // woot, found a valid argument =)
320                         char * par = 0;
321                         if ((arg_counter + 1) != ___argc)
322                         {
323                                 // grab the parameter from the next argument (if its not another argument)
324                                 if (strnicmp(___argv[arg_counter+1], "--", 2) != 0)
325                                 {
326                                         arg_counter++;          // Trash this next argument, we won't be needing it.
327                                         par = ___argv[arg_counter];
328                                 }
329                         }                       
330
331                         // increment the argument for next time
332                         arg_counter++;
333
334                         // determine action based on type
335                         if (__longopts[i].has_arg == required_argument && !par)
336                         {
337                                 // parameter missing and its a required parameter option
338                                 return 1;
339                         }
340
341                         // store argument in optarg
342                         if (par)
343                                 strncpy(optarg, par, 514);
344
345                         if (__longopts[i].flag != 0)
346                         {
347                                 // this is a variable, we have to set it if this argument is found.
348                                 *__longopts[i].flag = 1;
349                                 return 0;
350                         }
351                         else
352                         {
353                                 if (__longopts[i].val == -1 || par == 0)
354                                         return 1;
355                                 
356                                 return __longopts[i].val;
357                         }                       
358                         break;
359                 }
360         }
361
362         // return 1 (invalid argument)
363         return 1;
364 }
365
366 /*void IPC::Check()
367 {
368         if (hIPCPipe == INVALID_HANDLE_VALUE)
369                 return;
370
371         DWORD bytes;
372         DWORD action;
373
374         BOOL res = ReadFile(hIPCPipe, &action, sizeof(DWORD), &bytes, 0);
375         if (!res)
376         {
377                 if (GetLastError() != ERROR_SEM_TIMEOUT)
378                         Instance->Logs->Log("win32",DEFAULT, "IPC Pipe Error %u: %s", GetLastError(), dlerror());
379                 return;
380         }
381
382         switch (action)
383         {
384                 case IPC_MESSAGE_REHASH:
385                         Instance->Rehash("due to IPC message");
386                 break;
387                 
388                 case IPC_MESSAGE_DIE:
389                         Instance->Exit(0);
390                 break;
391
392                 case IPC_MESSAGE_RESTART:
393                         Instance->Restart("IPC_MESSAGE_RESTART received by mailslot.");
394                 break;
395         }
396 }*/
397
398
399 /* These three functions were created from looking at how ares does it
400  * (...and they look far tidier in C++)
401  */
402
403 /* Get active nameserver */
404 bool GetNameServer(HKEY regkey, const char *key, char* &output)
405 {
406         DWORD size = 0;
407         DWORD result = RegQueryValueEx(regkey, key, 0, NULL, NULL, &size);
408         if (((result != ERROR_SUCCESS) && (result != ERROR_MORE_DATA)) || (!size))
409                 return false;
410
411         output = new char[size+1];
412
413         if ((RegQueryValueEx(regkey, key, 0, NULL, (LPBYTE)output, &size) != ERROR_SUCCESS) || (!*output))
414         {
415                 delete output;
416                 return false;
417         }
418         return true;
419 }
420
421 /* Check a network interface for its nameserver */
422 bool GetInterface(HKEY regkey, const char *key, char* &output)
423 {
424         char buf[39];
425         DWORD size = 39;
426         int idx = 0;
427         HKEY top;
428
429         while (RegEnumKeyEx(regkey, idx++, buf, &size, 0, NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
430         {
431                 size = 39;
432                 if (RegOpenKeyEx(regkey, buf, 0, KEY_QUERY_VALUE, &top) != ERROR_SUCCESS)
433                         continue;
434                 int rc = GetNameServer(top, key, output);
435                 RegCloseKey(top);
436                 if (rc)
437                         return true;
438         }
439         return false;
440 }
441
442
443 std::string FindNameServerWin()
444 {
445         std::string returnval = "127.0.0.1";
446         HKEY top, key;
447         char* dns = NULL;
448
449         /* Lets see if the correct registry hive and tree exist */
450         if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\Tcpip\\Parameters", 0, KEY_READ, &top) == ERROR_SUCCESS)
451         {
452                 /* If they do, attempt to get the nameserver name */
453                 RegOpenKeyEx(top, "Interfaces", 0, KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &key);
454                 if ((GetNameServer(top, "NameServer", dns)) || (GetNameServer(top, "DhcpNameServer", dns))
455                         || (GetInterface(key, "NameServer", dns)) || (GetInterface(key, "DhcpNameServer", dns)))
456                 {
457                         if (dns)
458                         {
459                                 returnval = dns;
460                                 delete dns;
461                         }
462                 }
463                 RegCloseKey(key);
464                 RegCloseKey(top);
465         }
466         return returnval;
467 }
468
469
470 void ClearConsole()
471 {
472         COORD coordScreen = { 0, 0 };    /* here's where we'll home the cursor */
473         HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
474         DWORD cCharsWritten;
475         CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */ 
476         DWORD dwConSize;                 /* number of character cells in the current buffer */ 
477
478         /* get the number of character cells in the current buffer */ 
479
480         if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
481         {
482                 dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
483                 /* fill the entire screen with blanks */ 
484                 if (FillConsoleOutputCharacter( hConsole, (TCHAR) ' ', dwConSize, coordScreen, &cCharsWritten ))
485                 {
486                         /* get the current text attribute */ 
487                         if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
488                         {
489                                 /* now set the buffer's attributes accordingly */
490                                 if (FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten ))
491                                 {
492                                         /* put the cursor at (0, 0) */
493                                         SetConsoleCursorPosition( hConsole, coordScreen );
494                                 }
495                         }
496                 }
497         }
498         return;
499 }
500
501 /* Many inspircd classes contain function pointers/functors which can be changed to point at platform specific implementations
502  * of code. This function repoints these pointers and functors so that calls are windows specific.
503  */
504 void ChangeWindowsSpecificPointers(InspIRCd* Instance)
505 {
506         Instance->Logs->Log("win32",DEBUG,"Changing to windows specific pointer and functor set");
507         Instance->Config->DNSServerValidator = &ValidateWindowsDnsServer;
508 }
509
510 DWORD WindowsForkStart(InspIRCd* Instance)
511 {
512         /* Windows implementation of fork() :P */
513         if (owner_processid)
514                 return 0;
515
516         char module[MAX_PATH];
517         if(!GetModuleFileName(NULL, module, MAX_PATH))
518         {
519                 printf("GetModuleFileName() failed.\n");
520                 return false;
521         }
522
523         STARTUPINFO startupinfo;
524         PROCESS_INFORMATION procinfo;
525         ZeroMemory(&startupinfo, sizeof(STARTUPINFO));
526         ZeroMemory(&procinfo, sizeof(PROCESS_INFORMATION));
527
528         // Fill in the startup info struct
529         GetStartupInfo(&startupinfo);
530
531         /* Default creation flags create the processes suspended */
532         DWORD startupflags = CREATE_SUSPENDED;
533
534         /* On windows 2003/XP and above, we can use the value
535          * CREATE_PRESERVE_CODE_AUTHZ_LEVEL which gives more access
536          * to the process which we may require on these operating systems.
537          */
538         OSVERSIONINFO vi;
539         vi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
540         GetVersionEx(&vi);
541         if ((vi.dwMajorVersion >= 5) && (vi.dwMinorVersion > 0))
542                 startupflags |= CREATE_PRESERVE_CODE_AUTHZ_LEVEL;
543
544         // Launch our "forked" process.
545         BOOL bSuccess = CreateProcess ( module, // Module (exe) filename
546                 strdup(GetCommandLine()),       // Command line (exe plus parameters from the OS)
547                                                 // NOTE: We cannot return the direct value of the
548                                                 // GetCommandLine function here, as the pointer is
549                                                 // passed straight to the child process, and will be
550                                                 // invalid once we exit as it goes out of context.
551                                                 // strdup() seems ok, though.
552                 0,                              // PROCESS_SECURITY_ATTRIBUTES
553                 0,                              // THREAD_SECURITY_ATTRIBUTES
554                 TRUE,                           // We went to inherit handles.
555                 startupflags,                   // Allow us full access to the process and suspend it.
556                 0,                              // ENVIRONMENT
557                 0,                              // CURRENT_DIRECTORY
558                 &startupinfo,                   // startup info
559                 &procinfo);                     // process info
560
561         if(!bSuccess)
562         {
563                 printf("CreateProcess() error: %s\n", dlerror());
564                 return false;
565         }
566
567         // Set the owner process id in the target process.
568         SIZE_T written = 0;
569         DWORD pid = GetCurrentProcessId();
570         if(!WriteProcessMemory(procinfo.hProcess, &owner_processid, &pid, sizeof(DWORD), &written) || written != sizeof(DWORD))
571         {
572                 printf("WriteProcessMemory() failed: %s\n", dlerror());
573                 return false;
574         }
575
576         // Resume the other thread (let it start)
577         ResumeThread(procinfo.hThread);
578
579         // 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.
580         WaitForSingleObject(procinfo.hProcess, INFINITE);
581
582         // If we hit this it means startup failed, default to 14 if this fails.
583         DWORD ExitCode = 14;
584         GetExitCodeProcess(procinfo.hProcess, &ExitCode);
585         CloseHandle(procinfo.hThread);
586         CloseHandle(procinfo.hProcess);
587         return ExitCode;
588 }
589
590 void WindowsForkKillOwner(InspIRCd * Instance)
591 {
592         HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, owner_processid);
593         if(!hProcess || !owner_processid)
594         {
595                 printf("Could not open process id %u: %s.\n", owner_processid, dlerror());
596                 Instance->Exit(14);
597         }
598
599         // die die die
600         if(!TerminateProcess(hProcess, 0))
601         {
602                 printf("Could not TerminateProcess(): %s\n", dlerror());
603                 Instance->Exit(14);
604         }
605
606         CloseHandle(hProcess);
607 }
608
609 bool ValidateWindowsDnsServer(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
610 {
611         if (!*(data.GetString()))
612         {
613                 std::string nameserver;
614                 conf->GetInstance()->Logs->Log("win32",DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in the registry...");
615                 nameserver = FindNameServerWin();
616                 /* Windows stacks multiple nameservers in one registry key, seperated by commas.
617                  * Spotted by Cataclysm.
618                  */
619                 if (nameserver.find(',') != std::string::npos)
620                         nameserver = nameserver.substr(0, nameserver.find(','));
621                 /* Just to be FUCKING AKWARD, windows fister... err i mean vista...
622                  * seperates the nameservers with spaces instead.
623                  */
624                 if (nameserver.find(' ') != std::string::npos)
625                         nameserver = nameserver.substr(0, nameserver.find(' '));
626                 data.Set(nameserver.c_str());
627                 conf->GetInstance()->Logs->Log("win32",DEFAULT,"<dns:server> set to '%s' as first active resolver in registry.", nameserver.c_str());
628         }
629         return true;
630 }
631
632 int gettimeofday(struct timeval * tv, void * tz)
633 {
634         if(tv == NULL)
635                 return -1;
636
637         DWORD mstime = timeGetTime();
638         tv->tv_sec   = time(NULL);
639         tv->tv_usec  = (mstime - (tv->tv_sec * 1000)) * 1000;
640     return 0;   
641 }