1 /*
2 * based on Windows Sockets 1.1 specs
3 *
4 * Copyright (C) 1993,1994,1996,1997 John Brezak, Erik Bos, Alex Korobka.
5 * Copyright (C) 2005 Marcus Meissner
6 * Copyright (C) 2006-2008 Kai Blin
7 *
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 *
22 * NOTE: If you make any changes to fix a particular app, make sure
23 * they don't break something else like Netscape or telnet and ftp
24 * clients and servers (www.winsite.com got a lot of those).
25 */
26
27 #include "config.h"
28 #include "wine/port.h"
29
30 #include <stdarg.h>
31 #include <stdio.h>
32 #include <string.h>
33 #include <sys/types.h>
34 #ifdef HAVE_SYS_IPC_H
35 # include <sys/ipc.h>
36 #endif
37 #ifdef HAVE_SYS_IOCTL_H
38 # include <sys/ioctl.h>
39 #endif
40 #ifdef HAVE_SYS_FILIO_H
41 # include <sys/filio.h>
42 #endif
43 #ifdef HAVE_SYS_SOCKIO_H
44 # include <sys/sockio.h>
45 #endif
46
47 #if defined(__EMX__)
48 # include <sys/so_ioctl.h>
49 #endif
50
51 #ifdef HAVE_SYS_PARAM_H
52 # include <sys/param.h>
53 #endif
54
55 #ifdef HAVE_SYS_MSG_H
56 # include <sys/msg.h>
57 #endif
58 #ifdef HAVE_SYS_WAIT_H
59 # include <sys/wait.h>
60 #endif
61 #ifdef HAVE_SYS_UIO_H
62 # include <sys/uio.h>
63 #endif
64 #ifdef HAVE_SYS_SOCKET_H
65 #include <sys/socket.h>
66 #endif
67 #ifdef HAVE_NETINET_IN_H
68 # include <netinet/in.h>
69 #endif
70 #ifdef HAVE_NETINET_TCP_H
71 # include <netinet/tcp.h>
72 #endif
73 #ifdef HAVE_ARPA_INET_H
74 # include <arpa/inet.h>
75 #endif
76 #include <ctype.h>
77 #include <fcntl.h>
78 #include <errno.h>
79 #ifdef HAVE_SYS_ERRNO_H
80 #include <sys/errno.h>
81 #endif
82 #ifdef HAVE_NETDB_H
83 #include <netdb.h>
84 #endif
85 #ifdef HAVE_UNISTD_H
86 # include <unistd.h>
87 #endif
88 #include <stdlib.h>
89 #ifdef HAVE_ARPA_NAMESER_H
90 # include <arpa/nameser.h>
91 #endif
92 #ifdef HAVE_RESOLV_H
93 # include <resolv.h>
94 #endif
95 #ifdef HAVE_NET_IF_H
96 # include <net/if.h>
97 #endif
98
99 #ifdef HAVE_NETIPX_IPX_H
100 # include <netipx/ipx.h>
101 # define HAVE_IPX
102 #elif defined(HAVE_LINUX_IPX_H)
103 # ifdef HAVE_ASM_TYPES_H
104 # include <asm/types.h>
105 # endif
106 # include <linux/ipx.h>
107 # define HAVE_IPX
108 #endif
109
110 #ifdef HAVE_POLL_H
111 #include <poll.h>
112 #endif
113 #ifdef HAVE_SYS_POLL_H
114 # include <sys/poll.h>
115 #endif
116 #ifdef HAVE_SYS_TIME_H
117 # include <sys/time.h>
118 #endif
119
120 #define NONAMELESSUNION
121 #define NONAMELESSSTRUCT
122 #include "ntstatus.h"
123 #define WIN32_NO_STATUS
124 #include "windef.h"
125 #include "winbase.h"
126 #include "wingdi.h"
127 #include "winuser.h"
128 #include "winerror.h"
129 #include "winnls.h"
130 #include "winsock2.h"
131 #include "mswsock.h"
132 #include "ws2tcpip.h"
133 #include "ws2spi.h"
134 #include "wsipx.h"
135 #include "mstcpip.h"
136 #include "winnt.h"
137 #include "iphlpapi.h"
138 #include "wine/server.h"
139 #include "wine/debug.h"
140 #include "wine/unicode.h"
141
142 #ifdef HAVE_IPX
143 # include "wsnwlink.h"
144 #endif
145
146
147 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
148 # define sipx_network sipx_addr.x_net
149 # define sipx_node sipx_addr.x_host.c_host
150 #endif /* __FreeBSD__ */
151
152 #ifndef INADDR_NONE
153 #define INADDR_NONE ~0UL
154 #endif
155
156 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
157
158 /* critical section to protect some non-reentrant net function */
159 extern CRITICAL_SECTION csWSgetXXXbyYYY;
160
161 union generic_unix_sockaddr
162 {
163 struct sockaddr addr;
164 char data[128]; /* should be big enough for all families */
165 };
166
167 static inline const char *debugstr_sockaddr( const struct WS_sockaddr *a )
168 {
169 if (!a) return "(nil)";
170 return wine_dbg_sprintf("{ family %d, address %s, port %d }",
171 ((const struct sockaddr_in *)a)->sin_family,
172 inet_ntoa(((const struct sockaddr_in *)a)->sin_addr),
173 ntohs(((const struct sockaddr_in *)a)->sin_port));
174 }
175
176 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
177 #define SOCKET2HANDLE(s) ((HANDLE)(s))
178 #define HANDLE2SOCKET(h) ((SOCKET)(h))
179
180 /****************************************************************
181 * Async IO declarations
182 ****************************************************************/
183
184 typedef struct ws2_async
185 {
186 HANDLE hSocket;
187 int type;
188 LPWSAOVERLAPPED user_overlapped;
189 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
190 IO_STATUS_BLOCK local_iosb;
191 struct WS_sockaddr *addr;
192 union
193 {
194 int val; /* for send operations */
195 int *ptr; /* for recv operations */
196 } addrlen;
197 DWORD flags;
198 unsigned int n_iovecs;
199 unsigned int first_iovec;
200 struct iovec iovec[1];
201 } ws2_async;
202
203 /****************************************************************/
204
205 /* ----------------------------------- internal data */
206
207 /* ws_... struct conversion flags */
208
209 typedef struct /* WSAAsyncSelect() control struct */
210 {
211 HANDLE service, event, sock;
212 HWND hWnd;
213 UINT uMsg;
214 LONG lEvent;
215 } ws_select_info;
216
217 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
218 #define WS_MAX_UDP_DATAGRAM 1024
219 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
220
221 /* hostent's, servent's and protent's are stored in one buffer per thread,
222 * as documented on MSDN for the functions that return any of the buffers */
223 struct per_thread_data
224 {
225 int opentype;
226 struct WS_hostent *he_buffer;
227 struct WS_servent *se_buffer;
228 struct WS_protoent *pe_buffer;
229 int he_len;
230 int se_len;
231 int pe_len;
232 };
233
234 static INT num_startup; /* reference counter */
235 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
236
237 /* function prototypes */
238 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
239 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
240 static struct WS_servent *WS_dup_se(const struct servent* p_se);
241
242 int WSAIOCTL_GetInterfaceCount(void);
243 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
244
245 UINT wsaErrno(void);
246 UINT wsaHerrno(int errnr);
247
248 #define MAP_OPTION(opt) { WS_##opt, opt }
249
250 static const int ws_sock_map[][2] =
251 {
252 MAP_OPTION( SO_DEBUG ),
253 MAP_OPTION( SO_ACCEPTCONN ),
254 MAP_OPTION( SO_REUSEADDR ),
255 MAP_OPTION( SO_KEEPALIVE ),
256 MAP_OPTION( SO_DONTROUTE ),
257 MAP_OPTION( SO_BROADCAST ),
258 MAP_OPTION( SO_LINGER ),
259 MAP_OPTION( SO_OOBINLINE ),
260 MAP_OPTION( SO_SNDBUF ),
261 MAP_OPTION( SO_RCVBUF ),
262 MAP_OPTION( SO_ERROR ),
263 MAP_OPTION( SO_TYPE ),
264 #ifdef SO_RCVTIMEO
265 MAP_OPTION( SO_RCVTIMEO ),
266 #endif
267 #ifdef SO_SNDTIMEO
268 MAP_OPTION( SO_SNDTIMEO ),
269 #endif
270 };
271
272 static const int ws_tcp_map[][2] =
273 {
274 #ifdef TCP_NODELAY
275 MAP_OPTION( TCP_NODELAY ),
276 #endif
277 };
278
279 static const int ws_ip_map[][2] =
280 {
281 MAP_OPTION( IP_MULTICAST_IF ),
282 MAP_OPTION( IP_MULTICAST_TTL ),
283 MAP_OPTION( IP_MULTICAST_LOOP ),
284 MAP_OPTION( IP_ADD_MEMBERSHIP ),
285 MAP_OPTION( IP_DROP_MEMBERSHIP ),
286 MAP_OPTION( IP_OPTIONS ),
287 #ifdef IP_HDRINCL
288 MAP_OPTION( IP_HDRINCL ),
289 #endif
290 MAP_OPTION( IP_TOS ),
291 MAP_OPTION( IP_TTL ),
292 };
293
294 static const int ws_af_map[][2] =
295 {
296 MAP_OPTION( AF_UNSPEC ),
297 MAP_OPTION( AF_INET ),
298 MAP_OPTION( AF_INET6 ),
299 #ifdef HAVE_IPX
300 MAP_OPTION( AF_IPX ),
301 #endif
302 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
303 };
304
305 static const int ws_socktype_map[][2] =
306 {
307 MAP_OPTION( SOCK_DGRAM ),
308 MAP_OPTION( SOCK_STREAM ),
309 MAP_OPTION( SOCK_RAW ),
310 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
311 };
312
313 static const int ws_proto_map[][2] =
314 {
315 MAP_OPTION( IPPROTO_IP ),
316 MAP_OPTION( IPPROTO_TCP ),
317 MAP_OPTION( IPPROTO_UDP ),
318 MAP_OPTION( IPPROTO_ICMP ),
319 MAP_OPTION( IPPROTO_IGMP ),
320 MAP_OPTION( IPPROTO_RAW ),
321 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
322 };
323
324 static const int ws_aiflag_map[][2] =
325 {
326 MAP_OPTION( AI_PASSIVE ),
327 MAP_OPTION( AI_CANONNAME ),
328 MAP_OPTION( AI_NUMERICHOST ),
329 /* Linux/UNIX knows a lot more. But Windows only
330 * has 3 as far as I could see. -Marcus
331 */
332 };
333
334 static const int ws_niflag_map[][2] =
335 {
336 MAP_OPTION( NI_NOFQDN ),
337 MAP_OPTION( NI_NUMERICHOST ),
338 MAP_OPTION( NI_NAMEREQD ),
339 MAP_OPTION( NI_NUMERICSERV ),
340 MAP_OPTION( NI_DGRAM ),
341 };
342
343 static const int ws_eai_map[][2] =
344 {
345 MAP_OPTION( EAI_AGAIN ),
346 MAP_OPTION( EAI_BADFLAGS ),
347 MAP_OPTION( EAI_FAIL ),
348 MAP_OPTION( EAI_FAMILY ),
349 MAP_OPTION( EAI_MEMORY ),
350 /* Note: EAI_NODATA is deprecated, but still
351 * used by Windows and Linux... We map the newer
352 * EAI_NONAME to EAI_NODATA for now until Windows
353 * changes too.
354 */
355 #ifdef EAI_NODATA
356 MAP_OPTION( EAI_NODATA ),
357 #endif
358 #ifdef EAI_NONAME
359 { WS_EAI_NODATA, EAI_NONAME },
360 #endif
361
362 MAP_OPTION( EAI_SERVICE ),
363 MAP_OPTION( EAI_SOCKTYPE ),
364 { 0, 0 }
365 };
366
367 static const char magic_loopback_addr[] = {127, 12, 34, 56};
368
369 static inline DWORD NtStatusToWSAError( const DWORD status )
370 {
371 /* We only need to cover the status codes set by server async request handling */
372 DWORD wserr;
373 switch ( status )
374 {
375 case STATUS_SUCCESS: wserr = 0; break;
376 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
377 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
378 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
379 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
380 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
381 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
382 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
383 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
384 default:
385 if ( status >= WSABASEERR && status <= WSABASEERR+1004 )
386 /* It is not an NT status code but a winsock error */
387 wserr = status;
388 else
389 {
390 wserr = RtlNtStatusToDosError( status );
391 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
392 }
393 }
394 return wserr;
395 }
396
397 /* set last error code from NT status without mapping WSA errors */
398 static inline unsigned int set_error( unsigned int err )
399 {
400 if (err)
401 {
402 err = NtStatusToWSAError( err );
403 SetLastError( err );
404 }
405 return err;
406 }
407
408 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
409 {
410 int fd;
411 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
412 return -1;
413 return fd;
414 }
415
416 static inline void release_sock_fd( SOCKET s, int fd )
417 {
418 wine_server_release_fd( SOCKET2HANDLE(s), fd );
419 }
420
421 static void _enable_event( HANDLE s, unsigned int event,
422 unsigned int sstate, unsigned int cstate )
423 {
424 SERVER_START_REQ( enable_socket_event )
425 {
426 req->handle = wine_server_obj_handle( s );
427 req->mask = event;
428 req->sstate = sstate;
429 req->cstate = cstate;
430 wine_server_call( req );
431 }
432 SERVER_END_REQ;
433 }
434
435 static int _is_blocking(SOCKET s)
436 {
437 int ret;
438 SERVER_START_REQ( get_socket_event )
439 {
440 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
441 req->service = FALSE;
442 req->c_event = 0;
443 wine_server_call( req );
444 ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
445 }
446 SERVER_END_REQ;
447 return ret;
448 }
449
450 static unsigned int _get_sock_mask(SOCKET s)
451 {
452 unsigned int ret;
453 SERVER_START_REQ( get_socket_event )
454 {
455 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
456 req->service = FALSE;
457 req->c_event = 0;
458 wine_server_call( req );
459 ret = reply->mask;
460 }
461 SERVER_END_REQ;
462 return ret;
463 }
464
465 static void _sync_sock_state(SOCKET s)
466 {
467 /* do a dummy wineserver request in order to let
468 the wineserver run through its select loop once */
469 (void)_is_blocking(s);
470 }
471
472 static int _get_sock_error(SOCKET s, unsigned int bit)
473 {
474 int events[FD_MAX_EVENTS];
475
476 SERVER_START_REQ( get_socket_event )
477 {
478 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
479 req->service = FALSE;
480 req->c_event = 0;
481 wine_server_set_reply( req, events, sizeof(events) );
482 wine_server_call( req );
483 }
484 SERVER_END_REQ;
485 return events[bit];
486 }
487
488 static struct per_thread_data *get_per_thread_data(void)
489 {
490 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
491 /* lazy initialization */
492 if (!ptb)
493 {
494 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
495 NtCurrentTeb()->WinSockData = ptb;
496 }
497 return ptb;
498 }
499
500 static void free_per_thread_data(void)
501 {
502 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
503
504 if (!ptb) return;
505
506 /* delete scratch buffers */
507 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
508 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
509 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
510 ptb->he_buffer = NULL;
511 ptb->se_buffer = NULL;
512 ptb->pe_buffer = NULL;
513
514 HeapFree( GetProcessHeap(), 0, ptb );
515 NtCurrentTeb()->WinSockData = NULL;
516 }
517
518 /***********************************************************************
519 * DllMain (WS2_32.init)
520 */
521 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
522 {
523 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
524 switch (fdwReason) {
525 case DLL_PROCESS_ATTACH:
526 break;
527 case DLL_PROCESS_DETACH:
528 free_per_thread_data();
529 num_startup = 0;
530 break;
531 case DLL_THREAD_DETACH:
532 free_per_thread_data();
533 break;
534 }
535 return TRUE;
536 }
537
538 /***********************************************************************
539 * convert_sockopt()
540 *
541 * Converts socket flags from Windows format.
542 * Return 1 if converted, 0 if not (error).
543 */
544 static int convert_sockopt(INT *level, INT *optname)
545 {
546 unsigned int i;
547 switch (*level)
548 {
549 case WS_SOL_SOCKET:
550 *level = SOL_SOCKET;
551 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
552 if( ws_sock_map[i][0] == *optname )
553 {
554 *optname = ws_sock_map[i][1];
555 return 1;
556 }
557 }
558 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
559 break;
560 case WS_IPPROTO_TCP:
561 *level = IPPROTO_TCP;
562 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
563 if ( ws_tcp_map[i][0] == *optname )
564 {
565 *optname = ws_tcp_map[i][1];
566 return 1;
567 }
568 }
569 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
570 break;
571 case WS_IPPROTO_IP:
572 *level = IPPROTO_IP;
573 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
574 if (ws_ip_map[i][0] == *optname )
575 {
576 *optname = ws_ip_map[i][1];
577 return 1;
578 }
579 }
580 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
581 break;
582 default: FIXME("Unimplemented or unknown socket level\n");
583 }
584 return 0;
585 }
586
587 /* ----------------------------------- Per-thread info (or per-process?) */
588
589 static char *strdup_lower(const char *str)
590 {
591 int i;
592 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
593
594 if (ret)
595 {
596 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
597 ret[i] = 0;
598 }
599 else SetLastError(WSAENOBUFS);
600 return ret;
601 }
602
603 static inline int sock_error_p(int s)
604 {
605 unsigned int optval, optlen;
606
607 optlen = sizeof(optval);
608 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
609 if (optval) WARN("\t[%i] error: %d\n", s, optval);
610 return optval != 0;
611 }
612
613 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
614 * from an fd and return the value converted to milli seconds
615 * or -1 if there is an infinite time out */
616 static inline int get_rcvsnd_timeo( int fd, int optname)
617 {
618 struct timeval tv;
619 unsigned int len = sizeof(tv);
620 int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
621 if( ret >= 0)
622 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
623 if( ret <= 0 ) /* tv == {0,0} means infinite time out */
624 return -1;
625 return ret;
626 }
627
628 /* macro wrappers for portability */
629 #ifdef SO_RCVTIMEO
630 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
631 #else
632 #define GET_RCVTIMEO(fd) (-1)
633 #endif
634
635 #ifdef SO_SNDTIMEO
636 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
637 #else
638 #define GET_SNDTIMEO(fd) (-1)
639 #endif
640
641 /* utility: given an fd, will block until one of the events occurs */
642 static inline int do_block( int fd, int events, int timeout )
643 {
644 struct pollfd pfd;
645 int ret;
646
647 pfd.fd = fd;
648 pfd.events = events;
649
650 while ((ret = poll(&pfd, 1, timeout)) < 0)
651 {
652 if (errno != EINTR)
653 return -1;
654 }
655 if( ret == 0 )
656 return 0;
657 return pfd.revents;
658 }
659
660 static int
661 convert_af_w2u(int windowsaf) {
662 unsigned int i;
663
664 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
665 if (ws_af_map[i][0] == windowsaf)
666 return ws_af_map[i][1];
667 FIXME("unhandled Windows address family %d\n", windowsaf);
668 return -1;
669 }
670
671 static int
672 convert_af_u2w(int unixaf) {
673 unsigned int i;
674
675 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
676 if (ws_af_map[i][1] == unixaf)
677 return ws_af_map[i][0];
678 FIXME("unhandled UNIX address family %d\n", unixaf);
679 return -1;
680 }
681
682 static int
683 convert_proto_w2u(int windowsproto) {
684 unsigned int i;
685
686 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
687 if (ws_proto_map[i][0] == windowsproto)
688 return ws_proto_map[i][1];
689 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
690 return -1;
691 }
692
693 static int
694 convert_proto_u2w(int unixproto) {
695 unsigned int i;
696
697 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
698 if (ws_proto_map[i][1] == unixproto)
699 return ws_proto_map[i][0];
700 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
701 return -1;
702 }
703
704 static int
705 convert_socktype_w2u(int windowssocktype) {
706 unsigned int i;
707
708 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
709 if (ws_socktype_map[i][0] == windowssocktype)
710 return ws_socktype_map[i][1];
711 FIXME("unhandled Windows socket type %d\n", windowssocktype);
712 return -1;
713 }
714
715 static int
716 convert_socktype_u2w(int unixsocktype) {
717 unsigned int i;
718
719 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
720 if (ws_socktype_map[i][1] == unixsocktype)
721 return ws_socktype_map[i][0];
722 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
723 return -1;
724 }
725
726 /* ----------------------------------- API -----
727 *
728 * Init / cleanup / error checking.
729 */
730
731 /***********************************************************************
732 * WSAStartup (WS2_32.115)
733 */
734 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
735 {
736 TRACE("verReq=%x\n", wVersionRequested);
737
738 if (LOBYTE(wVersionRequested) < 1)
739 return WSAVERNOTSUPPORTED;
740
741 if (!lpWSAData) return WSAEINVAL;
742
743 num_startup++;
744
745 /* that's the whole of the negotiation for now */
746 lpWSAData->wVersion = wVersionRequested;
747 /* return winsock information */
748 lpWSAData->wHighVersion = 0x0202;
749 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
750 strcpy(lpWSAData->szSystemStatus, "Running" );
751 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
752 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
753 /* don't do anything with lpWSAData->lpVendorInfo */
754 /* (some apps don't allocate the space for this field) */
755
756 TRACE("succeeded\n");
757 return 0;
758 }
759
760
761 /***********************************************************************
762 * WSACleanup (WS2_32.116)
763 */
764 INT WINAPI WSACleanup(void)
765 {
766 if (num_startup) {
767 num_startup--;
768 return 0;
769 }
770 SetLastError(WSANOTINITIALISED);
771 return SOCKET_ERROR;
772 }
773
774
775 /***********************************************************************
776 * WSAGetLastError (WINSOCK.111)
777 * WSAGetLastError (WS2_32.111)
778 */
779 INT WINAPI WSAGetLastError(void)
780 {
781 return GetLastError();
782 }
783
784 /***********************************************************************
785 * WSASetLastError (WS2_32.112)
786 */
787 void WINAPI WSASetLastError(INT iError) {
788 SetLastError(iError);
789 }
790
791 static struct WS_hostent *check_buffer_he(int size)
792 {
793 struct per_thread_data * ptb = get_per_thread_data();
794 if (ptb->he_buffer)
795 {
796 if (ptb->he_len >= size ) return ptb->he_buffer;
797 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
798 }
799 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
800 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
801 return ptb->he_buffer;
802 }
803
804 static struct WS_servent *check_buffer_se(int size)
805 {
806 struct per_thread_data * ptb = get_per_thread_data();
807 if (ptb->se_buffer)
808 {
809 if (ptb->se_len >= size ) return ptb->se_buffer;
810 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
811 }
812 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
813 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
814 return ptb->se_buffer;
815 }
816
817 static struct WS_protoent *check_buffer_pe(int size)
818 {
819 struct per_thread_data * ptb = get_per_thread_data();
820 if (ptb->pe_buffer)
821 {
822 if (ptb->pe_len >= size ) return ptb->pe_buffer;
823 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
824 }
825 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
826 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
827 return ptb->pe_buffer;
828 }
829
830 /* ----------------------------------- i/o APIs */
831
832 #ifdef HAVE_IPX
833 #define SUPPORTED_PF(pf) ((pf)==WS_AF_INET || (pf)== WS_AF_IPX || (pf) == WS_AF_INET6)
834 #else
835 #define SUPPORTED_PF(pf) ((pf)==WS_AF_INET || (pf) == WS_AF_INET6)
836 #endif
837
838
839 /**********************************************************************/
840
841 /* Returns the length of the converted address if successful, 0 if it was too small to
842 * start with.
843 */
844 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
845 union generic_unix_sockaddr *uaddr)
846 {
847 unsigned int uaddrlen = 0;
848
849 switch (wsaddr->sa_family)
850 {
851 #ifdef HAVE_IPX
852 case WS_AF_IPX:
853 {
854 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
855 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
856
857 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
858 return 0;
859
860 uaddrlen = sizeof(struct sockaddr_ipx);
861 memset( uaddr, 0, uaddrlen );
862 uipx->sipx_family=AF_IPX;
863 uipx->sipx_port=wsipx->sa_socket;
864 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
865 * in one go
866 */
867 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
868 #ifdef IPX_FRAME_NONE
869 uipx->sipx_type=IPX_FRAME_NONE;
870 #endif
871 break;
872 }
873 #endif
874 case WS_AF_INET6: {
875 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
876 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
877
878 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
879 * scope_id, one without.
880 */
881 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
882 uaddrlen = sizeof(struct sockaddr_in6);
883 memset( uaddr, 0, uaddrlen );
884 uin6->sin6_family = AF_INET6;
885 uin6->sin6_port = win6->sin6_port;
886 uin6->sin6_flowinfo = win6->sin6_flowinfo;
887 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
888 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
889 #endif
890 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
891 break;
892 }
893 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
894 return 0;
895 }
896 case WS_AF_INET: {
897 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
898 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
899
900 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
901 return 0;
902 uaddrlen = sizeof(struct sockaddr_in);
903 memset( uaddr, 0, uaddrlen );
904 uin->sin_family = AF_INET;
905 uin->sin_port = win->sin_port;
906 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
907 break;
908 }
909 case WS_AF_UNSPEC: {
910 /* Try to determine the needed space by the passed windows sockaddr space */
911 switch (wsaddrlen) {
912 default: /* likely a ipv4 address */
913 case sizeof(struct WS_sockaddr_in):
914 uaddrlen = sizeof(struct sockaddr_in);
915 break;
916 #ifdef HAVE_IPX
917 case sizeof(struct WS_sockaddr_ipx):
918 uaddrlen = sizeof(struct sockaddr_ipx);
919 break;
920 #endif
921 case sizeof(struct WS_sockaddr_in6):
922 case sizeof(struct WS_sockaddr_in6_old):
923 uaddrlen = sizeof(struct sockaddr_in6);
924 break;
925 }
926 memset( uaddr, 0, uaddrlen );
927 break;
928 }
929 default:
930 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
931 return 0;
932 }
933 return uaddrlen;
934 }
935
936 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
937 {
938 switch (uaddr->sa_family)
939 {
940 #ifdef HAVE_IPX
941 case AF_IPX:
942 FIXME("don't know how to tell if IPX socket is bound, assuming it is!\n");
943 return TRUE;
944 #endif
945 case AF_INET6:
946 {
947 static const struct sockaddr_in6 emptyAddr;
948 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
949 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
950 }
951 case AF_INET:
952 {
953 static const struct sockaddr_in emptyAddr;
954 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
955 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
956 }
957 case AF_UNSPEC:
958 return FALSE;
959 default:
960 FIXME("unknown address family %d\n", uaddr->sa_family);
961 return TRUE;
962 }
963 }
964
965 /* Returns 0 if successful, -1 if the buffer is too small */
966 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
967 {
968 int res;
969
970 switch(uaddr->sa_family)
971 {
972 #ifdef HAVE_IPX
973 case AF_IPX:
974 {
975 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
976 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
977
978 res=-1;
979 switch (*wsaddrlen) /* how much can we copy? */
980 {
981 default:
982 res=0; /* enough */
983 *wsaddrlen = sizeof(*wsipx);
984 wsipx->sa_socket=uipx->sipx_port;
985 /* fall through */
986 case 13:
987 case 12:
988 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
989 /* fall through */
990 case 11:
991 case 10:
992 case 9:
993 case 8:
994 case 7:
995 case 6:
996 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
997 /* fall through */
998 case 5:
999 case 4:
1000 case 3:
1001 case 2:
1002 wsipx->sa_family=WS_AF_IPX;
1003 /* fall through */
1004 case 1:
1005 case 0:
1006 /* way too small */
1007 break;
1008 }
1009 }
1010 break;
1011 #endif
1012 case AF_INET6: {
1013 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1014 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1015
1016 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1017 return -1;
1018 win6old->sin6_family = WS_AF_INET6;
1019 win6old->sin6_port = uin6->sin6_port;
1020 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1021 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1022 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1023 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1024 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1025 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1026 win6->sin6_scope_id = uin6->sin6_scope_id;
1027 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1028 }
1029 #endif
1030 return 0;
1031 }
1032 case AF_INET: {
1033 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1034 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1035
1036 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1037 return -1;
1038 win->sin_family = WS_AF_INET;
1039 win->sin_port = uin->sin_port;
1040 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1041 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1042 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1043 return 0;
1044 }
1045 case AF_UNSPEC: {
1046 memset(wsaddr,0,*wsaddrlen);
1047 return 0;
1048 }
1049 default:
1050 FIXME("Unknown address family %d\n", uaddr->sa_family);
1051 return -1;
1052 }
1053 return res;
1054 }
1055
1056 /**************************************************************************
1057 * Functions for handling overlapped I/O
1058 **************************************************************************/
1059
1060 /* user APC called upon async completion */
1061 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1062 {
1063 ws2_async *wsa = arg;
1064
1065 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
1066 iosb->Information, wsa->user_overlapped,
1067 wsa->flags );
1068 HeapFree( GetProcessHeap(), 0, wsa );
1069 }
1070
1071 /***********************************************************************
1072 * WS2_recv (INTERNAL)
1073 *
1074 * Workhorse for both synchronous and asynchronous recv() operations.
1075 */
1076 static int WS2_recv( int fd, struct ws2_async *wsa )
1077 {
1078 struct msghdr hdr;
1079 union generic_unix_sockaddr unix_sockaddr;
1080 int n;
1081
1082 hdr.msg_name = NULL;
1083
1084 if (wsa->addr)
1085 {
1086 hdr.msg_namelen = sizeof(unix_sockaddr);
1087 hdr.msg_name = &unix_sockaddr;
1088 }
1089 else
1090 hdr.msg_namelen = 0;
1091
1092 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1093 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1094 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1095 hdr.msg_accrights = NULL;
1096 hdr.msg_accrightslen = 0;
1097 #else
1098 hdr.msg_control = NULL;
1099 hdr.msg_controllen = 0;
1100 hdr.msg_flags = 0;
1101 #endif
1102
1103 if ( (n = recvmsg(fd, &hdr, wsa->flags)) == -1 )
1104 return -1;
1105
1106 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1107 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1108 *
1109 * quoting linux 2.6 net/ipv4/tcp.c:
1110 * "According to UNIX98, msg_name/msg_namelen are ignored
1111 * on connected socket. I was just happy when found this 8) --ANK"
1112 *
1113 * likewise MSDN says that lpFrom and lpFromlen are ignored for
1114 * connection-oriented sockets, so don't try to update lpFrom.
1115 */
1116 if (wsa->addr && hdr.msg_namelen)
1117 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
1118
1119 return n;
1120 }
1121
1122 /***********************************************************************
1123 * WS2_async_recv (INTERNAL)
1124 *
1125 * Handler for overlapped recv() operations.
1126 */
1127 static NTSTATUS WS2_async_recv( void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, ULONG *total )
1128 {
1129 ws2_async* wsa = user;
1130 int result = 0, fd;
1131
1132 switch (status)
1133 {
1134 case STATUS_ALERTED:
1135 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
1136 break;
1137
1138 result = WS2_recv( fd, wsa );
1139 wine_server_release_fd( wsa->hSocket, fd );
1140 if (result >= 0)
1141 {
1142 status = STATUS_SUCCESS;
1143 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1144 }
1145 else
1146 {
1147 if (errno == EINTR || errno == EAGAIN)
1148 {
1149 status = STATUS_PENDING;
1150 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1151 }
1152 else
1153 {
1154 result = 0;
1155 status = wsaErrno(); /* FIXME: is this correct ???? */
1156 }
1157 }
1158 break;
1159 }
1160 if (status != STATUS_PENDING)
1161 {
1162 iosb->u.Status = status;
1163 iosb->Information = *total = result;
1164 }
1165 return status;
1166 }
1167
1168 /***********************************************************************
1169 * WS2_send (INTERNAL)
1170 *
1171 * Workhorse for both synchronous and asynchronous send() operations.
1172 */
1173 static int WS2_send( int fd, struct ws2_async *wsa )
1174 {
1175 struct msghdr hdr;
1176 union generic_unix_sockaddr unix_addr;
1177
1178 hdr.msg_name = NULL;
1179 hdr.msg_namelen = 0;
1180
1181 if (wsa->addr)
1182 {
1183 hdr.msg_name = &unix_addr;
1184 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
1185 if ( !hdr.msg_namelen )
1186 {
1187 errno = EFAULT;
1188 return -1;
1189 }
1190
1191 #if defined(HAVE_IPX) && defined(SOL_IPX)
1192 if(wsa->addr->sa_family == WS_AF_IPX)
1193 {
1194 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
1195 int val=0;
1196 unsigned int len=sizeof(int);
1197
1198 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
1199 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
1200 * the packet type and then we can retrieve it using getsockopt. After that we can set the
1201 * ipx type in the sockaddr_opx structure with the stored value.
1202 */
1203 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
1204 uipx->sipx_type = val;
1205 }
1206 #endif
1207 }
1208
1209 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1210 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1211 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1212 hdr.msg_accrights = NULL;
1213 hdr.msg_accrightslen = 0;
1214 #else
1215 hdr.msg_control = NULL;
1216 hdr.msg_controllen = 0;
1217 hdr.msg_flags = 0;
1218 #endif
1219
1220 return sendmsg(fd, &hdr, wsa->flags);
1221 }
1222
1223 /***********************************************************************
1224 * WS2_async_send (INTERNAL)
1225 *
1226 * Handler for overlapped send() operations.
1227 */
1228 static NTSTATUS WS2_async_send(void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, ULONG *total )
1229 {
1230 ws2_async* wsa = user;
1231 int result = 0, fd;
1232
1233 switch (status)
1234 {
1235 case STATUS_ALERTED:
1236 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
1237 break;
1238
1239 /* check to see if the data is ready (non-blocking) */
1240 result = WS2_send( fd, wsa );
1241 wine_server_release_fd( wsa->hSocket, fd );
1242
1243 if (result >= 0)
1244 {
1245 int totalLength = 0;
1246 unsigned int i;
1247 status = STATUS_SUCCESS;
1248 for (i = 0; i < wsa->n_iovecs; i++)
1249 totalLength += wsa->iovec[i].iov_len;
1250 if (result < totalLength)
1251 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1252 }
1253 else
1254 {
1255 if (errno == EINTR || errno == EAGAIN)
1256 {
1257 status = STATUS_PENDING;
1258 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1259 }
1260 else
1261 {
1262 /* We set the status to a winsock error code and check for that
1263 later in NtStatusToWSAError () */
1264 status = wsaErrno();
1265 result = 0;
1266 }
1267 }
1268 break;
1269 }
1270 if (status != STATUS_PENDING)
1271 {
1272 iosb->u.Status = status;
1273 iosb->Information = *total = result;
1274 }
1275 return status;
1276 }
1277
1278 /***********************************************************************
1279 * WS2_async_shutdown (INTERNAL)
1280 *
1281 * Handler for shutdown() operations on overlapped sockets.
1282 */
1283 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status, ULONG *total )
1284 {
1285 ws2_async* wsa = user;
1286 int fd, err = 1;
1287
1288 switch (status)
1289 {
1290 case STATUS_ALERTED:
1291 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
1292 break;
1293
1294 switch ( wsa->type )
1295 {
1296 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
1297 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
1298 }
1299 wine_server_release_fd( wsa->hSocket, fd );
1300 status = err ? wsaErrno() : STATUS_SUCCESS;
1301 break;
1302 }
1303 *total = 0;
1304 iosb->u.Status = status;
1305 return status;
1306 }
1307
1308 /***********************************************************************
1309 * WS2_register_async_shutdown (INTERNAL)
1310 *
1311 * Helper function for WS_shutdown() on overlapped sockets.
1312 */
1313 static int WS2_register_async_shutdown( SOCKET s, int type )
1314 {
1315 struct ws2_async *wsa;
1316 NTSTATUS status;
1317
1318 TRACE("s %ld type %d\n", s, type);
1319
1320 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
1321 if ( !wsa )
1322 return WSAEFAULT;
1323
1324 wsa->hSocket = SOCKET2HANDLE(s);
1325 wsa->type = type;
1326 wsa->completion_func = NULL;
1327
1328 SERVER_START_REQ( register_async )
1329 {
1330 req->handle = wine_server_obj_handle( wsa->hSocket );
1331 req->type = type;
1332 req->async.callback = WS2_async_shutdown;
1333 req->async.iosb = &wsa->local_iosb;
1334 req->async.arg = wsa;
1335 req->async.apc = ws2_async_apc;
1336 req->async.cvalue = 0;
1337 status = wine_server_call( req );
1338 }
1339 SERVER_END_REQ;
1340
1341 if (status != STATUS_PENDING)
1342 {
1343 HeapFree( GetProcessHeap(), 0, wsa );
1344 return NtStatusToWSAError( status );
1345 }
1346 return 0;
1347 }
1348
1349 /***********************************************************************
1350 * accept (WS2_32.1)
1351 */
1352 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr,
1353 int *addrlen32)
1354 {
1355 SOCKET as;
1356 BOOL is_blocking;
1357
1358 TRACE("socket %04lx\n", s );
1359 is_blocking = _is_blocking(s);
1360
1361 do {
1362 if (is_blocking)
1363 {
1364 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1365 if (fd == -1) return INVALID_SOCKET;
1366 /* block here */
1367 do_block(fd, POLLIN, -1);
1368 _sync_sock_state(s); /* let wineserver notice connection */
1369 release_sock_fd( s, fd );
1370 /* retrieve any error codes from it */
1371 SetLastError(_get_sock_error(s, FD_ACCEPT_BIT));
1372 /* FIXME: care about the error? */
1373 }
1374 SERVER_START_REQ( accept_socket )
1375 {
1376 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1377 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
1378 req->attributes = OBJ_INHERIT;
1379 set_error( wine_server_call( req ) );
1380 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
1381 }
1382 SERVER_END_REQ;
1383 if (as)
1384 {
1385 if (addr) WS_getpeername(as, addr, addrlen32);
1386 return as;
1387 }
1388 } while (is_blocking);
1389 return INVALID_SOCKET;
1390 }
1391
1392 /***********************************************************************
1393 * bind (WS2_32.2)
1394 */
1395 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
1396 {
1397 int fd = get_sock_fd( s, 0, NULL );
1398 int res = SOCKET_ERROR;
1399
1400 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1401
1402 if (fd != -1)
1403 {
1404 if (!name || (name->sa_family && !SUPPORTED_PF(name->sa_family)))
1405 {
1406 SetLastError(WSAEAFNOSUPPORT);
1407 }
1408 else
1409 {
1410 union generic_unix_sockaddr uaddr;
1411 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1412 if (!uaddrlen)
1413 {
1414 SetLastError(WSAEFAULT);
1415 }
1416 else
1417 {
1418 #ifdef IPV6_V6ONLY
1419 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
1420 if (name->sa_family == WS_AF_INET6 &&
1421 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
1422 {
1423 int enable = 1;
1424 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
1425 {
1426 release_sock_fd( s, fd );
1427 SetLastError(WSAEAFNOSUPPORT);
1428 return INVALID_SOCKET;
1429 }
1430 }
1431 #endif
1432 if (name->sa_family == WS_AF_INET)
1433 {
1434 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
1435 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
1436 {
1437 /* Trying to bind to the default host interface, using
1438 * INADDR_ANY instead*/
1439 WARN("Trying to bind to magic IP address, using "
1440 "INADDR_ANY instead.\n");
1441 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
1442 }
1443 }
1444 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
1445 {
1446 int loc_errno = errno;
1447 WARN("\tfailure - errno = %i\n", errno);
1448 errno = loc_errno;
1449 switch (errno)
1450 {
1451 case EBADF:
1452 SetLastError(WSAENOTSOCK);
1453 break;
1454 case EADDRNOTAVAIL:
1455 SetLastError(WSAEINVAL);
1456 break;
1457 default:
1458 SetLastError(wsaErrno());
1459 break;
1460 }
1461 }
1462 else
1463 {
1464 res=0; /* success */
1465 }
1466 }
1467 }
1468 release_sock_fd( s, fd );
1469 }
1470 return res;
1471 }
1472
1473 /***********************************************************************
1474 * closesocket (WS2_32.3)
1475 */
1476 int WINAPI WS_closesocket(SOCKET s)
1477 {
1478 TRACE("socket %04lx\n", s);
1479 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
1480 return SOCKET_ERROR;
1481 }
1482
1483 /***********************************************************************
1484 * connect (WS2_32.4)
1485 */
1486 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
1487 {
1488 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1489
1490 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1491
1492 if (fd != -1)
1493 {
1494 union generic_unix_sockaddr uaddr;
1495 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1496
1497 if (!uaddrlen)
1498 {
1499 SetLastError(WSAEFAULT);
1500 }
1501 else
1502 {
1503 if (name->sa_family == WS_AF_INET)
1504 {
1505 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
1506 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
1507 {
1508 /* Trying to connect to magic replace-loopback address,
1509 * assuming we really want to connect to localhost */
1510 TRACE("Trying to connect to magic IP address, using "
1511 "INADDR_LOOPBACK instead.\n");
1512 in4->sin_addr.s_addr = htonl(WS_INADDR_LOOPBACK);
1513 }
1514 }
1515
1516 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
1517 goto connect_success;
1518 }
1519
1520 if (errno == EINPROGRESS)
1521 {
1522 /* tell wineserver that a connection is in progress */
1523 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1524 FD_CONNECT|FD_READ|FD_WRITE,
1525 FD_WINE_CONNECTED|FD_WINE_LISTENING);
1526 if (_is_blocking(s))
1527 {
1528 int result;
1529 /* block here */
1530 do_block(fd, POLLIN | POLLOUT, -1);
1531 _sync_sock_state(s); /* let wineserver notice connection */
1532 /* retrieve any error codes from it */
1533 result = _get_sock_error(s, FD_CONNECT_BIT);
1534 if (result)
1535 SetLastError(result);
1536 else
1537 {
1538 goto connect_success;
1539 }
1540 }
1541 else
1542 {
1543 SetLastError(WSAEWOULDBLOCK);
1544 }
1545 }
1546 else
1547 {
1548 SetLastError(wsaErrno());
1549 }
1550 release_sock_fd( s, fd );
1551 }
1552 return SOCKET_ERROR;
1553
1554 connect_success:
1555 release_sock_fd( s, fd );
1556 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1557 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
1558 FD_CONNECT|FD_WINE_LISTENING);
1559 return 0;
1560 }
1561
1562 /***********************************************************************
1563 * WSAConnect (WS2_32.30)
1564 */
1565 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
1566 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
1567 LPQOS lpSQOS, LPQOS lpGQOS )
1568 {
1569 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
1570 FIXME("unsupported parameters!\n");
1571 return WS_connect( s, name, namelen );
1572 }
1573
1574
1575 /***********************************************************************
1576 * getpeername (WS2_32.5)
1577 */
1578 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
1579 {
1580 int fd;
1581 int res;
1582
1583 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, *namelen);
1584
1585 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1586 if( (name == NULL) || (namelen == NULL) )
1587 {
1588 SetLastError( WSAEFAULT );
1589 return SOCKET_ERROR;
1590 }
1591
1592 fd = get_sock_fd( s, 0, NULL );
1593 res = SOCKET_ERROR;
1594
1595 if (fd != -1)
1596 {
1597 union generic_unix_sockaddr uaddr;
1598 unsigned int uaddrlen = sizeof(uaddr);
1599
1600 if (getpeername(fd, &uaddr.addr, &uaddrlen) != 0)
1601 {
1602 SetLastError(wsaErrno());
1603 }
1604 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1605 {
1606 /* The buffer was too small */
1607 SetLastError(WSAEFAULT);
1608 }
1609 else
1610 {
1611 res=0;
1612 }
1613 release_sock_fd( s, fd );
1614 }
1615 return res;
1616 }
1617
1618 /***********************************************************************
1619 * getsockname (WS2_32.6)
1620 */
1621 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
1622 {
1623 int fd;
1624 int res;
1625
1626 TRACE("socket: %04lx, ptr %p, len %8x\n", s, name, *namelen);
1627
1628 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1629 if( (name == NULL) || (namelen == NULL) )
1630 {
1631 SetLastError( WSAEFAULT );
1632 return SOCKET_ERROR;
1633 }
1634
1635 fd = get_sock_fd( s, 0, NULL );
1636 res = SOCKET_ERROR;
1637
1638 if (fd != -1)
1639 {
1640 union generic_unix_sockaddr uaddr;
1641 unsigned int uaddrlen = sizeof(uaddr);
1642
1643 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
1644 {
1645 SetLastError(wsaErrno());
1646 }
1647 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
1648 {
1649 SetLastError(WSAEINVAL);
1650 }
1651 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1652 {
1653 /* The buffer was too small */
1654 SetLastError(WSAEFAULT);
1655 }
1656 else
1657 {
1658 res=0;
1659 }
1660 release_sock_fd( s, fd );
1661 }
1662 return res;
1663 }
1664
1665 /***********************************************************************
1666 * getsockopt (WS2_32.7)
1667 */
1668 INT WINAPI WS_getsockopt(SOCKET s, INT level,
1669 INT optname, char *optval, INT *optlen)
1670 {
1671 int fd;
1672 INT ret = 0;
1673
1674 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
1675 s, level, optname, optval, *optlen);
1676
1677 switch(level)
1678 {
1679 case WS_SOL_SOCKET:
1680 {
1681 switch(optname)
1682 {
1683 /* Handle common cases. The special cases are below, sorted
1684 * alphabetically */
1685 case WS_SO_ACCEPTCONN:
1686 case WS_SO_BROADCAST:
1687 case WS_SO_DEBUG:
1688 case WS_SO_ERROR:
1689 case WS_SO_KEEPALIVE:
1690 case WS_SO_OOBINLINE:
1691 case WS_SO_RCVBUF:
1692 case WS_SO_REUSEADDR:
1693 case WS_SO_SNDBUF:
1694 case WS_SO_TYPE:
1695 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1696 return SOCKET_ERROR;
1697 convert_sockopt(&level, &optname);
1698 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1699 {
1700 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1701 ret = SOCKET_ERROR;
1702 }
1703 release_sock_fd( s, fd );
1704 return ret;
1705
1706 case WS_SO_DONTLINGER:
1707 {
1708 struct linger lingval;
1709 unsigned int len = sizeof(struct linger);
1710
1711 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
1712 {
1713 SetLastError(WSAEFAULT);
1714 return SOCKET_ERROR;
1715 }
1716 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1717 return SOCKET_ERROR;
1718
1719 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
1720 {
1721 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1722 ret = SOCKET_ERROR;
1723 }
1724 else
1725 {
1726 *(BOOL *)optval = (lingval.l_onoff) ? FALSE : TRUE;
1727 *optlen = sizeof(BOOL);
1728 }
1729
1730 release_sock_fd( s, fd );
1731 return ret;
1732 }
1733
1734 /* As mentioned in setsockopt, Windows ignores this, so we
1735 * always return true here */
1736 case WS_SO_DONTROUTE:
1737 if (!optlen || *optlen < sizeof(BOOL) || !optval)
1738 {
1739 SetLastError(WSAEFAULT);
1740 return SOCKET_ERROR;
1741 }
1742 *(BOOL *)optval = TRUE;
1743 *optlen = sizeof(BOOL);
1744 return 0;
1745
1746 case WS_SO_LINGER:
1747 {
1748 struct linger lingval;
1749 unsigned int len = sizeof(struct linger);
1750
1751 /* struct linger and LINGER have different sizes */
1752 if (!optlen || *optlen < sizeof(LINGER) || !optval)
1753 {
1754 SetLastError(WSAEFAULT);
1755 return SOCKET_ERROR;
1756 }
1757 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1758 return SOCKET_ERROR;
1759
1760 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
1761 {
1762 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1763 ret = SOCKET_ERROR;
1764 }
1765 else
1766 {
1767 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
1768 ((LINGER *)optval)->l_linger = lingval.l_linger;
1769 *optlen = sizeof(struct linger);
1770 }
1771
1772 release_sock_fd( s, fd );
1773 return ret;
1774 }
1775
1776 case WS_SO_MAX_MSG_SIZE:
1777 if (!optlen || *optlen < sizeof(int) || !optval)
1778 {
1779 SetLastError(WSAEFAULT);
1780 return SOCKET_ERROR;
1781 }
1782 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
1783 *(int *)optval = 65507;
1784 *optlen = sizeof(int);
1785 return 0;
1786
1787 /* SO_OPENTYPE does not require a valid socket handle. */
1788 case WS_SO_OPENTYPE:
1789 if (!optlen || *optlen < sizeof(int) || !optval)
1790 {
1791 SetLastError(WSAEFAULT);
1792 return SOCKET_ERROR;
1793 }
1794 *(int *)optval = get_per_thread_data()->opentype;
1795 *optlen = sizeof(int);
1796 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
1797 return 0;
1798
1799 #ifdef SO_RCVTIMEO
1800 case WS_SO_RCVTIMEO:
1801 #endif
1802 #ifdef SO_SNDTIMEO
1803 case WS_SO_SNDTIMEO:
1804 #endif
1805 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
1806 {
1807 struct timeval tv;
1808 unsigned int len = sizeof(struct timeval);
1809
1810 if (!optlen || *optlen < sizeof(int)|| !optval)
1811 {
1812 SetLastError(WSAEFAULT);
1813 return SOCKET_ERROR;
1814 }
1815 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1816 return SOCKET_ERROR;
1817
1818 convert_sockopt(&level, &optname);
1819 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
1820 {
1821 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1822 ret = SOCKET_ERROR;
1823 }
1824 else
1825 {
1826 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
1827 *optlen = sizeof(int);
1828 }
1829
1830 release_sock_fd( s, fd );
1831 return ret;
1832 }
1833 #endif
1834 default:
1835 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
1836 SetLastError(WSAENOPROTOOPT);
1837 return SOCKET_ERROR;
1838 } /* end switch(optname) */
1839 }/* end case WS_SOL_SOCKET */
1840 #ifdef HAVE_IPX
1841 case NSPROTO_IPX:
1842 {
1843 struct WS_sockaddr_ipx addr;
1844 IPX_ADDRESS_DATA *data;
1845 int namelen;
1846 switch(optname)
1847 {
1848 case IPX_PTYPE:
1849 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
1850 #ifdef SOL_IPX
1851 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (unsigned int*)optlen) == -1)
1852 {
1853 ret = SOCKET_ERROR;
1854 }
1855 #else
1856 {
1857 struct ipx val;
1858 socklen_t len=sizeof(struct ipx);
1859 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
1860 ret = SOCKET_ERROR;
1861 else
1862 *optval = (int)val.ipx_pt;
1863 }
1864 #endif
1865 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
1866 release_sock_fd( s, fd );
1867 return ret;
1868
1869 case IPX_ADDRESS:
1870 /*
1871 * On a Win2000 system with one network card there are usually
1872 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
1873 * Using this call you can then retrieve info about this all.
1874 * In case of Linux it is a bit different. Usually you have
1875 * only "one" device active and further it is not possible to
1876 * query things like the linkspeed.
1877 */
1878 FIXME("IPX_ADDRESS\n");
1879 namelen = sizeof(struct WS_sockaddr_ipx);
1880 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
1881 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
1882
1883 data = (IPX_ADDRESS_DATA*)optval;
1884 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
1885 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
1886 data->adapternum = 0;
1887 data->wan = FALSE; /* We are not on a wan for now .. */
1888 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
1889 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
1890 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
1891 * note 1MB = 1000kB in this case */
1892 return 0;
1893
1894 case IPX_MAX_ADAPTER_NUM:
1895 FIXME("IPX_MAX_ADAPTER_NUM\n");
1896 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
1897 return 0;
1898
1899 default:
1900 FIXME("IPX optname:%x\n", optname);
1901 return SOCKET_ERROR;
1902 }/* end switch(optname) */
1903 } /* end case NSPROTO_IPX */
1904 #endif
1905 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
1906 case WS_IPPROTO_TCP:
1907 switch(optname)
1908 {
1909 case WS_TCP_NODELAY:
1910 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1911 return SOCKET_ERROR;
1912 convert_sockopt(&level, &optname);
1913 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1914 {
1915 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1916 ret = SOCKET_ERROR;
1917 }
1918 release_sock_fd( s, fd );
1919 return ret;
1920 }
1921 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
1922 return SOCKET_ERROR;
1923
1924 case WS_IPPROTO_IP:
1925 switch(optname)
1926 {
1927 case WS_IP_ADD_MEMBERSHIP:
1928 case WS_IP_DROP_MEMBERSHIP:
1929 #ifdef IP_HDRINCL
1930 case WS_IP_HDRINCL:
1931 #endif
1932 case WS_IP_MULTICAST_IF:
1933 case WS_IP_MULTICAST_LOOP:
1934 case WS_IP_MULTICAST_TTL:
1935 case WS_IP_OPTIONS:
1936 case WS_IP_TOS:
1937 case WS_IP_TTL:
1938 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1939 return SOCKET_ERROR;
1940 convert_sockopt(&level, &optname);
1941 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1942 {
1943 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1944 ret = SOCKET_ERROR;
1945 }
1946 release_sock_fd( s, fd );
1947 return ret;
1948 case WS_IP_DONTFRAGMENT:
1949 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
1950 *(BOOL*)optval = FALSE;
1951 return 0;
1952 }
1953 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
1954 return SOCKET_ERROR;
1955
1956 default:
1957 FIXME("Unknown level: 0x%08x\n", level);
1958 return SOCKET_ERROR;
1959 } /* end switch(level) */
1960 }
1961
1962 /***********************************************************************
1963 * htonl (WINSOCK.8)
1964 * htonl (WS2_32.8)
1965 */
1966 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
1967 {
1968 return htonl(hostlong);
1969 }
1970
1971
1972 /***********************************************************************
1973 * htons (WINSOCK.9)
1974 * htons (WS2_32.9)
1975 */
1976 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
1977 {
1978 return htons(hostshort);
1979 }
1980
1981 /***********************************************************************
1982 * WSAHtonl (WS2_32.46)
1983 * From MSDN description of error codes, this function should also
1984 * check if WinSock has been initialized and the socket is a valid
1985 * socket. But why? This function only translates a host byte order
1986 * u_long into a network byte order u_long...
1987 */
1988 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
1989 {
1990 if (lpnetlong)
1991 {
1992 *lpnetlong = htonl(hostlong);
1993 return 0;
1994 }
1995 WSASetLastError(WSAEFAULT);
1996 return SOCKET_ERROR;
1997 }
1998
1999 /***********************************************************************
2000 * WSAHtons (WS2_32.47)
2001 * From MSDN description of error codes, this function should also
2002 * check if WinSock has been initialized and the socket is a valid
2003 * socket. But why? This function only translates a host byte order
2004 * u_short into a network byte order u_short...
2005 */
2006 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
2007 {
2008
2009 if (lpnetshort)
2010 {
2011 *lpnetshort = htons(hostshort);
2012 return 0;
2013 }
2014 WSASetLastError(WSAEFAULT);
2015 return SOCKET_ERROR;
2016 }
2017
2018
2019 /***********************************************************************
2020 * inet_addr (WINSOCK.10)
2021 * inet_addr (WS2_32.11)
2022 */
2023 WS_u_long WINAPI WS_inet_addr(const char *cp)
2024 {
2025 if (!cp) return INADDR_NONE;
2026 return inet_addr(cp);
2027 }
2028
2029
2030 /***********************************************************************
2031 * ntohl (WINSOCK.14)
2032 * ntohl (WS2_32.14)
2033 */
2034 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
2035 {
2036 return ntohl(netlong);
2037 }
2038
2039
2040 /***********************************************************************
2041 * ntohs (WINSOCK.15)
2042 * ntohs (WS2_32.15)
2043 */
2044 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
2045 {
2046 return ntohs(netshort);
2047 }
2048
2049
2050 /***********************************************************************
2051 * inet_ntoa (WS2_32.12)
2052 */
2053 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
2054 {
2055 /* use "buffer for dummies" here because some applications have a
2056 * propensity to decode addresses in ws_hostent structure without
2057 * saving them first...
2058 */
2059 static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
2060
2061 char* s = inet_ntoa(*((struct in_addr*)&in));
2062 if( s )
2063 {
2064 strcpy(dbuffer, s);
2065 return dbuffer;
2066 }
2067 SetLastError(wsaErrno());
2068 return NULL;
2069 }
2070
2071 /**********************************************************************
2072 * WSAIoctl (WS2_32.50)
2073 *
2074 */
2075 INT WINAPI WSAIoctl(SOCKET s,
2076 DWORD dwIoControlCode,
2077 LPVOID lpvInBuffer,
2078 DWORD cbInBuffer,
2079 LPVOID lpbOutBuffer,
2080 DWORD cbOutBuffer,
2081 LPDWORD lpcbBytesReturned,
2082 LPWSAOVERLAPPED lpOverlapped,
2083 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2084 {
2085 TRACE("%ld, 0x%08x, %p, %d, %p, %d, %p, %p, %p\n",
2086 s, dwIoControlCode, lpvInBuffer, cbInBuffer, lpbOutBuffer,
2087 cbOutBuffer, lpcbBytesReturned, lpOverlapped, lpCompletionRoutine);
2088
2089 switch( dwIoControlCode )
2090 {
2091 case WS_FIONBIO:
2092 if (cbInBuffer != sizeof(WS_u_long)) {
2093 WSASetLastError(WSAEFAULT);
2094 return SOCKET_ERROR;
2095 }
2096 return WS_ioctlsocket( s, WS_FIONBIO, lpvInBuffer);
2097
2098 case WS_FIONREAD:
2099 if (cbOutBuffer != sizeof(WS_u_long)) {
2100 WSASetLastError(WSAEFAULT);
2101 return SOCKET_ERROR;
2102 }
2103 return WS_ioctlsocket( s, WS_FIONREAD, lpbOutBuffer);
2104
2105 case WS_SIO_GET_INTERFACE_LIST:
2106 {
2107 INTERFACE_INFO* intArray = (INTERFACE_INFO*)lpbOutBuffer;
2108 DWORD size, numInt, apiReturn;
2109 int fd;
2110
2111 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
2112
2113 if (!lpbOutBuffer)
2114 {
2115 WSASetLastError(WSAEFAULT);
2116 return SOCKET_ERROR;
2117 }
2118 if (!lpcbBytesReturned)
2119 {
2120 WSASetLastError(WSAEFAULT);
2121 return SOCKET_ERROR;
2122 }
2123
2124 fd = get_sock_fd( s, 0, NULL );
2125 if (fd == -1) return SOCKET_ERROR;
2126
2127 apiReturn = GetAdaptersInfo(NULL, &size);
2128 if (apiReturn == ERROR_NO_DATA)
2129 {
2130 numInt = 0;
2131 }
2132 else if (apiReturn == ERROR_BUFFER_OVERFLOW)
2133 {
2134 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
2135
2136 if (table)
2137 {
2138 if (GetAdaptersInfo(table, &size) == NO_ERROR)
2139 {
2140 PIP_ADAPTER_INFO ptr;
2141
2142 if (size*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > cbOutBuffer)
2143 {
2144 WARN("Buffer too small = %u, cbOutBuffer = %u\n", size, cbOutBuffer);
2145 HeapFree(GetProcessHeap(),0,table);
2146 release_sock_fd( s, fd );
2147 WSASetLastError(WSAEFAULT);
2148 return SOCKET_ERROR;
2149 }
2150 for (ptr = table, numInt = 0; ptr;
2151 ptr = ptr->Next, intArray++, numInt++)
2152 {
2153 unsigned int addr, mask, bcast;
2154 struct ifreq ifInfo;
2155
2156 /* Socket Status Flags */
2157 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
2158 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
2159 {
2160 ERR("Error obtaining status flags for socket!\n");
2161 HeapFree(GetProcessHeap(),0,table);
2162 release_sock_fd( s, fd );
2163 WSASetLastError(WSAEINVAL);
2164 return SOCKET_ERROR;
2165 }
2166 else
2167 {
2168 /* set flags; the values of IFF_* are not the same
2169 under Linux and Windows, therefore must generate
2170 new flags */
2171 intArray->iiFlags = 0;
2172 if (ifInfo.ifr_flags & IFF_BROADCAST)
2173 intArray->iiFlags |= WS_IFF_BROADCAST;
2174 #ifdef IFF_POINTOPOINT
2175 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
2176 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
2177 #endif
2178 if (ifInfo.ifr_flags & IFF_LOOPBACK)
2179 intArray->iiFlags |= WS_IFF_LOOPBACK;
2180 if (ifInfo.ifr_flags & IFF_UP)
2181 intArray->iiFlags |= WS_IFF_UP;
2182 if (ifInfo.ifr_flags & IFF_MULTICAST)
2183 intArray->iiFlags |= WS_IFF_MULTICAST;
2184 }
2185
2186 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
2187 mask = inet_addr(ptr->IpAddressList.IpMask.String);
2188 bcast = addr | ~mask;
2189 intArray->iiAddress.AddressIn.sin_family = AF_INET;
2190 intArray->iiAddress.AddressIn.sin_port = 0;
2191 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
2192 addr;
2193 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
2194 intArray->iiNetmask.AddressIn.sin_port = 0;
2195 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
2196 mask;
2197 intArray->iiBroadcastAddress.AddressIn.sin_family =
2198 AF_INET;
2199 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
2200 intArray->iiBroadcastAddress.AddressIn.sin_addr.
2201 WS_s_addr = bcast;
2202 }
2203 }
2204 else
2205 {
2206 ERR("Unable to get interface table!\n");
2207 release_sock_fd( s, fd );
2208 HeapFree(GetProcessHeap(),0,table);
2209 WSASetLastError(WSAEINVAL);
2210 return SOCKET_ERROR;
2211 }
2212 HeapFree(GetProcessHeap(),0,table);
2213 }
2214 else
2215 {
2216 release_sock_fd( s, fd );
2217 WSASetLastError(WSAEINVAL);
2218 return SOCKET_ERROR;
2219 }
2220 }
2221 else
2222 {
2223 ERR("Unable to get interface table!\n");
2224 release_sock_fd( s, fd );
2225 WSASetLastError(WSAEINVAL);
2226 return SOCKET_ERROR;
2227 }
2228 /* Calculate the size of the array being returned */
2229 *lpcbBytesReturned = sizeof(INTERFACE_INFO) * numInt;
2230 release_sock_fd( s, fd );
2231 break;
2232 }
2233
2234 case WS_SIO_ADDRESS_LIST_CHANGE:
2235 FIXME("-> SIO_ADDRESS_LIST_CHANGE request: stub\n");
2236 /* FIXME: error and return code depend on whether socket was created
2237 * with WSA_FLAG_OVERLAPPED, but there is no easy way to get this */
2238 break;
2239
2240 case WS_SIO_ADDRESS_LIST_QUERY:
2241 {
2242 DWORD size;
2243
2244 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
2245
2246 if (!lpcbBytesReturned)
2247 {
2248 WSASetLastError(WSAEFAULT);
2249 return SOCKET_ERROR;
2250 }
2251
2252 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
2253 {
2254 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
2255 DWORD need, num;
2256
2257 if (!table || GetAdaptersInfo(table, &size))
2258 {
2259 HeapFree(GetProcessHeap(), 0, table);
2260 WSASetLastError(WSAEINVAL);
2261 return SOCKET_ERROR;
2262 }
2263
2264 for (p = table, num = 0; p; p = p->Next)
2265 if (p->IpAddressList.IpAddress.String[0]) num++;
2266
2267 need = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
2268 need += sizeof(SOCKADDR) * num;
2269 *lpcbBytesReturned = need;
2270
2271 if (need > cbOutBuffer)
2272 {
2273 HeapFree(GetProcessHeap(), 0, table);
2274 WSASetLastError(WSAEFAULT);
2275 return SOCKET_ERROR;
2276 }
2277
2278 if (lpbOutBuffer)
2279 {
2280 unsigned int i;
2281 SOCKET_ADDRESS *sa;
2282 SOCKET_ADDRESS_LIST *sa_list = (SOCKET_ADDRESS_LIST *)lpbOutBuffer;
2283 SOCKADDR_IN *sockaddr;
2284
2285 sa = sa_list->Address;
2286 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
2287 sa_list->iAddressCount = num;
2288
2289 for (p = table, i = 0; p; p = p->Next)
2290 {
2291 if (!p->IpAddressList.IpAddress.String[0]) continue;
2292
2293 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
2294 sa[i].iSockaddrLength = sizeof(SOCKADDR);
2295
2296 sockaddr[i].sin_family = AF_INET;
2297 sockaddr[i].sin_port = 0;
2298 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
2299 i++;
2300 }
2301 }
2302
2303 HeapFree(GetProcessHeap(), 0, table);
2304 return 0;
2305 }
2306 else
2307 {
2308 WARN("unable to get IP address list\n");
2309 WSASetLastError(WSAEINVAL);
2310 return SOCKET_ERROR;
2311 }
2312 }
2313 case WS_SIO_FLUSH:
2314 FIXME("SIO_FLUSH: stub.\n");
2315 break;
2316
2317 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
2318 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(lpvInBuffer));
2319 WSASetLastError(WSAEOPNOTSUPP);
2320 return SOCKET_ERROR;
2321
2322 case WS_SIO_KEEPALIVE_VALS:
2323 {
2324 int fd;
2325 struct tcp_keepalive *k = lpvInBuffer;
2326 int keepalive = k->onoff ? 1 : 0;
2327 int keepidle = k->keepalivetime / 1000;
2328 int keepintvl = k->keepaliveinterval / 1000;
2329
2330 if (!lpvInBuffer)
2331 {
2332 WSASetLastError(WSAEINVAL);
2333 return SOCKET_ERROR;
2334 }
2335
2336 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
2337
2338 fd = get_sock_fd(s, 0, NULL);
2339 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
2340 {
2341 release_sock_fd(s, fd);
2342 WSASetLastError(WSAEINVAL);
2343 return SOCKET_ERROR;
2344 }
2345 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
2346 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
2347 {
2348 release_sock_fd(s, fd);
2349 WSASetLastError(WSAEINVAL);
2350 return SOCKET_ERROR;
2351 }
2352 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
2353 {
2354 release_sock_fd(s, fd);
2355 WSASetLastError(WSAEINVAL);
2356 return SOCKET_ERROR;
2357 }
2358 #else
2359 FIXME("ignoring keepalive interval and timeout\n");
2360 #endif
2361
2362 release_sock_fd(s, fd);
2363 break;
2364 }
2365 default:
2366 FIXME("unsupported WS_IOCTL cmd (%08x)\n", dwIoControlCode);
2367 WSASetLastError(WSAEOPNOTSUPP);
2368 return SOCKET_ERROR;
2369 }
2370
2371 return 0;
2372 }
2373
2374
2375 /***********************************************************************
2376 * ioctlsocket (WS2_32.10)
2377 */
2378 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
2379 {
2380 int fd;
2381 long newcmd = cmd;
2382
2383 TRACE("socket %04lx, cmd %08x, ptr %p\n", s, cmd, argp);
2384 /* broken apps like defcon pass the argp value directly instead of a pointer to it */
2385 if(IS_INTRESOURCE(argp))
2386 {
2387 SetLastError(WSAEFAULT);
2388 return SOCKET_ERROR;
2389 }
2390
2391 switch( cmd )
2392 {
2393 case WS_FIONREAD:
2394 newcmd=FIONREAD;
2395 break;
2396
2397 case WS_FIONBIO:
2398 if( _get_sock_mask(s) )
2399 {
2400 /* AsyncSelect()'ed sockets are always nonblocking */
2401 if (*argp) return 0;
2402 SetLastError(WSAEINVAL);
2403 return SOCKET_ERROR;
2404 }
2405 fd = get_sock_fd( s, 0, NULL );
2406 if (fd != -1)
2407 {
2408 int ret;
2409 if (*argp)
2410 {
2411 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
2412 ret = fcntl( fd, F_SETFL, O_NONBLOCK );
2413 }
2414 else
2415 {
2416 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
2417 ret = fcntl( fd, F_SETFL, 0 );
2418 }
2419 release_sock_fd( s, fd );
2420 if (!ret) return 0;
2421 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2422 }
2423 return SOCKET_ERROR;
2424
2425 case WS_SIOCATMARK:
2426 newcmd=SIOCATMARK;
2427 break;
2428
2429 case WS_FIOASYNC:
2430 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
2431 SetLastError(WSAEINVAL);
2432 return SOCKET_ERROR;
2433
2434 case SIOCGIFBRDADDR:
2435 case SIOCGIFNETMASK:
2436 case SIOCGIFADDR:
2437 /* These don't need any special handling. They are used by
2438 WsControl, and are here to suppress an unnecessary warning. */
2439 break;
2440
2441 default:
2442 /* Netscape tries hard to use bogus ioctl 0x667e */
2443 /* FIXME: 0x667e above is ('f' << 8) | 126, and is a low word of
2444 * FIONBIO (_IOW('f', 126, u_long)), how that should be handled?
2445 */
2446 WARN("\tunknown WS_IOCTL cmd (%08x)\n", cmd);
2447 break;
2448 }
2449
2450 fd = get_sock_fd( s, 0, NULL );
2451 if (fd != -1)
2452 {
2453 if( ioctl(fd, newcmd, (char*)argp ) == 0 )
2454 {
2455 release_sock_fd( s, fd );
2456 return 0;
2457 }
2458 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2459 release_sock_fd( s, fd );
2460 }
2461 return SOCKET_ERROR;
2462 }
2463
2464 /***********************************************************************
2465 * listen (WS2_32.13)
2466 */
2467 int WINAPI WS_listen(SOCKET s, int backlog)
2468 {
2469 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2470
2471 TRACE("socket %04lx, backlog %d\n", s, backlog);
2472 if (fd != -1)
2473 {
2474 if (listen(fd, backlog) == 0)
2475 {
2476 release_sock_fd( s, fd );
2477 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
2478 FD_WINE_LISTENING,
2479 FD_CONNECT|FD_WINE_CONNECTED);
2480 return 0;
2481 }
2482 SetLastError(wsaErrno());
2483 release_sock_fd( s, fd );
2484 }
2485 return SOCKET_ERROR;
2486 }
2487
2488 /***********************************************************************
2489 * recv (WS2_32.16)
2490 */
2491 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
2492 {
2493 DWORD n, dwFlags = flags;
2494 WSABUF wsabuf;
2495
2496 wsabuf.len = len;
2497 wsabuf.buf = buf;
2498
2499 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
2500 return SOCKET_ERROR;
2501 else
2502 return n;
2503 }
2504
2505 /***********************************************************************
2506 * recvfrom (WS2_32.17)
2507 */
2508 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
2509 struct WS_sockaddr *from, int *fromlen)
2510 {
2511 DWORD n, dwFlags = flags;
2512 WSABUF wsabuf;
2513
2514 wsabuf.len = len;
2515 wsabuf.buf = buf;
2516
2517 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL) == SOCKET_ERROR )
2518 return SOCKET_ERROR;
2519 else
2520 return n;
2521 }
2522
2523 /* allocate a poll array for the corresponding fd sets */
2524 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
2525 const WS_fd_set *exceptfds, int *count_ptr )
2526 {
2527 unsigned int i, j = 0, count = 0;
2528 struct pollfd *fds;
2529
2530 if (readfds) count += readfds->fd_count;
2531 if (writefds) count += writefds->fd_count;
2532 if (exceptfds) count += exceptfds->fd_count;
2533 *count_ptr = count;
2534 if (!count) return NULL;
2535 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0])))) return NULL;
2536 if (readfds)
2537 for (i = 0; i < readfds->fd_count; i++, j++)
2538 {
2539 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
2540 fds[j].events = POLLIN;
2541 fds[j].revents = 0;
2542 }
2543 if (writefds)
2544 for (i = 0; i < writefds->fd_count; i++, j++)
2545 {
2546 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
2547 fds[j].events = POLLOUT;
2548 fds[j].revents = 0;
2549 }
2550 if (exceptfds)
2551 for (i = 0; i < exceptfds->fd_count; i++, j++)
2552 {
2553 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
2554 fds[j].events = POLLHUP;
2555 fds[j].revents = 0;
2556 }
2557 return fds;
2558 }
2559
2560 /* release the file descriptor obtained in fd_sets_to_poll */
2561 /* must be called with the original fd_set arrays, before calling get_poll_results */
2562 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
2563 const WS_fd_set *exceptfds, struct pollfd *fds )
2564 {
2565 unsigned int i, j = 0;
2566
2567 if (readfds)
2568 {
2569 for (i = 0; i < readfds->fd_count; i++, j++)
2570 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
2571 }
2572 if (writefds)
2573 {
2574 for (i = 0; i < writefds->fd_count; i++, j++)
2575 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
2576 }
2577 if (exceptfds)
2578 {
2579 for (i = 0; i < exceptfds->fd_count; i++, j++)
2580 if (fds[j].fd != -1)
2581 {
2582 /* make sure we have a real error before releasing the fd */
2583 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
2584 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
2585 }
2586 }
2587 }
2588
2589 /* map the poll results back into the Windows fd sets */
2590 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
2591 const struct pollfd *fds )
2592 {
2593 unsigned int i, j = 0, k, total = 0;
2594
2595 if (readfds)
2596 {
2597 for (i = k = 0; i < readfds->fd_count; i++, j++)
2598 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
2599 readfds->fd_count = k;
2600 total += k;
2601 }
2602 if (writefds)
2603 {
2604 for (i = k = 0; i < writefds->fd_count; i++, j++)
2605 if (fds[j].revents) writefds->fd_array[k++] = writefds->fd_array[i];
2606 writefds->fd_count = k;
2607 total += k;
2608 }
2609 if (exceptfds)
2610 {
2611 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
2612 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
2613 exceptfds->fd_count = k;
2614 total += k;
2615 }
2616 return total;
2617 }
2618
2619
2620 /***********************************************************************
2621 * select (WS2_32.18)
2622 */
2623 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
2624 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
2625 const struct WS_timeval* ws_timeout)
2626 {
2627 struct pollfd *pollfds;
2628 int count, ret, timeout = -1;
2629
2630 TRACE("read %p, write %p, excp %p timeout %p\n",
2631 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
2632
2633 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )) && count)
2634 {
2635 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2636 return SOCKET_ERROR;
2637 }
2638
2639 if (ws_timeout) timeout = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
2640
2641 ret = poll( pollfds, count, timeout );
2642 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2643
2644 if (ret == -1) SetLastError(wsaErrno());
2645 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2646 HeapFree( GetProcessHeap(), 0, pollfds );
2647 return ret;
2648 }
2649
2650 /* helper to send completion messages for client-only i/o operation case */
2651 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
2652 ULONG Information )
2653 {
2654 NTSTATUS status;
2655
2656 SERVER_START_REQ( add_fd_completion )
2657 {
2658 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
2659 req->cvalue = CompletionValue;
2660 req->status = CompletionStatus;
2661 req->information = Information;
2662 status = wine_server_call( req );
2663 }
2664 SERVER_END_REQ;
2665 }
2666
2667
2668 /***********************************************************************
2669 * send (WS2_32.19)
2670 */
2671 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
2672 {
2673 DWORD n;
2674 WSABUF wsabuf;
2675
2676 wsabuf.len = len;
2677 wsabuf.buf = (char*) buf;
2678
2679 if ( WSASendTo( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
2680 return SOCKET_ERROR;
2681 else
2682 return n;
2683 }
2684
2685 /***********************************************************************
2686 * WSASend (WS2_32.72)
2687 */
2688 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2689 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2690 LPWSAOVERLAPPED lpOverlapped,
2691 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2692 {
2693 return WSASendTo( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
2694 NULL, 0, lpOverlapped, lpCompletionRoutine );
2695 }
2696
2697 /***********************************************************************
2698 * WSASendDisconnect (WS2_32.73)
2699 */
2700 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
2701 {
2702 return WS_shutdown( s, SD_SEND );
2703 }
2704
2705
2706 /***********************************************************************
2707 * WSASendTo (WS2_32.74)
2708 */
2709 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2710 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2711 const struct WS_sockaddr *to, int tolen,
2712 LPWSAOVERLAPPED lpOverlapped,
2713 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2714 {
2715 unsigned int i, options;
2716 int n, fd, err;
2717 struct ws2_async *wsa;
2718 int totalLength = 0;
2719 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
2720
2721 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
2722 s, lpBuffers, dwBufferCount, dwFlags,
2723 to, tolen, lpOverlapped, lpCompletionRoutine);
2724
2725 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
2726 TRACE( "fd=%d, options=%x\n", fd, options );
2727
2728 if ( fd == -1 ) return SOCKET_ERROR;
2729
2730 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
2731 {
2732 err = WSAEFAULT;
2733 goto error;
2734 }
2735
2736 wsa->hSocket = SOCKET2HANDLE(s);
2737 wsa->addr = (struct WS_sockaddr *)to;
2738 wsa->addrlen.val = tolen;
2739 wsa->flags = dwFlags;
2740 wsa->n_iovecs = dwBufferCount;
2741 wsa->first_iovec = 0;
2742 for ( i = 0; i < dwBufferCount; i++ )
2743 {
2744 wsa->iovec[i].iov_base = lpBuffers[i].buf;
2745 wsa->iovec[i].iov_len = lpBuffers[i].len;
2746 totalLength += lpBuffers[i].len;
2747 }
2748
2749 if (!lpNumberOfBytesSent)
2750 {
2751 err = WSAEFAULT;
2752 goto error;
2753 }
2754
2755 for (;;)
2756 {
2757 n = WS2_send( fd, wsa );
2758 if (n != -1 || errno != EINTR) break;
2759 }
2760 if (n == -1 && errno != EAGAIN)
2761 {
2762 err = wsaErrno();
2763 if (cvalue) WS_AddCompletion( s, cvalue, err, 0 );
2764 goto error;
2765 }
2766
2767 if ((lpOverlapped || lpCompletionRoutine) &&
2768 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
2769 {
2770 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
2771
2772 wsa->user_overlapped = lpOverlapped;
2773 wsa->completion_func = lpCompletionRoutine;
2774 release_sock_fd( s, fd );
2775
2776 if (n == -1)
2777 {
2778 iosb->u.Status = STATUS_PENDING;
2779 iosb->Information = 0;
2780
2781 SERVER_START_REQ( register_async )
2782 {
2783 req->handle = wine_server_obj_handle( wsa->hSocket );
2784 req->type = ASYNC_TYPE_WRITE;
2785 req->async.callback = WS2_async_send;
2786 req->async.iosb = iosb;
2787 req->async.arg = wsa;
2788 req->async.apc = ws2_async_apc;
2789 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
2790 req->async.cvalue = cvalue;
2791 err = wine_server_call( req );
2792 }
2793 SERVER_END_REQ;
2794
2795 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
2796 WSASetLastError( NtStatusToWSAError( err ));
2797 return SOCKET_ERROR;
2798 }
2799
2800 iosb->u.Status = STATUS_SUCCESS;
2801 iosb->Information = n;
2802 *lpNumberOfBytesSent = n;
2803 if (!wsa->completion_func)
2804 {
2805 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
2806 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
2807 HeapFree( GetProcessHeap(), 0, wsa );
2808 }
2809 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
2810 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
2811 WSASetLastError(0);
2812 return 0;
2813 }
2814
2815 if ( _is_blocking(s) )
2816 {
2817 /* On a blocking non-overlapped stream socket,
2818 * sending blocks until the entire buffer is sent. */
2819 DWORD timeout_start = GetTickCount();
2820
2821 *lpNumberOfBytesSent = 0;
2822
2823 while (wsa->first_iovec < dwBufferCount)
2824 {
2825 struct pollfd pfd;
2826 int timeout = GET_SNDTIMEO(fd);
2827
2828 if (n >= 0)
2829 {
2830 *lpNumberOfBytesSent += n;
2831 while (wsa->first_iovec < dwBufferCount && wsa->iovec[wsa->first_iovec].iov_len <= n)
2832 n -= wsa->iovec[wsa->first_iovec++].iov_len;
2833 if (wsa->first_iovec >= dwBufferCount) break;
2834 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
2835 wsa->iovec[wsa->first_iovec].iov_len -= n;
2836 }
2837
2838 if (timeout != -1)
2839 {
2840 timeout -= GetTickCount() - timeout_start;
2841 if (timeout < 0) timeout = 0;
2842 }
2843
2844 pfd.fd = fd;
2845 pfd.events = POLLOUT;
2846
2847 if (!timeout || !poll( &pfd, 1, timeout ))
2848 {
2849 err = WSAETIMEDOUT;
2850 goto error; /* msdn says a timeout in send is fatal */
2851 }
2852
2853 n = WS2_send( fd, wsa );
2854 if (n == -1 && errno != EAGAIN && errno != EINTR)
2855 {
2856 err = wsaErrno();
2857 goto error;
2858 }
2859 }
2860 }
2861 else /* non-blocking */
2862 {
2863 if (n < totalLength)
2864 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
2865 if (n == -1)
2866 {
2867 err = WSAEWOULDBLOCK;
2868 goto error;
2869 }
2870 *lpNumberOfBytesSent = n;
2871 }
2872
2873 TRACE(" -> %i bytes\n", *lpNumberOfBytesSent);
2874
2875 HeapFree( GetProcessHeap(), 0, wsa );
2876 release_sock_fd( s, fd );
2877 WSASetLastError(0);
2878 return 0;
2879
2880 error:
2881 HeapFree( GetProcessHeap(), 0, wsa );
2882 release_sock_fd( s, fd );
2883 WARN(" -> ERROR %d\n", err);
2884 WSASetLastError(err);
2885 return SOCKET_ERROR;
2886 }
2887
2888 /***********************************************************************
2889 * sendto (WS2_32.20)
2890 */
2891 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
2892 const struct WS_sockaddr *to, int tolen)
2893 {
2894 DWORD n;
2895 WSABUF wsabuf;
2896
2897 wsabuf.len = len;
2898 wsabuf.buf = (char*) buf;
2899
2900 if ( WSASendTo(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
2901 return SOCKET_ERROR;
2902 else
2903 return n;
2904 }
2905
2906 /***********************************************************************
2907 * setsockopt (WS2_32.21)
2908 */
2909 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
2910 const char *optval, int optlen)
2911 {
2912 int fd;
2913 int woptval;
2914 struct linger linger;
2915 struct timeval tval;
2916
2917 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
2918 s, level, optname, optval, optlen);
2919
2920 /* some broken apps pass the value directly instead of a pointer to it */
2921 if(IS_INTRESOURCE(optval))
2922 {
2923 SetLastError(WSAEFAULT);
2924 return SOCKET_ERROR;
2925 }
2926
2927 switch(level)
2928 {
2929 case WS_SOL_SOCKET:
2930 switch(optname)
2931 {
2932 /* Some options need some conversion before they can be sent to
2933 * setsockopt. The conversions are done here, then they will fall though
2934 * to the general case. Special options that are not passed to
2935 * setsockopt follow below that.*/
2936
2937 case WS_SO_DONTLINGER:
2938 linger.l_onoff = *((const int*)optval) ? 0: 1;
2939 linger.l_linger = 0;
2940 level = SOL_SOCKET;
2941 optname = SO_LINGER;
2942 optval = (char*)&linger;
2943 optlen = sizeof(struct linger);
2944 break;
2945
2946 case WS_SO_LINGER:
2947 linger.l_onoff = ((LINGER*)optval)->l_onoff;
2948 linger.l_linger = ((LINGER*)optval)->l_linger;
2949 /* FIXME: what is documented behavior if SO_LINGER optval
2950 is null?? */
2951 level = SOL_SOCKET;
2952 optname = SO_LINGER;
2953 optval = (char*)&linger;
2954 optlen = sizeof(struct linger);
2955 break;
2956
2957 case WS_SO_RCVBUF:
2958 if (*(const int*)optval < 2048)
2959 {
2960 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
2961 return 0;
2962 }
2963 /* Fall through */
2964
2965 /* The options listed here don't need any special handling. Thanks to
2966 * the conversion happening above, options from there will fall through
2967 * to this, too.*/
2968 case WS_SO_ACCEPTCONN:
2969 case WS_SO_BROADCAST:
2970 case WS_SO_ERROR:
2971 case WS_SO_KEEPALIVE:
2972 case WS_SO_OOBINLINE:
2973 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
2974 * however, using it the BSD way fixes bug 8513 and seems to be what
2975 * most programmers assume, anyway */
2976 case WS_SO_REUSEADDR:
2977 case WS_SO_SNDBUF:
2978 case WS_SO_TYPE:
2979 convert_sockopt(&level, &optname);
2980 break;
2981
2982 /* SO_DEBUG is a privileged operation, ignore it. */
2983 case WS_SO_DEBUG:
2984 TRACE("Ignoring SO_DEBUG\n");
2985 return 0;
2986
2987 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
2988 * socket. According to MSDN, this option is silently ignored.*/
2989 case WS_SO_DONTROUTE:
2990 TRACE("Ignoring SO_DONTROUTE\n");
2991 return 0;
2992
2993 /* Stops two sockets from being bound to the same port. Always happens
2994 * on unix systems, so just drop it. */
2995 case WS_SO_EXCLUSIVEADDRUSE:
2996 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
2997 return 0;
2998
2999 /* SO_OPENTYPE does not require a valid socket handle. */
3000 case WS_SO_OPENTYPE:
3001 if (!optlen || optlen < sizeof(int) || !optval)
3002 {
3003 SetLastError(WSAEFAULT);
3004 return SOCKET_ERROR;
3005 }
3006 get_per_thread_data()->opentype = *(const int *)optval;
3007 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
3008 return 0;
3009
3010 #ifdef SO_RCVTIMEO
3011 case WS_SO_RCVTIMEO:
3012 #endif
3013 #ifdef SO_SNDTIMEO
3014 case WS_SO_SNDTIMEO:
3015 #endif
3016 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
3017 if (optval && optlen == sizeof(UINT32)) {
3018 /* WinSock passes milliseconds instead of struct timeval */
3019 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
3020 tval.tv_sec = *(const UINT32*)optval / 1000;
3021 /* min of 500 milliseconds */
3022 if (tval.tv_sec == 0 && tval.tv_usec < 500000)
3023 tval.tv_usec = 500000;
3024 optlen = sizeof(struct timeval);
3025 optval = (char*)&tval;
3026 } else if (optlen == sizeof(struct timeval)) {
3027 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
3028 } else {
3029 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
3030 return 0;
3031 }
3032 convert_sockopt(&level, &optname);
3033 break;
3034 #endif
3035
3036 default:
3037 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
3038 SetLastError(WSAENOPROTOOPT);
3039 return SOCKET_ERROR;
3040 }
3041 break; /* case WS_SOL_SOCKET */
3042
3043 #ifdef HAVE_IPX
3044 case NSPROTO_IPX:
3045 switch(optname)
3046 {
3047 case IPX_PTYPE:
3048 fd = get_sock_fd( s, 0, NULL );
3049 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", *(const int*)optval, fd);
3050
3051 /* We try to set the ipx type on ipx socket level. */
3052 #ifdef SOL_IPX
3053 if(setsockopt(fd, SOL_IPX, IPX_TYPE, optval, optlen) == -1)
3054 {
3055 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
3056 release_sock_fd( s, fd );
3057 return SOCKET_ERROR;
3058 }
3059 #else
3060 {
3061 struct ipx val;
3062 /* Should we retrieve val using a getsockopt call and then
3063 * set the modified one? */
3064 val.ipx_pt = *optval;
3065 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
3066 }
3067 #endif
3068 release_sock_fd( s, fd );
3069 return 0;
3070
3071 case IPX_FILTERPTYPE:
3072 /* Sets the receive filter packet type, at the moment we don't support it */
3073 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
3074 /* Returning 0 is better for now than returning a SOCKET_ERROR */
3075 return 0;
3076
3077 default:
3078 FIXME("opt_name:%x\n", optname);
3079 return SOCKET_ERROR;
3080 }
3081 break; /* case NSPROTO_IPX */
3082 #endif
3083
3084 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3085 case WS_IPPROTO_TCP:
3086 switch(optname)
3087 {
3088 case WS_TCP_NODELAY:
3089 convert_sockopt(&level, &optname);
3090 break;
3091 default:
3092 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3093 return SOCKET_ERROR;
3094 }
3095 break;
3096
3097 case WS_IPPROTO_IP:
3098 switch(optname)
3099 {
3100 case WS_IP_ADD_MEMBERSHIP:
3101 case WS_IP_DROP_MEMBERSHIP:
3102 #ifdef IP_HDRINCL
3103 case WS_IP_HDRINCL:
3104 #endif
3105 case WS_IP_MULTICAST_IF:
3106 case WS_IP_MULTICAST_LOOP:
3107 case WS_IP_MULTICAST_TTL:
3108 case WS_IP_OPTIONS:
3109 case WS_IP_TOS:
3110 case WS_IP_TTL:
3111 convert_sockopt(&level, &optname);
3112 break;
3113 case WS_IP_DONTFRAGMENT:
3114 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
3115 return 0;
3116 default:
3117 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3118 return SOCKET_ERROR;
3119 }
3120 break;
3121
3122 default:
3123 FIXME("Unknown level: 0x%08x\n", level);
3124 return SOCKET_ERROR;
3125 } /* end switch(level) */
3126
3127 /* avoid endianness issues if argument is a 16-bit int */
3128 if (optval && optlen < sizeof(int))
3129 {
3130 woptval= *((const INT16 *) optval);
3131 optval= (char*) &woptval;
3132 optlen=sizeof(int);
3133 }
3134 fd = get_sock_fd( s, 0, NULL );
3135 if (fd == -1) return SOCKET_ERROR;
3136
3137 if (setsockopt(fd, level, optname, optval, optlen) == 0)
3138 {
3139 release_sock_fd( s, fd );
3140 return 0;
3141 }
3142 TRACE("Setting socket error, %d\n", wsaErrno());
3143 SetLastError(wsaErrno());
3144 release_sock_fd( s, fd );
3145
3146 return SOCKET_ERROR;
3147 }
3148
3149 /***********************************************************************
3150 * shutdown (WS2_32.22)
3151 */
3152 int WINAPI WS_shutdown(SOCKET s, int how)
3153 {
3154 int fd, err = WSAENOTSOCK;
3155 unsigned int options, clear_flags = 0;
3156
3157 fd = get_sock_fd( s, 0, &options );
3158 TRACE("socket %04lx, how %i %x\n", s, how, options );
3159
3160 if (fd == -1)
3161 return SOCKET_ERROR;
3162
3163 switch( how )
3164 {
3165 case 0: /* drop receives */
3166 clear_flags |= FD_READ;
3167 break;
3168 case 1: /* drop sends */
3169 clear_flags |= FD_WRITE;
3170 break;
3171 case 2: /* drop all */
3172 clear_flags |= FD_READ|FD_WRITE;
3173 default:
3174 clear_flags |= FD_WINE_LISTENING;
3175 }
3176
3177 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
3178 {
3179 switch ( how )
3180 {
3181 case SD_RECEIVE:
3182 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3183 break;
3184 case SD_SEND:
3185 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3186 break;
3187 case SD_BOTH:
3188 default:
3189 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3190 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3191 break;
3192 }
3193 if (err) goto error;
3194 }
3195 else /* non-overlapped mode */
3196 {
3197 if ( shutdown( fd, how ) )
3198 {
3199 err = wsaErrno();
3200 goto error;
3201 }
3202 }
3203
3204 release_sock_fd( s, fd );
3205 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3206 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
3207 return 0;
3208
3209 error:
3210 release_sock_fd( s, fd );
3211 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3212 WSASetLastError( err );
3213 return SOCKET_ERROR;
3214 }
3215
3216 /***********************************************************************
3217 * socket (WS2_32.23)
3218 */
3219 SOCKET WINAPI WS_socket(int af, int type, int protocol)
3220 {
3221 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
3222
3223 return WSASocketA( af, type, protocol, NULL, 0,
3224 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
3225 }
3226
3227
3228 /***********************************************************************
3229 * gethostbyaddr (WS2_32.51)
3230 */
3231 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
3232 {
3233 struct WS_hostent *retval = NULL;
3234 struct hostent* host;
3235
3236 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3237 char *extrabuf;
3238 int ebufsize=1024;
3239 struct hostent hostentry;
3240 int locerr=ENOBUFS;
3241 host = NULL;
3242 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3243 while(extrabuf) {
3244 int res = gethostbyaddr_r(addr, len, type,
3245 &hostentry, extrabuf, ebufsize, &host, &locerr);
3246 if( res != ERANGE) break;
3247 ebufsize *=2;
3248 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3249 }
3250 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3251 #else
3252 EnterCriticalSection( &csWSgetXXXbyYYY );
3253 host = gethostbyaddr(addr, len, type);
3254 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3255 #endif
3256 if( host != NULL ) retval = WS_dup_he(host);
3257 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3258 HeapFree(GetProcessHeap(),0,extrabuf);
3259 #else
3260 LeaveCriticalSection( &csWSgetXXXbyYYY );
3261 #endif
3262 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
3263 return retval;
3264 }
3265
3266 /***********************************************************************
3267 * gethostbyname (WS2_32.52)
3268 */
3269 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
3270 {
3271 struct WS_hostent *retval = NULL;
3272 struct hostent* host;
3273 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3274 char *extrabuf;
3275 int ebufsize=1024;
3276 struct hostent hostentry;
3277 int locerr = ENOBUFS;
3278 #endif
3279 char buf[100];
3280 if( !name || !name[0]) {
3281 name = buf;
3282 if( gethostname( buf, 100) == -1) {
3283 SetLastError( WSAENOBUFS); /* appropriate ? */
3284 return retval;
3285 }
3286 }
3287 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3288 host = NULL;
3289 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3290 while(extrabuf) {
3291 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
3292 if( res != ERANGE) break;
3293 ebufsize *=2;
3294 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3295 }
3296 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3297 #else
3298 EnterCriticalSection( &csWSgetXXXbyYYY );
3299 host = gethostbyname(name);
3300 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3301 #endif
3302 if (host) retval = WS_dup_he(host);
3303 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3304 HeapFree(GetProcessHeap(),0,extrabuf);
3305 #else
3306 LeaveCriticalSection( &csWSgetXXXbyYYY );
3307 #endif
3308 if (retval && retval->h_addr_list[0][0] == 127 &&
3309 strcmp(name, "localhost") != 0)
3310 {
3311 /* hostname != "localhost" but has loopback address. replace by our
3312 * special address.*/
3313 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
3314 }
3315 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3316 return retval;
3317 }
3318
3319
3320 /***********************************************************************
3321 * getprotobyname (WS2_32.53)
3322 */
3323 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
3324 {
3325 struct WS_protoent* retval = NULL;
3326 #ifdef HAVE_GETPROTOBYNAME
3327 struct protoent* proto;
3328 EnterCriticalSection( &csWSgetXXXbyYYY );
3329 if( (proto = getprotobyname(name)) != NULL )
3330 {
3331 retval = WS_dup_pe(proto);
3332 }
3333 else {
3334 MESSAGE("protocol %s not found; You might want to add "
3335 "this to /etc/protocols\n", debugstr_a(name) );
3336 SetLastError(WSANO_DATA);
3337 }
3338 LeaveCriticalSection( &csWSgetXXXbyYYY );
3339 #endif
3340 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3341 return retval;
3342 }
3343
3344
3345 /***********************************************************************
3346 * getprotobynumber (WS2_32.54)
3347 */
3348 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
3349 {
3350 struct WS_protoent* retval = NULL;
3351 #ifdef HAVE_GETPROTOBYNUMBER
3352 struct protoent* proto;
3353 EnterCriticalSection( &csWSgetXXXbyYYY );
3354 if( (proto = getprotobynumber(number)) != NULL )
3355 {
3356 retval = WS_dup_pe(proto);
3357 }
3358 else {
3359 MESSAGE("protocol number %d not found; You might want to add "
3360 "this to /etc/protocols\n", number );
3361 SetLastError(WSANO_DATA);
3362 }
3363 LeaveCriticalSection( &csWSgetXXXbyYYY );
3364 #endif
3365 TRACE("%i ret %p\n", number, retval);
3366 return retval;
3367 }
3368
3369
3370 /***********************************************************************
3371 * getservbyname (WS2_32.55)
3372 */
3373 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
3374 {
3375 struct WS_servent* retval = NULL;
3376 struct servent* serv;
3377 char *name_str;
3378 char *proto_str = NULL;
3379
3380 if (!(name_str = strdup_lower(name))) return NULL;
3381
3382 if (proto && *proto)
3383 {
3384 if (!(proto_str = strdup_lower(proto)))
3385 {
3386 HeapFree( GetProcessHeap(), 0, name_str );
3387 return NULL;
3388 }
3389 }
3390
3391 EnterCriticalSection( &csWSgetXXXbyYYY );
3392 serv = getservbyname(name_str, proto_str);
3393 if( serv != NULL )
3394 {
3395 retval = WS_dup_se(serv);
3396 }
3397 else SetLastError(WSANO_DATA);
3398 LeaveCriticalSection( &csWSgetXXXbyYYY );
3399 HeapFree( GetProcessHeap(), 0, proto_str );
3400 HeapFree( GetProcessHeap(), 0, name_str );
3401 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
3402 return retval;
3403 }
3404
3405 /***********************************************************************
3406 * freeaddrinfo (WS2_32.@)
3407 */
3408 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
3409 {
3410 while (res) {
3411 struct WS_addrinfo *next;
3412
3413 HeapFree(GetProcessHeap(),0,res->ai_canonname);
3414 HeapFree(GetProcessHeap(),0,res->ai_addr);
3415 next = res->ai_next;
3416 HeapFree(GetProcessHeap(),0,res);
3417 res = next;
3418 }
3419 }
3420
3421 /* helper functions for getaddrinfo()/getnameinfo() */
3422 static int convert_aiflag_w2u(int winflags) {
3423 unsigned int i;
3424 int unixflags = 0;
3425
3426 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3427 if (ws_aiflag_map[i][0] & winflags) {
3428 unixflags |= ws_aiflag_map[i][1];
3429 winflags &= ~ws_aiflag_map[i][0];
3430 }
3431 if (winflags)
3432 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
3433 return unixflags;
3434 }
3435
3436 static int convert_niflag_w2u(int winflags) {
3437 unsigned int i;
3438 int unixflags = 0;
3439
3440 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
3441 if (ws_niflag_map[i][0] & winflags) {
3442 unixflags |= ws_niflag_map[i][1];
3443 winflags &= ~ws_niflag_map[i][0];
3444 }
3445 if (winflags)
3446 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
3447 return unixflags;
3448 }
3449
3450 static int convert_aiflag_u2w(int unixflags) {
3451 unsigned int i;
3452 int winflags = 0;
3453
3454 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3455 if (ws_aiflag_map[i][1] & unixflags) {
3456 winflags |= ws_aiflag_map[i][0];
3457 unixflags &= ~ws_aiflag_map[i][1];
3458 }
3459 if (unixflags) /* will warn usually */
3460 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
3461 return winflags;
3462 }
3463
3464 static int convert_eai_u2w(int unixret) {
3465 int i;
3466
3467 for (i=0;ws_eai_map[i][0];i++)
3468 if (ws_eai_map[i][1] == unixret)
3469 return ws_eai_map[i][0];
3470 return unixret;
3471 }
3472
3473 /***********************************************************************
3474 * getaddrinfo (WS2_32.@)
3475 */
3476 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
3477 {
3478 #ifdef HAVE_GETADDRINFO
3479 struct addrinfo *unixaires = NULL;
3480 int result;
3481 struct addrinfo unixhints, *punixhints = NULL;
3482 CHAR *node = NULL, *serv = NULL;
3483
3484 if (nodename)
3485 if (!(node = strdup_lower(nodename))) return WSA_NOT_ENOUGH_MEMORY;
3486
3487 if (servname) {
3488 if (!(serv = strdup_lower(servname))) {
3489 HeapFree(GetProcessHeap(), 0, node);
3490 return WSA_NOT_ENOUGH_MEMORY;
3491 }
3492 }
3493
3494 if (hints) {
3495 punixhints = &unixhints;
3496
3497 memset(&unixhints, 0, sizeof(unixhints));
3498 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
3499 if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
3500 punixhints->ai_family = 0;
3501 else
3502 punixhints->ai_family = convert_af_w2u(hints->ai_family);
3503 if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
3504 punixhints->ai_socktype = 0;
3505 else
3506 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
3507 if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
3508 punixhints->ai_protocol = 0;
3509 else
3510 punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
3511 }
3512
3513 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
3514 result = getaddrinfo(nodename, servname, punixhints, &unixaires);
3515
3516 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
3517
3518 HeapFree(GetProcessHeap(), 0, node);
3519 HeapFree(GetProcessHeap(), 0, serv);
3520
3521 if (!result) {
3522 struct addrinfo *xuai = unixaires;
3523 struct WS_addrinfo **xai = res;
3524
3525 *xai = NULL;
3526 while (xuai) {
3527 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
3528 int len;
3529
3530 if (!ai)
3531 goto outofmem;
3532
3533 *xai = ai;xai = &ai->ai_next;
3534 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
3535 ai->ai_family = convert_af_u2w(xuai->ai_family);
3536 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
3537 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
3538 if (xuai->ai_canonname) {
3539 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
3540 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
3541 if (!ai->ai_canonname)
3542 goto outofmem;
3543 strcpy(ai->ai_canonname,xuai->ai_canonname);
3544 }
3545 len = xuai->ai_addrlen;
3546 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
3547 if (!ai->ai_addr)
3548 goto outofmem;
3549 ai->ai_addrlen = len;
3550 do {
3551 int winlen = ai->ai_addrlen;
3552
3553 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
3554 ai->ai_addrlen = winlen;
3555 break;
3556 }
3557 len = 2*len;
3558 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
3559 if (!ai->ai_addr)
3560 goto outofmem;
3561 ai->ai_addrlen = len;
3562 } while (1);
3563 xuai = xuai->ai_next;
3564 }
3565 freeaddrinfo(unixaires);
3566 } else {
3567 result = convert_eai_u2w(result);
3568 *res = NULL;
3569 }
3570 return result;
3571
3572 outofmem:
3573 if (*res) WS_freeaddrinfo(*res);
3574 if (unixaires) freeaddrinfo(unixaires);
3575 *res = NULL;
3576 return WSA_NOT_ENOUGH_MEMORY;
3577 #else
3578 FIXME("getaddrinfo() failed, not found during buildtime.\n");
3579 return EAI_FAIL;
3580 #endif
3581 }
3582
3583 /***********************************************************************
3584 * GetAddrInfoW (WS2_32.@)
3585 */
3586 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
3587 {
3588 FIXME("empty stub!\n");
3589 return EAI_FAIL;
3590 }
3591
3592 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
3593 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
3594 {
3595 #ifdef HAVE_GETNAMEINFO
3596 int ret;
3597 union generic_unix_sockaddr sa_u;
3598 unsigned int size;
3599
3600 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
3601 serv, servlen, flags);
3602
3603 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
3604 if (!size)
3605 {
3606