windows: Extend strerror_r/s by extended POSIX errno strings
[strongswan.git] / src / libstrongswan / utils / windows.c
1 /*
2 * Copyright (C) 2013 Martin Willi
3 * Copyright (C) 2013 revosec AG
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * for more details.
14 */
15
16 #include "utils.h"
17
18 #include <errno.h>
19
20 /**
21 * See header
22 */
23 void windows_init()
24 {
25 WSADATA wsad;
26
27 /* initialize winsock2 */
28 WSAStartup(MAKEWORD(2, 2), &wsad);
29 }
30
31 /**
32 * See header
33 */
34 void windows_deinit()
35 {
36 WSACleanup();
37 }
38
39 /**
40 * See header
41 */
42 int usleep(useconds_t usec)
43 {
44 if (usec > 0 && usec < 1000)
45 { /* do not Sleep(0) for small values */
46 usec = 1000;
47 }
48 SleepEx(usec / 1000, TRUE);
49 return 0;
50 }
51
52 /**
53 * See header.
54 */
55 char* strndup(const char *s, size_t n)
56 {
57 char *dst;
58
59 n = min(strnlen(s, n), n);
60 dst = malloc(n + 1);
61 memcpy(dst, s, n);
62 dst[n] = '\0';
63
64 return dst;
65 }
66
67 /*
68 * See header.
69 */
70 void *dlopen(const char *filename, int flag)
71 {
72 return LoadLibrary(filename);
73 }
74
75 /**
76 * Load a symbol from known default libs (monolithic build)
77 */
78 static void* dlsym_default(const char *name)
79 {
80 const char *dlls[] = {
81 "libstrongswan-0.dll",
82 "libhydra-0.dll",
83 "libcharon-0.dll",
84 "libtnccs-0.dll",
85 NULL /* .exe */
86 };
87 HANDLE handle;
88 void *sym = NULL;
89 int i;
90
91 for (i = 0; i < countof(dlls); i++)
92 {
93 handle = GetModuleHandle(dlls[i]);
94 if (handle)
95 {
96 sym = GetProcAddress(handle, name);
97 if (sym)
98 {
99 break;
100 }
101 }
102 }
103 return sym;
104 }
105
106 /**
107 * Emulate RTLD_NEXT for some known symbols
108 */
109 static void* dlsym_next(const char *name)
110 {
111 struct {
112 const char *dll;
113 const char *syms[4];
114 } dlls[] = {
115 /* for leak detective */
116 { "msvcrt",
117 { "malloc", "calloc", "realloc", "free" }
118 },
119 };
120 HANDLE handle = NULL;
121 int i, j;
122
123 for (i = 0; i < countof(dlls); i++)
124 {
125 for (j = 0; j < countof(dlls[0].syms); j++)
126 {
127 if (dlls[i].syms[j] && streq(dlls[i].syms[j], name))
128 {
129 handle = GetModuleHandle(dlls[i].dll);
130 break;
131 }
132 }
133 }
134 if (handle)
135 {
136 return GetProcAddress(handle, name);
137 }
138 return handle;
139 }
140
141 /**
142 * See header.
143 */
144 void* dlsym(void *handle, const char *symbol)
145 {
146 if (handle == RTLD_DEFAULT)
147 {
148 return dlsym_default(symbol);
149 }
150 if (handle == RTLD_NEXT)
151 {
152 return dlsym_next(symbol);
153 }
154 return GetProcAddress((HMODULE)handle, symbol);
155 }
156
157 /**
158 * See header.
159 */
160 char* dlerror(void)
161 {
162 static char buf[128];
163 char *pos;
164 DWORD err;
165
166 err = GetLastError();
167 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
168 NULL, err, 0, buf, sizeof(buf), NULL) > 0)
169 {
170 pos = strchr(buf, '\n');
171 if (pos)
172 {
173 *pos = '\0';
174 }
175 }
176 else
177 {
178 snprintf(buf, sizeof(buf), "(%u)", err);
179 }
180 return buf;
181 }
182
183 /**
184 * See header.
185 */
186 int dlclose(void *handle)
187 {
188 return FreeLibrary((HMODULE)handle);
189 }
190
191 /**
192 * See header
193 */
194 int socketpair(int domain, int type, int protocol, int sv[2])
195 {
196 struct sockaddr_in addr = {
197 .sin_family = AF_INET,
198 .sin_addr.s_addr = htonl(INADDR_LOOPBACK),
199 };
200 socklen_t len = sizeof(addr);
201 int s, c, sc;
202 BOOL on;
203
204 /* We don't check domain for AF_INET, as we use it as replacement for
205 * AF_UNIX. */
206 if (type != SOCK_STREAM)
207 {
208 errno = EINVAL;
209 return -1;
210 }
211 if (protocol != 0 && protocol != IPPROTO_TCP)
212 {
213 errno = EINVAL;
214 return -1;
215 }
216 s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
217 if (s == -1)
218 {
219 return -1;
220 }
221 c = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
222 if (c == -1)
223 {
224 closesocket(c);
225 return -1;
226 }
227 if (bind(s, (struct sockaddr*)&addr, sizeof(addr)) == 0 &&
228 getsockname(s,(struct sockaddr*)&addr, &len) == 0 &&
229 listen(s, 0) == 0 &&
230 connect(c, (struct sockaddr*)&addr, sizeof(addr)) == 0)
231 {
232 sc = accept(s, NULL, NULL);
233 if (sc > 0)
234 {
235 closesocket(s);
236 s = sc;
237 if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY,
238 (void*)&on, sizeof(on)) == 0 &&
239 setsockopt(c, IPPROTO_TCP, TCP_NODELAY,
240 (void*)&on, sizeof(on)) == 0)
241 {
242 sv[0] = s;
243 sv[1] = c;
244 return 0;
245 }
246 }
247 }
248 closesocket(s);
249 closesocket(c);
250 return -1;
251 }
252
253 /**
254 * See header
255 */
256 char* getpass(const char *prompt)
257 {
258 static char buf[64] = "";
259 char *pos;
260 HANDLE in, out;
261 DWORD mode, written = 0, total, done;
262
263 out = GetStdHandle(STD_OUTPUT_HANDLE);
264 in = GetStdHandle(STD_INPUT_HANDLE);
265
266 if (out == INVALID_HANDLE_VALUE || in == INVALID_HANDLE_VALUE ||
267 !GetConsoleMode(out, &mode) || !GetConsoleMode(in, &mode))
268 {
269 return NULL;
270 }
271
272 total = strlen(prompt);
273 while (written < total)
274 {
275 if (!WriteConsole(out, prompt + written, total - written, &done, NULL))
276 {
277 return NULL;
278 }
279 written += done;
280 }
281
282 if (!SetConsoleMode(in, mode & ~ENABLE_ECHO_INPUT))
283 {
284 return NULL;
285 }
286
287 while (TRUE)
288 {
289 if (!ReadConsole(in, buf, sizeof(buf), &done, NULL))
290 {
291 SetConsoleMode(in, mode);
292 return NULL;
293 }
294 if (done)
295 {
296 pos = strchr(buf, '\r');
297 if (pos)
298 {
299 *pos = '\0';
300 }
301 break;
302 }
303 }
304 SetConsoleMode(in, mode);
305
306 /* append a newline, as we have no echo during input */
307 WriteConsole(out, "\r\n", 2, &done, NULL);
308
309 return buf;
310 }
311
312 /**
313 * See header.
314 */
315 #undef strerror_s
316 int strerror_s_extended(char *buf, size_t buflen, int errnum)
317 {
318 const char *errstr [] = {
319 /* EADDRINUSE */ "Address in use",
320 /* EADDRNOTAVAIL */ "Address not available",
321 /* EAFNOSUPPORT */ "Address family not supported",
322 /* EALREADY */ "Connection already in progress",
323 /* EBADMSG */ "Bad message",
324 /* ECANCELED */ "Operation canceled",
325 /* ECONNABORTED */ "Connection aborted",
326 /* ECONNREFUSED */ "Connection refused",
327 /* ECONNRESET */ "Connection reset",
328 /* EDESTADDRREQ */ "Destination address required",
329 /* EHOSTUNREACH */ "Host is unreachable",
330 /* EIDRM */ "Identifier removed",
331 /* EINPROGRESS */ "Operation in progress",
332 /* EISCONN */ "Socket is connected",
333 /* ELOOP */ "Too many levels of symbolic links",
334 /* EMSGSIZE */ "Message too large",
335 /* ENETDOWN */ "Network is down",
336 /* ENETRESET */ "Connection aborted by network",
337 /* ENETUNREACH */ "Network unreachable",
338 /* ENOBUFS */ "No buffer space available",
339 /* ENODATA */ "No message is available",
340 /* ENOLINK */ "No link",
341 /* ENOMSG */ "No message of the desired type",
342 /* ENOPROTOOPT */ "Protocol not available",
343 /* ENOSR */ "No stream resources",
344 /* ENOSTR */ "Not a stream",
345 /* ENOTCONN */ "The socket is not connected",
346 /* ENOTRECOVERABLE */ "State not recoverable",
347 /* ENOTSOCK */ "Not a socket",
348 /* ENOTSUP */ "Not supported",
349 /* EOPNOTSUPP */ "Operation not supported on socket",
350 /* EOTHER */ "Other error",
351 /* EOVERFLOW */ "Value too large to be stored in data type",
352 /* EOWNERDEAD */ "Previous owner died",
353 /* EPROTO */ "Protocol error",
354 /* EPROTONOSUPPORT */ "Protocol not supported",
355 /* EPROTOTYPE */ "Protocol wrong type for socket",
356 /* ETIME */ "Timeout",
357 /* ETIMEDOUT */ "Connection timed out",
358 /* ETXTBSY */ "Text file busy",
359 /* EWOULDBLOCK */ "Operation would block",
360 };
361 int offset = EADDRINUSE;
362
363 if (errnum < offset || errnum > offset + countof(errstr))
364 {
365 return strerror_s(buf, buflen, errnum);
366 }
367 strncpy(buf, errstr[errnum - offset], buflen);
368 buf[buflen - 1] = '\0';
369 return 0;
370 }
371
372 /**
373 * Set errno for a function setting WSA error on failure
374 */
375 static int wserr(int retval)
376 {
377 if (retval < 0)
378 {
379 static const struct {
380 DWORD wsa;
381 int err;
382 } map[] = {
383 { WSANOTINITIALISED, EBADF },
384 { WSAENETDOWN, ENETDOWN },
385 { WSAENETRESET, ENETRESET },
386 { WSAECONNABORTED, ECONNABORTED },
387 { WSAESHUTDOWN, ECONNABORTED },
388 { WSAEACCES, EACCES },
389 { WSAEINTR, EINTR },
390 { WSAEINPROGRESS, EINPROGRESS },
391 { WSAEFAULT, EFAULT },
392 { WSAENOBUFS, ENOBUFS },
393 { WSAENOTSOCK, ENOTSOCK },
394 { WSAEOPNOTSUPP, EOPNOTSUPP },
395 { WSAEWOULDBLOCK, EWOULDBLOCK },
396 { WSAEMSGSIZE, EMSGSIZE },
397 { WSAEINVAL, EINVAL },
398 { WSAENOTCONN, ENOTCONN },
399 { WSAEHOSTUNREACH, EHOSTUNREACH },
400 { WSAENETUNREACH, ENETUNREACH },
401 { WSAECONNABORTED, ECONNABORTED },
402 { WSAECONNRESET, ECONNRESET },
403 { WSAETIMEDOUT, ETIMEDOUT },
404 { WSAEMFILE, EMFILE },
405 { WSAEALREADY, EALREADY },
406 { WSAEDESTADDRREQ, EDESTADDRREQ },
407 { WSAEISCONN, EISCONN },
408 { WSAEOPNOTSUPP, EOPNOTSUPP },
409 { WSAEPROTOTYPE, EPROTOTYPE },
410 { WSAENOPROTOOPT, ENOPROTOOPT },
411 { WSAEPROTONOSUPPORT, EPROTONOSUPPORT },
412 { WSAEPFNOSUPPORT, EPROTONOSUPPORT },
413 { WSAEAFNOSUPPORT, EAFNOSUPPORT },
414 { WSAEADDRNOTAVAIL, EADDRNOTAVAIL },
415 { WSAEADDRINUSE, EADDRINUSE },
416 { WSAETIMEDOUT, ETIMEDOUT },
417 { WSAECONNREFUSED, ECONNREFUSED },
418 { WSAELOOP, ELOOP },
419 { WSAENAMETOOLONG, ENAMETOOLONG },
420 { WSAENOTEMPTY, ENOTEMPTY },
421 { WSAEPROTOTYPE, EPROTOTYPE },
422 { WSAVERNOTSUPPORTED, ENOTSUP },
423 };
424 DWORD wsa, i;
425
426 wsa = WSAGetLastError();
427 for (i = 0; i < countof(map); i++)
428 {
429 if (map[i].wsa == wsa)
430 {
431 errno = map[i].err;
432 return retval;
433 }
434 }
435 errno = ENOENT;
436 return retval;
437 }
438 errno = 0;
439 return retval;
440 }
441
442 /**
443 * Check and clear the dontwait flag
444 */
445 static bool check_dontwait(int *flags)
446 {
447 if (*flags & MSG_DONTWAIT)
448 {
449 *flags &= ~MSG_DONTWAIT;
450 return TRUE;
451 }
452 return FALSE;
453 }
454
455 /**
456 * See header
457 */
458 #undef shutdown
459 int windows_shutdown(int sockfd, int how)
460 {
461 return wserr(shutdown(sockfd, how));
462 }
463
464 /**
465 * See header
466 */
467 #undef accept
468 int windows_accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen)
469 {
470 return wserr(accept(sockfd, addr, addrlen));
471 }
472
473 /**
474 * See header
475 */
476 #undef bind
477 int windows_bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen)
478 {
479 return wserr(bind(sockfd, addr, addrlen));
480 }
481
482 /**
483 * See header
484 */
485 #undef connect
486 int windows_connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen)
487 {
488 return wserr(connect(sockfd, addr, addrlen));
489 }
490
491 /**
492 * See header
493 */
494 #undef getsockname
495 int windows_getsockname(int sockfd, struct sockaddr *addr, socklen_t *addrlen)
496 {
497 return wserr(getsockname(sockfd, addr, addrlen));
498 }
499
500 /**
501 * See header
502 */
503 #undef getsockopt
504 int windows_getsockopt(int sockfd, int level, int optname,
505 void *optval, socklen_t *optlen)
506 {
507 return wserr(getsockopt(sockfd, level, optname, optval, optlen));
508 }
509
510 /**
511 * See header
512 */
513 #undef setsockopt
514 int windows_setsockopt(int sockfd, int level, int optname,
515 const void *optval, socklen_t optlen)
516 {
517 return wserr(setsockopt(sockfd, level, optname, optval, optlen));
518 }
519
520 /**
521 * See header
522 */
523 #undef socket
524 int windows_socket(int domain, int type, int protocol)
525 {
526 return wserr(socket(domain, type, protocol));
527 }
528
529 /**
530 * See header
531 */
532 #undef select
533 int windows_select(int nfds, fd_set *readfds, fd_set *writefds,
534 fd_set *exceptfds, struct timeval *timeout)
535 {
536 return wserr(select(nfds, readfds, writefds, exceptfds, timeout));
537 }
538
539 /**
540 * See header
541 */
542 #undef close
543 int windows_close(int fd)
544 {
545 int ret;
546
547 ret = close(fd);
548 if (ret == -1 && errno == EBADF)
549 { /* Winsock socket? */
550 ret = wserr(closesocket(fd));
551 }
552 return ret;
553 }
554
555 /**
556 * See header
557 */
558 #undef recv
559 ssize_t windows_recv(int sockfd, void *buf, size_t len, int flags)
560 {
561 u_long on = 1, off = 0;
562 ssize_t outlen = -1;
563
564 if (!check_dontwait(&flags))
565 {
566 return wserr(recv(sockfd, buf, len, flags));
567 }
568 if (wserr(ioctlsocket(sockfd, FIONBIO, &on) == 0))
569 {
570 outlen = wserr(recv(sockfd, buf, len, flags));
571 ioctlsocket(sockfd, FIONBIO, &off);
572 }
573 return outlen;
574 }
575
576 /**
577 * See header
578 */
579 #undef recvfrom
580 ssize_t windows_recvfrom(int sockfd, void *buf, size_t len, int flags,
581 struct sockaddr *src_addr, socklen_t *addrlen)
582 {
583 u_long on = 1, off = 0;
584 ssize_t outlen = -1;
585
586 if (!check_dontwait(&flags))
587 {
588 return wserr(recvfrom(sockfd, buf, len, flags, src_addr, addrlen));
589 }
590 if (wserr(ioctlsocket(sockfd, FIONBIO, &on)) == 0)
591 {
592 outlen = wserr(recvfrom(sockfd, buf, len, flags, src_addr, addrlen));
593 ioctlsocket(sockfd, FIONBIO, &off);
594 }
595 return outlen;
596 }
597
598 /**
599 * See header
600 */
601 #undef send
602 ssize_t windows_send(int sockfd, const void *buf, size_t len, int flags)
603 {
604 u_long on = 1, off = 0;
605 ssize_t outlen = -1;
606
607 if (!check_dontwait(&flags))
608 {
609 return wserr(send(sockfd, buf, len, flags));
610 }
611 if (wserr(ioctlsocket(sockfd, FIONBIO, &on)) == 0)
612 {
613 outlen = wserr(send(sockfd, buf, len, flags));
614 ioctlsocket(sockfd, FIONBIO, &off);
615 }
616 return outlen;
617 }
618
619 /**
620 * See header
621 */
622 #undef sendto
623 ssize_t windows_sendto(int sockfd, const void *buf, size_t len, int flags,
624 const struct sockaddr *dest_addr, socklen_t addrlen)
625 {
626 u_long on = 1, off = 0;
627 ssize_t outlen = -1;
628
629 if (!check_dontwait(&flags))
630 {
631 return wserr(sendto(sockfd, buf, len, flags, dest_addr, addrlen));
632 }
633 if (wserr(ioctlsocket(sockfd, FIONBIO, &on)) == 0)
634 {
635 outlen = wserr(sendto(sockfd, buf, len, flags, dest_addr, addrlen));
636 ioctlsocket(sockfd, FIONBIO, &off);
637 }
638 return outlen;
639 }