windows: Wrap most Winsock2 Posix functions to set errno
[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 * Set errno for a function setting WSA error on failure
314 */
315 static int wserr(int retval)
316 {
317 if (retval < 0)
318 {
319 static const struct {
320 DWORD wsa;
321 int err;
322 } map[] = {
323 { WSANOTINITIALISED, EBADF },
324 { WSAENETDOWN, ENETDOWN },
325 { WSAENETRESET, ENETRESET },
326 { WSAECONNABORTED, ECONNABORTED },
327 { WSAESHUTDOWN, ECONNABORTED },
328 { WSAEACCES, EACCES },
329 { WSAEINTR, EINTR },
330 { WSAEINPROGRESS, EINPROGRESS },
331 { WSAEFAULT, EFAULT },
332 { WSAENOBUFS, ENOBUFS },
333 { WSAENOTSOCK, ENOTSOCK },
334 { WSAEOPNOTSUPP, EOPNOTSUPP },
335 { WSAEWOULDBLOCK, EWOULDBLOCK },
336 { WSAEMSGSIZE, EMSGSIZE },
337 { WSAEINVAL, EINVAL },
338 { WSAENOTCONN, ENOTCONN },
339 { WSAEHOSTUNREACH, EHOSTUNREACH },
340 { WSAENETUNREACH, ENETUNREACH },
341 { WSAECONNABORTED, ECONNABORTED },
342 { WSAECONNRESET, ECONNRESET },
343 { WSAETIMEDOUT, ETIMEDOUT },
344 { WSAEMFILE, EMFILE },
345 { WSAEALREADY, EALREADY },
346 { WSAEDESTADDRREQ, EDESTADDRREQ },
347 { WSAEISCONN, EISCONN },
348 { WSAEOPNOTSUPP, EOPNOTSUPP },
349 { WSAEPROTOTYPE, EPROTOTYPE },
350 { WSAENOPROTOOPT, ENOPROTOOPT },
351 { WSAEPROTONOSUPPORT, EPROTONOSUPPORT },
352 { WSAEPFNOSUPPORT, EPROTONOSUPPORT },
353 { WSAEAFNOSUPPORT, EAFNOSUPPORT },
354 { WSAEADDRNOTAVAIL, EADDRNOTAVAIL },
355 { WSAEADDRINUSE, EADDRINUSE },
356 { WSAETIMEDOUT, ETIMEDOUT },
357 { WSAECONNREFUSED, ECONNREFUSED },
358 { WSAELOOP, ELOOP },
359 { WSAENAMETOOLONG, ENAMETOOLONG },
360 { WSAENOTEMPTY, ENOTEMPTY },
361 { WSAEPROTOTYPE, EPROTOTYPE },
362 { WSAVERNOTSUPPORTED, ENOTSUP },
363 };
364 DWORD wsa, i;
365
366 wsa = WSAGetLastError();
367 for (i = 0; i < countof(map); i++)
368 {
369 if (map[i].wsa == wsa)
370 {
371 errno = map[i].err;
372 return retval;
373 }
374 }
375 errno = ENOENT;
376 return retval;
377 }
378 errno = 0;
379 return retval;
380 }
381
382 /**
383 * Check and clear the dontwait flag
384 */
385 static bool check_dontwait(int *flags)
386 {
387 if (*flags & MSG_DONTWAIT)
388 {
389 *flags &= ~MSG_DONTWAIT;
390 return TRUE;
391 }
392 return FALSE;
393 }
394
395 /**
396 * See header
397 */
398 #undef shutdown
399 int windows_shutdown(int sockfd, int how)
400 {
401 return wserr(shutdown(sockfd, how));
402 }
403
404 /**
405 * See header
406 */
407 #undef accept
408 int windows_accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen)
409 {
410 return wserr(accept(sockfd, addr, addrlen));
411 }
412
413 /**
414 * See header
415 */
416 #undef bind
417 int windows_bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen)
418 {
419 return wserr(bind(sockfd, addr, addrlen));
420 }
421
422 /**
423 * See header
424 */
425 #undef connect
426 int windows_connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen)
427 {
428 return wserr(connect(sockfd, addr, addrlen));
429 }
430
431 /**
432 * See header
433 */
434 #undef getsockname
435 int windows_getsockname(int sockfd, struct sockaddr *addr, socklen_t *addrlen)
436 {
437 return wserr(getsockname(sockfd, addr, addrlen));
438 }
439
440 /**
441 * See header
442 */
443 #undef getsockopt
444 int windows_getsockopt(int sockfd, int level, int optname,
445 void *optval, socklen_t *optlen)
446 {
447 return wserr(getsockopt(sockfd, level, optname, optval, optlen));
448 }
449
450 /**
451 * See header
452 */
453 #undef setsockopt
454 int windows_setsockopt(int sockfd, int level, int optname,
455 const void *optval, socklen_t optlen)
456 {
457 return wserr(setsockopt(sockfd, level, optname, optval, optlen));
458 }
459
460 /**
461 * See header
462 */
463 #undef socket
464 int windows_socket(int domain, int type, int protocol)
465 {
466 return wserr(socket(domain, type, protocol));
467 }
468
469 /**
470 * See header
471 */
472 #undef select
473 int windows_select(int nfds, fd_set *readfds, fd_set *writefds,
474 fd_set *exceptfds, struct timeval *timeout)
475 {
476 return wserr(select(nfds, readfds, writefds, exceptfds, timeout));
477 }
478
479 /**
480 * See header
481 */
482 #undef close
483 int windows_close(int fd)
484 {
485 int ret;
486
487 ret = close(fd);
488 if (ret == -1 && errno == EBADF)
489 { /* Winsock socket? */
490 ret = wserr(closesocket(fd));
491 }
492 return ret;
493 }
494
495 /**
496 * See header
497 */
498 #undef recv
499 ssize_t windows_recv(int sockfd, void *buf, size_t len, int flags)
500 {
501 u_long on = 1, off = 0;
502 ssize_t outlen = -1;
503
504 if (!check_dontwait(&flags))
505 {
506 return wserr(recv(sockfd, buf, len, flags));
507 }
508 if (wserr(ioctlsocket(sockfd, FIONBIO, &on) == 0))
509 {
510 outlen = wserr(recv(sockfd, buf, len, flags));
511 ioctlsocket(sockfd, FIONBIO, &off);
512 }
513 return outlen;
514 }
515
516 /**
517 * See header
518 */
519 #undef recvfrom
520 ssize_t windows_recvfrom(int sockfd, void *buf, size_t len, int flags,
521 struct sockaddr *src_addr, socklen_t *addrlen)
522 {
523 u_long on = 1, off = 0;
524 ssize_t outlen = -1;
525
526 if (!check_dontwait(&flags))
527 {
528 return wserr(recvfrom(sockfd, buf, len, flags, src_addr, addrlen));
529 }
530 if (wserr(ioctlsocket(sockfd, FIONBIO, &on)) == 0)
531 {
532 outlen = wserr(recvfrom(sockfd, buf, len, flags, src_addr, addrlen));
533 ioctlsocket(sockfd, FIONBIO, &off);
534 }
535 return outlen;
536 }
537
538 /**
539 * See header
540 */
541 #undef send
542 ssize_t windows_send(int sockfd, const void *buf, size_t len, int flags)
543 {
544 u_long on = 1, off = 0;
545 ssize_t outlen = -1;
546
547 if (!check_dontwait(&flags))
548 {
549 return wserr(send(sockfd, buf, len, flags));
550 }
551 if (wserr(ioctlsocket(sockfd, FIONBIO, &on)) == 0)
552 {
553 outlen = wserr(send(sockfd, buf, len, flags));
554 ioctlsocket(sockfd, FIONBIO, &off);
555 }
556 return outlen;
557 }
558
559 /**
560 * See header
561 */
562 #undef sendto
563 ssize_t windows_sendto(int sockfd, const void *buf, size_t len, int flags,
564 const struct sockaddr *dest_addr, socklen_t addrlen)
565 {
566 u_long on = 1, off = 0;
567 ssize_t outlen = -1;
568
569 if (!check_dontwait(&flags))
570 {
571 return wserr(sendto(sockfd, buf, len, flags, dest_addr, addrlen));
572 }
573 if (wserr(ioctlsocket(sockfd, FIONBIO, &on)) == 0)
574 {
575 outlen = wserr(sendto(sockfd, buf, len, flags, dest_addr, addrlen));
576 ioctlsocket(sockfd, FIONBIO, &off);
577 }
578 return outlen;
579 }