]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - win/inspircd_win32wrapper.cpp
c32d31d5a2b81045387d0e8e6dbea6735bc976ca
[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 /* IPC Messages */
367 #define IPC_MESSAGE_REHASH      1
368 #define IPC_MESSAGE_DIE         2
369 #define IPC_MESSAGE_RESTART     3
370
371 IPC::IPC(InspIRCd* Srv) : Instance(Srv)
372 {
373         static DWORD buflen = 1024;
374         static const char * pipename = "\\\\.\\mailslot\\Inspircd";
375         hIPCPipe = CreateMailslot(pipename, buflen, 0, 0);
376         if (hIPCPipe == INVALID_HANDLE_VALUE)
377                 printf("IPC Pipe could not be created. Are you sure you didn't start InspIRCd twice?\n");
378 }
379
380 void IPC::Check()
381 {
382         if (hIPCPipe == INVALID_HANDLE_VALUE)
383                 return;
384
385         DWORD bytes;
386         DWORD action;
387
388         BOOL res = ReadFile(hIPCPipe, &action, sizeof(DWORD), &bytes, 0);
389         if (!res)
390         {
391                 if (GetLastError() != ERROR_SEM_TIMEOUT)
392                         Instance->Logs->Log("win32",DEFAULT, "IPC Pipe Error %u: %s", GetLastError(), dlerror());
393                 return;
394         }
395
396         switch (action)
397         {
398                 case IPC_MESSAGE_REHASH:
399                         Instance->Rehash("due to IPC message");
400                 break;
401                 
402                 case IPC_MESSAGE_DIE:
403                         Instance->Exit(0);
404                 break;
405
406                 case IPC_MESSAGE_RESTART:
407                         Instance->Restart("IPC_MESSAGE_RESTART received by mailslot.");
408                 break;
409         }
410 }
411
412 IPC::~IPC()
413 {
414         CloseHandle(hIPCPipe);
415 }
416
417
418 /* These three functions were created from looking at how ares does it
419  * (...and they look far tidier in C++)
420  */
421
422 /* Get active nameserver */
423 bool GetNameServer(HKEY regkey, const char *key, char* &output)
424 {
425         DWORD size = 0;
426         DWORD result = RegQueryValueEx(regkey, key, 0, NULL, NULL, &size);
427         if (((result != ERROR_SUCCESS) && (result != ERROR_MORE_DATA)) || (!size))
428                 return false;
429
430         output = new char[size+1];
431
432         if ((RegQueryValueEx(regkey, key, 0, NULL, (LPBYTE)output, &size) != ERROR_SUCCESS) || (!*output))
433         {
434                 delete output;
435                 return false;
436         }
437         return true;
438 }
439
440 /* Check a network interface for its nameserver */
441 bool GetInterface(HKEY regkey, const char *key, char* &output)
442 {
443         char buf[39];
444         DWORD size = 39;
445         int idx = 0;
446         HKEY top;
447
448         while (RegEnumKeyEx(regkey, idx++, buf, &size, 0, NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
449         {
450                 size = 39;
451                 if (RegOpenKeyEx(regkey, buf, 0, KEY_QUERY_VALUE, &top) != ERROR_SUCCESS)
452                         continue;
453                 int rc = GetNameServer(top, key, output);
454                 RegCloseKey(top);
455                 if (rc)
456                         return true;
457         }
458         return false;
459 }
460
461
462 std::string FindNameServerWin()
463 {
464         std::string returnval = "127.0.0.1";
465         HKEY top, key;
466         char* dns = NULL;
467
468         /* Lets see if the correct registry hive and tree exist */
469         if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\Tcpip\\Parameters", 0, KEY_READ, &top) == ERROR_SUCCESS)
470         {
471                 /* If they do, attempt to get the nameserver name */
472                 RegOpenKeyEx(top, "Interfaces", 0, KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &key);
473                 if ((GetNameServer(top, "NameServer", dns)) || (GetNameServer(top, "DhcpNameServer", dns))
474                         || (GetInterface(key, "NameServer", dns)) || (GetInterface(key, "DhcpNameServer", dns)))
475                 {
476                         if (dns)
477                         {
478                                 returnval = dns;
479                                 delete dns;
480                         }
481                 }
482                 RegCloseKey(key);
483                 RegCloseKey(top);
484         }
485         return returnval;
486 }
487
488
489 void ClearConsole()
490 {
491         COORD coordScreen = { 0, 0 };    /* here's where we'll home the cursor */
492         HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
493         DWORD cCharsWritten;
494         CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */ 
495         DWORD dwConSize;                 /* number of character cells in the current buffer */ 
496
497         /* get the number of character cells in the current buffer */ 
498
499         if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
500         {
501                 dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
502                 /* fill the entire screen with blanks */ 
503                 if (FillConsoleOutputCharacter( hConsole, (TCHAR) ' ', dwConSize, coordScreen, &cCharsWritten ))
504                 {
505                         /* get the current text attribute */ 
506                         if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
507                         {
508                                 /* now set the buffer's attributes accordingly */
509                                 if (FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten ))
510                                 {
511                                         /* put the cursor at (0, 0) */
512                                         SetConsoleCursorPosition( hConsole, coordScreen );
513                                 }
514                         }
515                 }
516         }
517         return;
518 }
519
520 /* Many inspircd classes contain function pointers/functors which can be changed to point at platform specific implementations
521  * of code. This function repoints these pointers and functors so that calls are windows specific.
522  */
523 void ChangeWindowsSpecificPointers(InspIRCd* Instance)
524 {
525         Instance->Logs->Log("win32",DEBUG,"Changing to windows specific pointer and functor set");
526         Instance->Config->DNSServerValidator = &ValidateWindowsDnsServer;
527 }
528
529 DWORD WindowsForkStart(InspIRCd* Instance)
530 {
531         /* Windows implementation of fork() :P */
532         if (owner_processid)
533                 return 0;
534
535         char module[MAX_PATH];
536         if(!GetModuleFileName(NULL, module, MAX_PATH))
537         {
538                 printf("GetModuleFileName() failed.\n");
539                 return false;
540         }
541
542         STARTUPINFO startupinfo;
543         PROCESS_INFORMATION procinfo;
544         ZeroMemory(&startupinfo, sizeof(STARTUPINFO));
545         ZeroMemory(&procinfo, sizeof(PROCESS_INFORMATION));
546
547         // Fill in the startup info struct
548         GetStartupInfo(&startupinfo);
549
550         /* Default creation flags create the processes suspended */
551         DWORD startupflags = CREATE_SUSPENDED;
552
553         /* On windows 2003/XP and above, we can use the value
554          * CREATE_PRESERVE_CODE_AUTHZ_LEVEL which gives more access
555          * to the process which we may require on these operating systems.
556          */
557         OSVERSIONINFO vi;
558         vi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
559         GetVersionEx(&vi);
560         if ((vi.dwMajorVersion >= 5) && (vi.dwMinorVersion > 0))
561                 startupflags |= CREATE_PRESERVE_CODE_AUTHZ_LEVEL;
562
563         // Launch our "forked" process.
564         BOOL bSuccess = CreateProcess ( module, // Module (exe) filename
565                 strdup(GetCommandLine()),       // Command line (exe plus parameters from the OS)
566                                                 // NOTE: We cannot return the direct value of the
567                                                 // GetCommandLine function here, as the pointer is
568                                                 // passed straight to the child process, and will be
569                                                 // invalid once we exit as it goes out of context.
570                                                 // strdup() seems ok, though.
571                 0,                              // PROCESS_SECURITY_ATTRIBUTES
572                 0,                              // THREAD_SECURITY_ATTRIBUTES
573                 TRUE,                           // We went to inherit handles.
574                 startupflags,                   // Allow us full access to the process and suspend it.
575                 0,                              // ENVIRONMENT
576                 0,                              // CURRENT_DIRECTORY
577                 &startupinfo,                   // startup info
578                 &procinfo);                     // process info
579
580         if(!bSuccess)
581         {
582                 printf("CreateProcess() error: %s\n", dlerror());
583                 return false;
584         }
585
586         // Set the owner process id in the target process.
587         SIZE_T written = 0;
588         DWORD pid = GetCurrentProcessId();
589         if(!WriteProcessMemory(procinfo.hProcess, &owner_processid, &pid, sizeof(DWORD), &written) || written != sizeof(DWORD))
590         {
591                 printf("WriteProcessMemory() failed: %s\n", dlerror());
592                 return false;
593         }
594
595         // Resume the other thread (let it start)
596         ResumeThread(procinfo.hThread);
597
598         // 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.
599         WaitForSingleObject(procinfo.hProcess, INFINITE);
600
601         // If we hit this it means startup failed, default to 14 if this fails.
602         DWORD ExitCode = 14;
603         GetExitCodeProcess(procinfo.hProcess, &ExitCode);
604         CloseHandle(procinfo.hThread);
605         CloseHandle(procinfo.hProcess);
606         return ExitCode;
607 }
608
609 void WindowsForkKillOwner(InspIRCd * Instance)
610 {
611         HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, owner_processid);
612         if(!hProcess || !owner_processid)
613         {
614                 printf("Could not open process id %u: %s.\n", owner_processid, dlerror());
615                 Instance->Exit(14);
616         }
617
618         // die die die
619         if(!TerminateProcess(hProcess, 0))
620         {
621                 printf("Could not TerminateProcess(): %s\n", dlerror());
622                 Instance->Exit(14);
623         }
624
625         CloseHandle(hProcess);
626 }
627
628 bool ValidateWindowsDnsServer(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
629 {
630         if (!*(data.GetString()))
631         {
632                 std::string nameserver;
633                 conf->GetInstance()->Logs->Log("win32",DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in the registry...");
634                 nameserver = FindNameServerWin();
635                 /* Windows stacks multiple nameservers in one registry key, seperated by commas.
636                  * Spotted by Cataclysm.
637                  */
638                 if (nameserver.find(',') != std::string::npos)
639                         nameserver = nameserver.substr(0, nameserver.find(','));
640                 /* Just to be FUCKING AKWARD, windows fister... err i mean vista...
641                  * seperates the nameservers with spaces instead.
642                  */
643                 if (nameserver.find(' ') != std::string::npos)
644                         nameserver = nameserver.substr(0, nameserver.find(' '));
645                 data.Set(nameserver.c_str());
646                 conf->GetInstance()->Logs->Log("win32",DEFAULT,"<dns:server> set to '%s' as first active resolver in registry.", nameserver.c_str());
647         }
648         return true;
649 }
650
651 int gettimeofday(struct timeval * tv, void * tz)
652 {
653         if(tv == NULL)
654                 return -1;
655
656         DWORD mstime = timeGetTime();
657         tv->tv_sec   = time(NULL);
658         tv->tv_usec  = (mstime - (tv->tv_sec * 1000)) * 1000;
659     return 0;   
660 }