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