]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - win/inspircd_win32wrapper.cpp
0af54a39c14744ff18d2334b69bd549985ef0bfb
[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 int arg_counter = 1;
201 char optarg[514];
202 int getopt_long_only(int ___argc, char *const *___argv, const char *__shortopts, const struct option *__longopts, int *__longind)
203 {
204         // burlex todo: handle the shortops, at the moment it only works with longopts.
205
206         if (___argc == 1 || arg_counter == ___argc)                     // No arguments (apart from filename)
207                 return -1;
208
209         const char * opt = ___argv[arg_counter];
210         int return_val = 0;
211
212         // if we're not an option, return an error.
213         if (strnicmp(opt, "--", 2) != 0)
214                 return 1;
215         else
216                 opt += 2;
217
218
219         // parse argument list
220         int i = 0;
221         for (; __longopts[i].name != 0; ++i)
222         {
223                 if (!strnicmp(__longopts[i].name, opt, strlen(__longopts[i].name)))
224                 {
225                         // woot, found a valid argument =)
226                         char * par = 0;
227                         if ((arg_counter + 1) != ___argc)
228                         {
229                                 // grab the parameter from the next argument (if its not another argument)
230                                 if (strnicmp(___argv[arg_counter+1], "--", 2) != 0)
231                                 {
232                                         arg_counter++;          // Trash this next argument, we won't be needing it.
233                                         par = ___argv[arg_counter];
234                                 }
235                         }                       
236
237                         // increment the argument for next time
238                         arg_counter++;
239
240                         // determine action based on type
241                         if (__longopts[i].has_arg == required_argument && !par)
242                         {
243                                 // parameter missing and its a required parameter option
244                                 return 1;
245                         }
246
247                         // store argument in optarg
248                         if (par)
249                                 strncpy(optarg, par, 514);
250
251                         if (__longopts[i].flag != 0)
252                         {
253                                 // this is a variable, we have to set it if this argument is found.
254                                 *__longopts[i].flag = 1;
255                                 return 0;
256                         }
257                         else
258                         {
259                                 if (__longopts[i].val == -1 || par == 0)
260                                         return 1;
261                                 
262                                 return __longopts[i].val;
263                         }                       
264                         break;
265                 }
266         }
267
268         // return 1 (invalid argument)
269         return 1;
270 }
271
272 /* IPC Messages */
273 #define IPC_MESSAGE_REHASH      1
274 #define IPC_MESSAGE_DIE         2
275 #define IPC_MESSAGE_RESTART     3
276
277 void InitIPC()
278 {
279         static DWORD buflen = 1024;
280         static const char * pipename = "\\\\.\\mailslot\\Inspircd";
281         hIPCPipe = CreateMailslot(pipename, buflen, 0, 0);
282         if (hIPCPipe == INVALID_HANDLE_VALUE)
283                 printf("IPC Pipe could not be created. Are you sure you didn't start InspIRCd twice?\n");
284 }
285
286 void CheckIPC(InspIRCd * Instance)
287 {
288         if (hIPCPipe == INVALID_HANDLE_VALUE)
289                 return;
290
291         DWORD bytes;
292         DWORD action;
293
294         BOOL res = ReadFile(hIPCPipe, &action, sizeof(DWORD), &bytes, 0);
295         if (!res)
296         {
297                 if (GetLastError() != ERROR_SEM_TIMEOUT)
298                         Instance->Log(DEFAULT, "IPC Pipe Error %u: %s", GetLastError(), dlerror());
299                 return;
300         }
301
302         switch (action)
303         {
304                 case IPC_MESSAGE_REHASH:
305                         InspIRCd::Rehash(0);
306                 break;
307                 
308                 case IPC_MESSAGE_DIE:
309                         InspIRCd::Exit(0);
310                 break;
311
312                 case IPC_MESSAGE_RESTART:
313                         Instance->Restart("IPC_MESSAGE_RESTART received by mailslot.");
314                 break;
315         }
316 }
317
318 void CloseIPC()
319 {
320         CloseHandle(hIPCPipe);
321 }
322
323
324 /* These three functions were created from looking at how ares does it
325  * (...and they look far tidier in C++)
326  */
327
328 /* Get active nameserver */
329 bool GetNameServer(HKEY regkey, const char *key, char* &output)
330 {
331         DWORD size = 0;
332         DWORD result = RegQueryValueEx(regkey, key, 0, NULL, NULL, &size);
333         if (((result != ERROR_SUCCESS) && (result != ERROR_MORE_DATA)) || (!size))
334                 return false;
335
336         output = new char[size+1];
337
338         if ((RegQueryValueEx(regkey, key, 0, NULL, (LPBYTE)output, &size) != ERROR_SUCCESS) || (!*output))
339         {
340                 delete output;
341                 return false;
342         }
343         return true;
344 }
345
346 /* Check a network interface for its nameserver */
347 bool GetInterface(HKEY regkey, const char *key, char* &output)
348 {
349         char buf[39];
350         DWORD size = 39;
351         int idx = 0;
352         HKEY top;
353
354         while (RegEnumKeyEx(regkey, idx++, buf, &size, 0, NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
355         {
356                 size = 39;
357                 if (RegOpenKeyEx(regkey, buf, 0, KEY_QUERY_VALUE, &top) != ERROR_SUCCESS)
358                         continue;
359                 int rc = GetNameServer(top, key, output);
360                 RegCloseKey(top);
361                 if (rc)
362                         return true;
363         }
364         return false;
365 }
366
367
368 std::string FindNameServerWin()
369 {
370         std::string returnval = "127.0.0.1";
371         HKEY top, key;
372         char* dns = NULL;
373
374         /* Lets see if the correct registry hive and tree exist */
375         if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\Tcpip\\Parameters", 0, KEY_READ, &top) == ERROR_SUCCESS)
376         {
377                 /* If they do, attempt to get the nameserver name */
378                 RegOpenKeyEx(top, "Interfaces", 0, KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &key);
379                 if ((GetNameServer(top, "NameServer", dns)) || (GetNameServer(top, "DhcpNameServer", dns))
380                         || (GetInterface(key, "NameServer", dns)) || (GetInterface(key, "DhcpNameServer", dns)))
381                 {
382                         if (dns)
383                         {
384                                 returnval = dns;
385                                 delete dns;
386                         }
387                 }
388                 RegCloseKey(key);
389                 RegCloseKey(top);
390         }
391         return returnval;
392 }
393
394
395 void ClearConsole()
396 {
397         COORD coordScreen = { 0, 0 };    /* here's where we'll home the cursor */
398         HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
399         DWORD cCharsWritten;
400         CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */ 
401         DWORD dwConSize;                 /* number of character cells in the current buffer */ 
402
403         /* get the number of character cells in the current buffer */ 
404
405         if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
406         {
407                 dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
408                 /* fill the entire screen with blanks */ 
409                 if (FillConsoleOutputCharacter( hConsole, (TCHAR) ' ', dwConSize, coordScreen, &cCharsWritten ))
410                 {
411                         /* get the current text attribute */ 
412                         if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
413                         {
414                                 /* now set the buffer's attributes accordingly */
415                                 if (FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten ))
416                                 {
417                                         /* put the cursor at (0, 0) */
418                                         SetConsoleCursorPosition( hConsole, coordScreen );
419                                 }
420                         }
421                 }
422         }
423         return;
424 }