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