]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - win/inspircd_win32wrapper.cpp
Ok windows.. YOU WIN :< .. but at least I can use MAXBUF now and configure will have...
[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 <string>
17 #include <errno.h>
18 #include <assert.h>
19 using namespace std;
20
21 #ifndef INADDR_NONE
22 #define INADDR_NONE 0xffffffff
23 #endif
24
25 HANDLE hIPCPipe;
26
27 int inet_aton(const char *cp, struct in_addr *addr)
28 {
29         unsigned long ip = inet_addr(cp);
30         addr->s_addr = ip;
31         return (addr->s_addr == INADDR_NONE) ? 0 : 1;
32 }
33
34 const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt)
35 {
36
37         if (af == AF_INET)
38         {
39                 struct sockaddr_in in;
40                 memset(&in, 0, sizeof(in));
41                 in.sin_family = AF_INET;
42                 memcpy(&in.sin_addr, src, sizeof(struct in_addr));
43                 getnameinfo((struct sockaddr *)&in, sizeof(struct sockaddr_in), dst, cnt, NULL, 0, NI_NUMERICHOST);
44                 return dst;
45         }
46         else if (af == AF_INET6)
47         {
48                 struct sockaddr_in6 in;
49                 memset(&in, 0, sizeof(in));
50                 in.sin6_family = AF_INET6;
51                 memcpy(&in.sin6_addr, src, sizeof(struct in_addr6));
52                 getnameinfo((struct sockaddr *)&in, sizeof(struct sockaddr_in6), dst, cnt, NULL, 0, NI_NUMERICHOST);
53                 return dst;
54         }
55         return NULL;
56 }
57
58 int geteuid()
59 {
60         return 1;
61 }
62
63 int inet_pton(int af, const char *src, void *dst)
64 {
65         sockaddr_in sa;
66         int len = sizeof(SOCKADDR);
67         int rv = WSAStringToAddress((LPSTR)src, af, NULL, (LPSOCKADDR)&sa, &len);
68         if(rv >= 0)
69         {
70                 if(WSAGetLastError() == 10022)                  // Invalid Argument
71                         rv = 0;
72                 else
73                         rv = 1;
74         }
75         memcpy(dst, &sa.sin_addr, sizeof(struct in_addr));
76         return rv;
77 }
78
79 char * strtok_r(char *_String, const char *_Control, char **_Context)
80 {
81         unsigned char *str;
82         const unsigned char *ctl = (const unsigned char*)_Control;
83         unsigned char map[32];
84
85         if (_Context == 0 || !_Control)
86                 return 0;
87
88         if (!(_String != NULL || *_Context != NULL))
89                 return 0;
90
91         memset(map, 0, 32);
92
93         do {
94                 map[*ctl >> 3] |= (1 << (*ctl & 7));
95         } while (*ctl++);
96
97         /* If string is NULL, set str to the saved
98         * pointer (i.e., continue breaking tokens out of the string
99         * from the last strtok call) */
100         if (_String != NULL)
101         {
102                 str = (unsigned char*)_String;
103         }
104         else
105         {
106                 str = (unsigned char*)*_Context;
107         }
108
109         /* Find beginning of token (skip over leading delimiters). Note that
110         * there is no token iff this loop sets str to point to the terminal
111         * null (*str == 0) */
112         while ((map[*str >> 3] & (1 << (*str & 7))) && *str != 0)
113         {
114                 str++;
115         }
116
117         _String = (char*)str;
118
119         /* Find the end of the token. If it is not the end of the string,
120         * put a null there. */
121         for ( ; *str != 0 ; str++ )
122         {
123                 if (map[*str >> 3] & (1 << (*str & 7)))
124                 {
125                         *str++ = 0;
126                         break;
127                 }
128         }
129
130         /* Update context */
131         *_Context = (char*)str;
132
133         /* Determine if a token has been found. */
134         if (_String == (char*)str)
135         {
136                 return NULL;
137         }
138         else
139         {
140                 return _String;
141         }
142 }
143
144 void setcolor(int color_code)
145 {
146         SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color_code);
147 }
148
149 DIR * opendir(const char * path)
150 {
151         std::string search_path = string(path) + "\\*.*";
152         WIN32_FIND_DATA fd;
153         HANDLE f = FindFirstFile(search_path.c_str(), &fd);
154         if (f != INVALID_HANDLE_VALUE)
155         {
156                 DIR * d = new DIR;
157                 memcpy(&d->find_data, &fd, sizeof(WIN32_FIND_DATA));
158                 d->find_handle = f;
159                 d->first = true;
160                 return d;
161         }
162         else
163         {
164                 return 0;
165         }
166 }
167
168 dirent * readdir(DIR * handle)
169 {
170         if (handle->first)
171                 handle->first = false;
172         else
173         {
174                 if (!FindNextFile(handle->find_handle, &handle->find_data))
175                         return 0;
176         }
177
178         strncpy(handle->dirent_pointer.d_name, handle->find_data.cFileName, MAX_PATH);
179         return &handle->dirent_pointer;
180 }
181
182 void closedir(DIR * handle)
183 {
184         FindClose(handle->find_handle);
185         delete handle;
186 }
187
188 const char * dlerror()
189 {
190         static char errormessage[500];
191         DWORD error = GetLastError();
192         SetLastError(0);
193         if (error == 0)
194                 return 0;
195
196         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)errormessage, 500, 0);
197         return errormessage;
198 }
199
200 #define TRED FOREGROUND_RED | FOREGROUND_INTENSITY
201 #define TGREEN FOREGROUND_GREEN | FOREGROUND_INTENSITY
202 #define TYELLOW FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY
203 #define TNORMAL FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE
204 #define TWHITE TNORMAL | FOREGROUND_INTENSITY
205 #define TBLUE FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY
206
207 /* Handles colors in printf */
208 int printf_c(const char * format, ...)
209 {
210         // Better hope we're not multithreaded, otherwise we'll have chickens crossing the road other side to get the to :P
211         static char message[MAXBUF];
212         static char temp[MAXBUF];
213         int color1, color2;
214
215         /* parse arguments */
216         va_list ap;
217         va_start(ap, format);
218         vsnprintf(message, 500, format, ap);
219         va_end(ap);
220
221         /* search for unix-style escape sequences */
222         int t;
223         int c = 0;
224         const char * p = message;
225         while (*p != 0)
226         {
227                 if (*p == '\033')
228                 {
229                         // Escape sequence -> copy into the temp buffer, and parse the color.
230                         p++;
231                         t = 0;
232                         while ((*p) && (*p != 'm'))
233                         {
234                                 temp[t++] = *p;
235                                 ++p;
236                         }
237
238                         temp[t] = 0;
239                         p++;
240
241                         if (*temp == '[')
242                         {
243                                 if (sscanf(temp, "[%u;%u", &color1, &color2) == 2)
244                                 {
245                                         switch(color2)
246                                         {
247                                         case 32:                // Green
248                                                 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN | FOREGROUND_INTENSITY);              // Yellow
249                                                 break;
250
251                                         default:                // Unknown
252                                                 // White
253                                                 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
254                                                 break;
255                                         }
256                                 }
257                                 else
258                                 {
259                                         switch (*(temp+1))
260                                         {
261                                                 case '0':
262                                                         // Returning to normal colour.
263                                                         SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
264                                                         break;
265
266                                                 case '1':
267                                                         // White
268                                                         SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), TWHITE);
269                                                         break;
270
271                                                 default:
272                                                         char message[50];
273                                                         sprintf(message, "Unknown color code: %s", temp);
274                                                         MessageBox(0, message, message, MB_OK);
275                                                         break;
276                                         }
277                                 }
278                         }
279                 }
280
281                 putchar(*p);
282                 ++c;
283                 ++p;
284         }
285
286         return c;
287 }
288
289 int arg_counter = 1;
290 char optarg[514];
291 int getopt_long_only(int ___argc, char *const *___argv, const char *__shortopts, const struct option *__longopts, int *__longind)
292 {
293         // burlex todo: handle the shortops, at the moment it only works with longopts.
294
295         if (___argc == 1 || arg_counter == ___argc)                     // No arguments (apart from filename)
296                 return -1;
297
298         const char * opt = ___argv[arg_counter];
299         int return_val = 0;
300
301         // if we're not an option, return an error.
302         if (strnicmp(opt, "--", 2) != 0)
303                 return 1;
304         else
305                 opt += 2;
306
307
308         // parse argument list
309         int i = 0;
310         for (; __longopts[i].name != 0; ++i)
311         {
312                 if (!strnicmp(__longopts[i].name, opt, strlen(__longopts[i].name)))
313                 {
314                         // woot, found a valid argument =)
315                         char * par = 0;
316                         if ((arg_counter + 1) != ___argc)
317                         {
318                                 // grab the parameter from the next argument (if its not another argument)
319                                 if (strnicmp(___argv[arg_counter+1], "--", 2) != 0)
320                                 {
321                                         arg_counter++;          // Trash this next argument, we won't be needing it.
322                                         par = ___argv[arg_counter];
323                                 }
324                         }                       
325
326                         // increment the argument for next time
327                         arg_counter++;
328
329                         // determine action based on type
330                         if (__longopts[i].has_arg == required_argument && !par)
331                         {
332                                 // parameter missing and its a required parameter option
333                                 return 1;
334                         }
335
336                         // store argument in optarg
337                         if (par)
338                                 strncpy(optarg, par, 514);
339
340                         if (__longopts[i].flag != 0)
341                         {
342                                 // this is a variable, we have to set it if this argument is found.
343                                 *__longopts[i].flag = 1;
344                                 return 0;
345                         }
346                         else
347                         {
348                                 if (__longopts[i].val == -1 || par == 0)
349                                         return 1;
350                                 
351                                 return __longopts[i].val;
352                         }                       
353                         break;
354                 }
355         }
356
357         // return 1 (invalid argument)
358         return 1;
359 }
360
361 /* IPC Messages */
362 #define IPC_MESSAGE_REHASH      1
363 #define IPC_MESSAGE_DIE         2
364 #define IPC_MESSAGE_RESTART     3
365
366 void InitIPC()
367 {
368         static DWORD buflen = 1024;
369         static const char * pipename = "\\\\.\\mailslot\\Inspircd";
370         hIPCPipe = CreateMailslot(pipename, buflen, 0, 0);
371         if (hIPCPipe == INVALID_HANDLE_VALUE)
372                 printf("IPC Pipe could not be created. Are you sure you didn't start InspIRCd twice?\n");
373 }
374
375 void CheckIPC(InspIRCd * Instance)
376 {
377         if (hIPCPipe == INVALID_HANDLE_VALUE)
378                 return;
379
380         DWORD bytes;
381         DWORD action;
382
383         BOOL res = ReadFile(hIPCPipe, &action, sizeof(DWORD), &bytes, 0);
384         if (!res)
385         {
386                 if (GetLastError() != ERROR_SEM_TIMEOUT)
387                         Instance->Log(DEFAULT, "IPC Pipe Error %u: %s", GetLastError(), dlerror());
388                 return;
389         }
390
391         switch (action)
392         {
393                 case IPC_MESSAGE_REHASH:
394                         InspIRCd::Rehash(0);
395                 break;
396                 
397                 case IPC_MESSAGE_DIE:
398                         InspIRCd::Exit(0);
399                 break;
400
401                 case IPC_MESSAGE_RESTART:
402                         Instance->Restart("IPC_MESSAGE_RESTART received by mailslot.");
403                 break;
404         }
405 }
406
407 void CloseIPC()
408 {
409         CloseHandle(hIPCPipe);
410 }
411
412
413 /* These three functions were created from looking at how ares does it
414  * (...and they look far tidier in C++)
415  */
416
417 /* Get active nameserver */
418 bool GetNameServer(HKEY regkey, const char *key, char* &output)
419 {
420         DWORD size = 0;
421         DWORD result = RegQueryValueEx(regkey, key, 0, NULL, NULL, &size);
422         if (((result != ERROR_SUCCESS) && (result != ERROR_MORE_DATA)) || (!size))
423                 return false;
424
425         output = new char[size+1];
426
427         if ((RegQueryValueEx(regkey, key, 0, NULL, (LPBYTE)output, &size) != ERROR_SUCCESS) || (!*output))
428         {
429                 delete output;
430                 return false;
431         }
432         return true;
433 }
434
435 /* Check a network interface for its nameserver */
436 bool GetInterface(HKEY regkey, const char *key, char* &output)
437 {
438         char buf[39];
439         DWORD size = 39;
440         int idx = 0;
441         HKEY top;
442
443         while (RegEnumKeyEx(regkey, idx++, buf, &size, 0, NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
444         {
445                 size = 39;
446                 if (RegOpenKeyEx(regkey, buf, 0, KEY_QUERY_VALUE, &top) != ERROR_SUCCESS)
447                         continue;
448                 int rc = GetNameServer(top, key, output);
449                 RegCloseKey(top);
450                 if (rc)
451                         return true;
452         }
453         return false;
454 }
455
456
457 std::string FindNameServerWin()
458 {
459         std::string returnval = "127.0.0.1";
460         HKEY top, key;
461         char* dns = NULL;
462
463         /* Lets see if the correct registry hive and tree exist */
464         if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\Tcpip\\Parameters", 0, KEY_READ, &top) == ERROR_SUCCESS)
465         {
466                 /* If they do, attempt to get the nameserver name */
467                 RegOpenKeyEx(top, "Interfaces", 0, KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &key);
468                 if ((GetNameServer(top, "NameServer", dns)) || (GetNameServer(top, "DhcpNameServer", dns))
469                         || (GetInterface(key, "NameServer", dns)) || (GetInterface(key, "DhcpNameServer", dns)))
470                 {
471                         if (dns)
472                         {
473                                 returnval = dns;
474                                 delete dns;
475                         }
476                 }
477                 RegCloseKey(key);
478                 RegCloseKey(top);
479         }
480         return returnval;
481 }
482
483
484 void ClearConsole()
485 {
486         COORD coordScreen = { 0, 0 };    /* here's where we'll home the cursor */
487         HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
488         DWORD cCharsWritten;
489         CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */ 
490         DWORD dwConSize;                 /* number of character cells in the current buffer */ 
491
492         /* get the number of character cells in the current buffer */ 
493
494         if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
495         {
496                 dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
497                 /* fill the entire screen with blanks */ 
498                 if (FillConsoleOutputCharacter( hConsole, (TCHAR) ' ', dwConSize, coordScreen, &cCharsWritten ))
499                 {
500                         /* get the current text attribute */ 
501                         if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
502                         {
503                                 /* now set the buffer's attributes accordingly */
504                                 if (FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten ))
505                                 {
506                                         /* put the cursor at (0, 0) */
507                                         SetConsoleCursorPosition( hConsole, coordScreen );
508                                 }
509                         }
510                 }
511         }
512         return;
513 }