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 int totalLength = 0;
1254 int i;
1255 status = STATUS_SUCCESS;
1256 for (i = 0; i < wsa->n_iovecs; i++)
1257 totalLength += wsa->iovec[i].iov_len;
1258 if (result < totalLength)
1259 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1260 }
1261 else
1262 {
1263 if (errno == EINTR || errno == EAGAIN)
1264 {
1265 status = STATUS_PENDING;
1266 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1267 }
1268 else
1269 {
1270 /* We set the status to a winsock error code and check for that
1271 later in NtStatusToWSAError () */
1272 status = wsaErrno();
1273 result = 0;
1274 }
1275 }
1276 break;
1277 }
1278 if (status != STATUS_PENDING)
1279 {
1280 iosb->u.Status = status;
1281 iosb->Information = *total = result;
1282 }
1283 return status;
1284 }
1285
1286 /***********************************************************************
1287 * WS2_async_shutdown (INTERNAL)
1288 *
1289 * Handler for shutdown() operations on overlapped sockets.
1290 */
1291 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status )
1292 {
1293 ws2_async* wsa = user;
1294 int fd, err = 1;
1295
1296 switch (status)
1297 {
1298 case STATUS_ALERTED:
1299 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
1300 break;
1301
1302 switch ( wsa->type )
1303 {
1304 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
1305 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
1306 }
1307 wine_server_release_fd( wsa->hSocket, fd );
1308 status = err ? wsaErrno() : STATUS_SUCCESS;
1309 break;
1310 }
1311 iosb->u.Status = status;
1312 return status;
1313 }
1314
1315 /***********************************************************************
1316 * WS2_register_async_shutdown (INTERNAL)
1317 *
1318 * Helper function for WS_shutdown() on overlapped sockets.
1319 */
1320 static int WS2_register_async_shutdown( SOCKET s, int type )
1321 {
1322 struct ws2_async *wsa;
1323 NTSTATUS status;
1324
1325 TRACE("s %ld type %d\n", s, type);
1326
1327 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
1328 if ( !wsa )
1329 return WSAEFAULT;
1330
1331 wsa->hSocket = SOCKET2HANDLE(s);
1332 wsa->type = type;
1333 wsa->completion_func = NULL;
1334
1335 SERVER_START_REQ( register_async )
1336 {
1337 req->handle = wsa->hSocket;
1338 req->type = type;
1339 req->async.callback = WS2_async_shutdown;
1340 req->async.iosb = &wsa->local_iosb;
1341 req->async.arg = wsa;
1342 req->async.apc = ws2_async_apc;
1343 req->async.cvalue = 0;
1344 status = wine_server_call( req );
1345 }
1346 SERVER_END_REQ;
1347
1348 if (status != STATUS_PENDING)
1349 {
1350 HeapFree( GetProcessHeap(), 0, wsa );
1351 return NtStatusToWSAError( status );
1352 }
1353 return 0;
1354 }
1355
1356 /***********************************************************************
1357 * accept (WS2_32.1)
1358 */
1359 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr,
1360 int *addrlen32)
1361 {
1362 SOCKET as;
1363 BOOL is_blocking;
1364
1365 TRACE("socket %04lx\n", s );
1366 is_blocking = _is_blocking(s);
1367
1368 do {
1369 if (is_blocking)
1370 {
1371 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1372 if (fd == -1) return INVALID_SOCKET;
1373 /* block here */
1374 do_block(fd, POLLIN, -1);
1375 _sync_sock_state(s); /* let wineserver notice connection */
1376 release_sock_fd( s, fd );
1377 /* retrieve any error codes from it */
1378 SetLastError(_get_sock_error(s, FD_ACCEPT_BIT));
1379 /* FIXME: care about the error? */
1380 }
1381 SERVER_START_REQ( accept_socket )
1382 {
1383 req->lhandle = SOCKET2HANDLE(s);
1384 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
1385 req->attributes = OBJ_INHERIT;
1386 set_error( wine_server_call( req ) );
1387 as = HANDLE2SOCKET( reply->handle );
1388 }
1389 SERVER_END_REQ;
1390 if (as)
1391 {
1392 if (addr) WS_getpeername(as, addr, addrlen32);
1393 return as;
1394 }
1395 } while (is_blocking);
1396 return INVALID_SOCKET;
1397 }
1398
1399 /***********************************************************************
1400 * bind (WS2_32.2)
1401 */
1402 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
1403 {
1404 int fd = get_sock_fd( s, 0, NULL );
1405 int res = SOCKET_ERROR;
1406
1407 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1408
1409 if (fd != -1)
1410 {
1411 if (!name || (name->sa_family && !SUPPORTED_PF(name->sa_family)))
1412 {
1413 SetLastError(WSAEAFNOSUPPORT);
1414 }
1415 else
1416 {
1417 union generic_unix_sockaddr uaddr;
1418 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1419 if (!uaddrlen)
1420 {
1421 SetLastError(WSAEFAULT);
1422 }
1423 else
1424 {
1425 #ifdef IPV6_V6ONLY
1426 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
1427 if (name->sa_family == WS_AF_INET6 &&
1428 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
1429 {
1430 int enable = 1;
1431 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
1432 {
1433 release_sock_fd( s, fd );
1434 SetLastError(WSAEAFNOSUPPORT);
1435 return INVALID_SOCKET;
1436 }
1437 }
1438 #endif
1439 if (name->sa_family == WS_AF_INET)
1440 {
1441 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
1442 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
1443 {
1444 /* Trying to bind to the default host interface, using
1445 * INADDR_ANY instead*/
1446 WARN("Trying to bind to magic IP address, using "
1447 "INADDR_ANY instead.\n");
1448 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
1449 }
1450 }
1451 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
1452 {
1453 int loc_errno = errno;
1454 WARN("\tfailure - errno = %i\n", errno);
1455 errno = loc_errno;
1456 switch (errno)
1457 {
1458 case EBADF:
1459 SetLastError(WSAENOTSOCK);
1460 break;
1461 case EADDRNOTAVAIL:
1462 SetLastError(WSAEINVAL);
1463 break;
1464 default:
1465 SetLastError(wsaErrno());
1466 break;
1467 }
1468 }
1469 else
1470 {
1471 res=0; /* success */
1472 }
1473 }
1474 }
1475 release_sock_fd( s, fd );
1476 }
1477 return res;
1478 }
1479
1480 /***********************************************************************
1481 * closesocket (WS2_32.3)
1482 */
1483 int WINAPI WS_closesocket(SOCKET s)
1484 {
1485 TRACE("socket %04lx\n", s);
1486 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
1487 return SOCKET_ERROR;
1488 }
1489
1490 /***********************************************************************
1491 * connect (WS2_32.4)
1492 */
1493 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
1494 {
1495 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1496
1497 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1498
1499 if (fd != -1)
1500 {
1501 union generic_unix_sockaddr uaddr;
1502 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1503
1504 if (!uaddrlen)
1505 {
1506 SetLastError(WSAEFAULT);
1507 }
1508 else
1509 {
1510 if (name->sa_family == WS_AF_INET)
1511 {
1512 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
1513 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
1514 {
1515 /* Trying to connect to magic replace-loopback address,
1516 * assuming we really want to connect to localhost */
1517 TRACE("Trying to connect to magic IP address, using "
1518 "INADDR_LOOPBACK instead.\n");
1519 in4->sin_addr.s_addr = htonl(WS_INADDR_LOOPBACK);
1520 }
1521 }
1522
1523 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
1524 goto connect_success;
1525 }
1526
1527 if (errno == EINPROGRESS)
1528 {
1529 /* tell wineserver that a connection is in progress */
1530 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1531 FD_CONNECT|FD_READ|FD_WRITE,
1532 FD_WINE_CONNECTED|FD_WINE_LISTENING);
1533 if (_is_blocking(s))
1534 {
1535 int result;
1536 /* block here */
1537 do_block(fd, POLLIN | POLLOUT, -1);
1538 _sync_sock_state(s); /* let wineserver notice connection */
1539 /* retrieve any error codes from it */
1540 result = _get_sock_error(s, FD_CONNECT_BIT);
1541 if (result)
1542 SetLastError(result);
1543 else
1544 {
1545 goto connect_success;
1546 }
1547 }
1548 else
1549 {
1550 SetLastError(WSAEWOULDBLOCK);
1551 }
1552 }
1553 else
1554 {
1555 SetLastError(wsaErrno());
1556 }
1557 release_sock_fd( s, fd );
1558 }
1559 return SOCKET_ERROR;
1560
1561 connect_success:
1562 release_sock_fd( s, fd );
1563 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1564 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
1565 FD_CONNECT|FD_WINE_LISTENING);
1566 return 0;
1567 }
1568
1569 /***********************************************************************
1570 * WSAConnect (WS2_32.30)
1571 */
1572 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
1573 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
1574 LPQOS lpSQOS, LPQOS lpGQOS )
1575 {
1576 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
1577 FIXME("unsupported parameters!\n");
1578 return WS_connect( s, name, namelen );
1579 }
1580
1581
1582 /***********************************************************************
1583 * getpeername (WS2_32.5)
1584 */
1585 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
1586 {
1587 int fd;
1588 int res;
1589
1590 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, *namelen);
1591
1592 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1593 if( (name == NULL) || (namelen == NULL) )
1594 {
1595 SetLastError( WSAEFAULT );
1596 return SOCKET_ERROR;
1597 }
1598
1599 fd = get_sock_fd( s, 0, NULL );
1600 res = SOCKET_ERROR;
1601
1602 if (fd != -1)
1603 {
1604 union generic_unix_sockaddr uaddr;
1605 unsigned int uaddrlen = sizeof(uaddr);
1606
1607 if (getpeername(fd, &uaddr.addr, &uaddrlen) != 0)
1608 {
1609 SetLastError(wsaErrno());
1610 }
1611 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1612 {
1613 /* The buffer was too small */
1614 SetLastError(WSAEFAULT);
1615 }
1616 else
1617 {
1618 res=0;
1619 }
1620 release_sock_fd( s, fd );
1621 }
1622 return res;
1623 }
1624
1625 /***********************************************************************
1626 * getsockname (WS2_32.6)
1627 */
1628 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
1629 {
1630 int fd;
1631 int res;
1632
1633 TRACE("socket: %04lx, ptr %p, len %8x\n", s, name, *namelen);
1634
1635 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1636 if( (name == NULL) || (namelen == NULL) )
1637 {
1638 SetLastError( WSAEFAULT );
1639 return SOCKET_ERROR;
1640 }
1641
1642 fd = get_sock_fd( s, 0, NULL );
1643 res = SOCKET_ERROR;
1644
1645 if (fd != -1)
1646 {
1647 union generic_unix_sockaddr uaddr;
1648 unsigned int uaddrlen = sizeof(uaddr);
1649
1650 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
1651 {
1652 SetLastError(wsaErrno());
1653 }
1654 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
1655 {
1656 SetLastError(WSAEINVAL);
1657 }
1658 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1659 {
1660 /* The buffer was too small */
1661 SetLastError(WSAEFAULT);
1662 }
1663 else
1664 {
1665 res=0;
1666 }
1667 release_sock_fd( s, fd );
1668 }
1669 return res;
1670 }
1671
1672 /***********************************************************************
1673 * getsockopt (WS2_32.7)
1674 */
1675 INT WINAPI WS_getsockopt(SOCKET s, INT level,
1676 INT optname, char *optval, INT *optlen)
1677 {
1678 int fd;
1679 INT ret = 0;
1680
1681 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
1682 s, level, optname, optval, *optlen);
1683
1684 switch(level)
1685 {
1686 case WS_SOL_SOCKET:
1687 {
1688 switch(optname)
1689 {
1690 /* Handle common cases. The special cases are below, sorted
1691 * alphabetically */
1692 case WS_SO_ACCEPTCONN:
1693 case WS_SO_BROADCAST:
1694 case WS_SO_DEBUG:
1695 case WS_SO_ERROR:
1696 case WS_SO_KEEPALIVE:
1697 case WS_SO_OOBINLINE:
1698 case WS_SO_RCVBUF:
1699 case WS_SO_REUSEADDR:
1700 case WS_SO_SNDBUF:
1701 case WS_SO_TYPE:
1702 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1703 return SOCKET_ERROR;
1704 convert_sockopt(&level, &optname);
1705 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1706 {
1707 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1708 ret = SOCKET_ERROR;
1709 }
1710 release_sock_fd( s, fd );
1711 return ret;
1712
1713 case WS_SO_DONTLINGER:
1714 {
1715 struct linger lingval;
1716 unsigned int len = sizeof(struct linger);
1717
1718 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
1719 {
1720 SetLastError(WSAEFAULT);
1721 return SOCKET_ERROR;
1722 }
1723 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1724 return SOCKET_ERROR;
1725
1726 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
1727 {
1728 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1729 ret = SOCKET_ERROR;
1730 }
1731 else
1732 {
1733 *(BOOL *)optval = (lingval.l_onoff) ? FALSE : TRUE;
1734 *optlen = sizeof(BOOL);
1735 }
1736
1737 release_sock_fd( s, fd );
1738 return ret;
1739 }
1740
1741 /* As mentioned in setsockopt, Windows ignores this, so we
1742 * always return true here */
1743 case WS_SO_DONTROUTE:
1744 if (!optlen || *optlen < sizeof(BOOL) || !optval)
1745 {
1746 SetLastError(WSAEFAULT);
1747 return SOCKET_ERROR;
1748 }
1749 *(BOOL *)optval = TRUE;
1750 *optlen = sizeof(BOOL);
1751 return 0;
1752
1753 case WS_SO_LINGER:
1754 {
1755 struct linger lingval;
1756 unsigned int len = sizeof(struct linger);
1757
1758 /* struct linger and LINGER have different sizes */
1759 if (!optlen || *optlen < sizeof(LINGER) || !optval)
1760 {
1761 SetLastError(WSAEFAULT);
1762 return SOCKET_ERROR;
1763 }
1764 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1765 return SOCKET_ERROR;
1766
1767 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
1768 {
1769 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1770 ret = SOCKET_ERROR;
1771 }
1772 else
1773 {
1774 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
1775 ((LINGER *)optval)->l_linger = lingval.l_linger;
1776 *optlen = sizeof(struct linger);
1777 }
1778
1779 release_sock_fd( s, fd );
1780 return ret;
1781 }
1782
1783 case WS_SO_MAX_MSG_SIZE:
1784 if (!optlen || *optlen < sizeof(int) || !optval)
1785 {
1786 SetLastError(WSAEFAULT);
1787 return SOCKET_ERROR;
1788 }
1789 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
1790 *(int *)optval = 65507;
1791 *optlen = sizeof(int);
1792 return 0;
1793
1794 /* SO_OPENTYPE does not require a valid socket handle. */
1795 case WS_SO_OPENTYPE:
1796 if (!optlen || *optlen < sizeof(int) || !optval)
1797 {
1798 SetLastError(WSAEFAULT);
1799 return SOCKET_ERROR;
1800 }
1801 *(int *)optval = get_per_thread_data()->opentype;
1802 *optlen = sizeof(int);
1803 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
1804 return 0;
1805
1806 #ifdef SO_RCVTIMEO
1807 case WS_SO_RCVTIMEO:
1808 #endif
1809 #ifdef SO_SNDTIMEO
1810 case WS_SO_SNDTIMEO:
1811 #endif
1812 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
1813 {
1814 struct timeval tv;
1815 unsigned int len = sizeof(struct timeval);
1816
1817 if (!optlen || *optlen < sizeof(int)|| !optval)
1818 {
1819 SetLastError(WSAEFAULT);
1820 return SOCKET_ERROR;
1821 }
1822 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1823 return SOCKET_ERROR;
1824
1825 convert_sockopt(&level, &optname);
1826 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
1827 {
1828 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1829 ret = SOCKET_ERROR;
1830 }
1831 else
1832 {
1833 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
1834 *optlen = sizeof(int);
1835 }
1836
1837 release_sock_fd( s, fd );
1838 return ret;
1839 }
1840 #endif
1841 default:
1842 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
1843 SetLastError(WSAENOPROTOOPT);
1844 return SOCKET_ERROR;
1845 } /* end switch(optname) */
1846 }/* end case WS_SOL_SOCKET */
1847 #ifdef HAVE_IPX
1848 case NSPROTO_IPX:
1849 {
1850 struct WS_sockaddr_ipx addr;
1851 IPX_ADDRESS_DATA *data;
1852 int namelen;
1853 switch(optname)
1854 {
1855 case IPX_PTYPE:
1856 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
1857 #ifdef SOL_IPX
1858 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (unsigned int*)optlen) == -1)
1859 {
1860 ret = SOCKET_ERROR;
1861 }
1862 #else
1863 {
1864 struct ipx val;
1865 socklen_t len=sizeof(struct ipx);
1866 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
1867 ret = SOCKET_ERROR;
1868 else
1869 *optval = (int)val.ipx_pt;
1870 }
1871 #endif
1872 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
1873 release_sock_fd( s, fd );
1874 return ret;
1875
1876 case IPX_ADDRESS:
1877 /*
1878 * On a Win2000 system with one network card there are usually
1879 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
1880 * Using this call you can then retrieve info about this all.
1881 * In case of Linux it is a bit different. Usually you have
1882 * only "one" device active and further it is not possible to
1883 * query things like the linkspeed.
1884 */
1885 FIXME("IPX_ADDRESS\n");
1886 namelen = sizeof(struct WS_sockaddr_ipx);
1887 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
1888 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
1889
1890 data = (IPX_ADDRESS_DATA*)optval;
1891 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
1892 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
1893 data->adapternum = 0;
1894 data->wan = FALSE; /* We are not on a wan for now .. */
1895 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
1896 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
1897 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
1898 * note 1MB = 1000kB in this case */
1899 return 0;
1900
1901 case IPX_MAX_ADAPTER_NUM:
1902 FIXME("IPX_MAX_ADAPTER_NUM\n");
1903 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
1904 return 0;
1905
1906 default:
1907 FIXME("IPX optname:%x\n", optname);
1908 return SOCKET_ERROR;
1909 }/* end switch(optname) */
1910 } /* end case NSPROTO_IPX */
1911 #endif
1912 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
1913 case WS_IPPROTO_TCP:
1914 switch(optname)
1915 {
1916 case WS_TCP_NODELAY:
1917 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1918 return SOCKET_ERROR;
1919 convert_sockopt(&level, &optname);
1920 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1921 {
1922 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1923 ret = SOCKET_ERROR;
1924 }
1925 release_sock_fd( s, fd );
1926 return ret;
1927 }
1928 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
1929 return SOCKET_ERROR;
1930
1931 case WS_IPPROTO_IP:
1932 switch(optname)
1933 {
1934 case WS_IP_ADD_MEMBERSHIP:
1935 case WS_IP_DROP_MEMBERSHIP:
1936 #ifdef IP_HDRINCL
1937 case WS_IP_HDRINCL:
1938 #endif
1939 case WS_IP_MULTICAST_IF:
1940 case WS_IP_MULTICAST_LOOP:
1941 case WS_IP_MULTICAST_TTL:
1942 case WS_IP_OPTIONS:
1943 case WS_IP_TOS:
1944 case WS_IP_TTL:
1945 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1946 return SOCKET_ERROR;
1947 convert_sockopt(&level, &optname);
1948 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1949 {
1950 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1951 ret = SOCKET_ERROR;
1952 }
1953 release_sock_fd( s, fd );
1954 return ret;
1955 case WS_IP_DONTFRAGMENT:
1956 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
1957 *(BOOL*)optval = FALSE;
1958 return 0;
1959 }
1960 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
1961 return SOCKET_ERROR;
1962
1963 default:
1964 FIXME("Unknown level: 0x%08x\n", level);
1965 return SOCKET_ERROR;
1966 } /* end switch(level) */
1967 }
1968
1969 /***********************************************************************
1970 * htonl (WINSOCK.8)
1971 * htonl (WS2_32.8)
1972 */
1973 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
1974 {
1975 return htonl(hostlong);
1976 }
1977
1978
1979 /***********************************************************************
1980 * htons (WINSOCK.9)
1981 * htons (WS2_32.9)
1982 */
1983 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
1984 {
1985 return htons(hostshort);
1986 }
1987
1988 /***********************************************************************
1989 * WSAHtonl (WS2_32.46)
1990 * From MSDN description of error codes, this function should also
1991 * check if WinSock has been initialized and the socket is a valid
1992 * socket. But why? This function only translates a host byte order
1993 * u_long into a network byte order u_long...
1994 */
1995 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
1996 {
1997 if (lpnetlong)
1998 {
1999 *lpnetlong = htonl(hostlong);
2000 return 0;
2001 }
2002 WSASetLastError(WSAEFAULT);
2003 return SOCKET_ERROR;
2004 }
2005
2006 /***********************************************************************
2007 * WSAHtons (WS2_32.47)
2008 * From MSDN description of error codes, this function should also
2009 * check if WinSock has been initialized and the socket is a valid
2010 * socket. But why? This function only translates a host byte order
2011 * u_short into a network byte order u_short...
2012 */
2013 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
2014 {
2015
2016 if (lpnetshort)
2017 {
2018 *lpnetshort = htons(hostshort);
2019 return 0;
2020 }
2021 WSASetLastError(WSAEFAULT);
2022 return SOCKET_ERROR;
2023 }
2024
2025
2026 /***********************************************************************
2027 * inet_addr (WINSOCK.10)
2028 * inet_addr (WS2_32.11)
2029 */
2030 WS_u_long WINAPI WS_inet_addr(const char *cp)
2031 {
2032 if (!cp) return INADDR_NONE;
2033 return inet_addr(cp);
2034 }
2035
2036
2037 /***********************************************************************
2038 * ntohl (WINSOCK.14)
2039 * ntohl (WS2_32.14)
2040 */
2041 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
2042 {
2043 return ntohl(netlong);
2044 }
2045
2046
2047 /***********************************************************************
2048 * ntohs (WINSOCK.15)
2049 * ntohs (WS2_32.15)
2050 */
2051 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
2052 {
2053 return ntohs(netshort);
2054 }
2055
2056
2057 /***********************************************************************
2058 * inet_ntoa (WS2_32.12)
2059 */
2060 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
2061 {
2062 /* use "buffer for dummies" here because some applications have a
2063 * propensity to decode addresses in ws_hostent structure without
2064 * saving them first...
2065 */
2066 static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
2067
2068 char* s = inet_ntoa(*((struct in_addr*)&in));
2069 if( s )
2070 {
2071 strcpy(dbuffer, s);
2072 return dbuffer;
2073 }
2074 SetLastError(wsaErrno());
2075 return NULL;
2076 }
2077
2078 /**********************************************************************
2079 * WSAIoctl (WS2_32.50)
2080 *
2081 */
2082 INT WINAPI WSAIoctl(SOCKET s,
2083 DWORD dwIoControlCode,
2084 LPVOID lpvInBuffer,
2085 DWORD cbInBuffer,
2086 LPVOID lpbOutBuffer,
2087 DWORD cbOutBuffer,
2088 LPDWORD lpcbBytesReturned,
2089 LPWSAOVERLAPPED lpOverlapped,
2090 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2091 {
2092 TRACE("%ld, 0x%08x, %p, %d, %p, %d, %p, %p, %p\n",
2093 s, dwIoControlCode, lpvInBuffer, cbInBuffer, lpbOutBuffer,
2094 cbOutBuffer, lpcbBytesReturned, lpOverlapped, lpCompletionRoutine);
2095
2096 switch( dwIoControlCode )
2097 {
2098 case WS_FIONBIO:
2099 if (cbInBuffer != sizeof(WS_u_long)) {
2100 WSASetLastError(WSAEFAULT);
2101 return SOCKET_ERROR;
2102 }
2103 return WS_ioctlsocket( s, WS_FIONBIO, lpvInBuffer);
2104
2105 case WS_FIONREAD:
2106 if (cbOutBuffer != sizeof(WS_u_long)) {
2107 WSASetLastError(WSAEFAULT);
2108 return SOCKET_ERROR;
2109 }
2110 return WS_ioctlsocket( s, WS_FIONREAD, lpbOutBuffer);
2111
2112 case WS_SIO_GET_INTERFACE_LIST:
2113 {
2114 INTERFACE_INFO* intArray = (INTERFACE_INFO*)lpbOutBuffer;
2115 DWORD size, numInt, apiReturn;
2116 int fd;
2117
2118 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
2119
2120 if (!lpbOutBuffer)
2121 {
2122 WSASetLastError(WSAEFAULT);
2123 return SOCKET_ERROR;
2124 }
2125 if (!lpcbBytesReturned)
2126 {
2127 WSASetLastError(WSAEFAULT);
2128 return SOCKET_ERROR;
2129 }
2130
2131 fd = get_sock_fd( s, 0, NULL );
2132 if (fd == -1) return SOCKET_ERROR;
2133
2134 apiReturn = GetAdaptersInfo(NULL, &size);
2135 if (apiReturn == ERROR_NO_DATA)
2136 {
2137 numInt = 0;
2138 }
2139 else if (apiReturn == ERROR_BUFFER_OVERFLOW)
2140 {
2141 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
2142
2143 if (table)
2144 {
2145 if (GetAdaptersInfo(table, &size) == NO_ERROR)
2146 {
2147 PIP_ADAPTER_INFO ptr;
2148
2149 if (size*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > cbOutBuffer)
2150 {
2151 WARN("Buffer too small = %u, cbOutBuffer = %u\n", size, cbOutBuffer);
2152 HeapFree(GetProcessHeap(),0,table);
2153 release_sock_fd( s, fd );
2154 WSASetLastError(WSAEFAULT);
2155 return SOCKET_ERROR;
2156 }
2157 for (ptr = table, numInt = 0; ptr;
2158 ptr = ptr->Next, intArray++, numInt++)
2159 {
2160 unsigned int addr, mask, bcast;
2161 struct ifreq ifInfo;
2162
2163 /* Socket Status Flags */
2164 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
2165 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
2166 {
2167 ERR("Error obtaining status flags for socket!\n");
2168 HeapFree(GetProcessHeap(),0,table);
2169 release_sock_fd( s, fd );
2170 WSASetLastError(WSAEINVAL);
2171 return SOCKET_ERROR;
2172 }
2173 else
2174 {
2175 /* set flags; the values of IFF_* are not the same
2176 under Linux and Windows, therefore must generate
2177 new flags */
2178 intArray->iiFlags = 0;
2179 if (ifInfo.ifr_flags & IFF_BROADCAST)
2180 intArray->iiFlags |= WS_IFF_BROADCAST;
2181 #ifdef IFF_POINTOPOINT
2182 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
2183 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
2184 #endif
2185 if (ifInfo.ifr_flags & IFF_LOOPBACK)
2186 intArray->iiFlags |= WS_IFF_LOOPBACK;
2187 if (ifInfo.ifr_flags & IFF_UP)
2188 intArray->iiFlags |= WS_IFF_UP;
2189 if (ifInfo.ifr_flags & IFF_MULTICAST)
2190 intArray->iiFlags |= WS_IFF_MULTICAST;
2191 }
2192
2193 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
2194 mask = inet_addr(ptr->IpAddressList.IpMask.String);
2195 bcast = addr | ~mask;
2196 intArray->iiAddress.AddressIn.sin_family = AF_INET;
2197 intArray->iiAddress.AddressIn.sin_port = 0;
2198 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
2199 addr;
2200 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
2201 intArray->iiNetmask.AddressIn.sin_port = 0;
2202 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
2203 mask;
2204 intArray->iiBroadcastAddress.AddressIn.sin_family =
2205 AF_INET;
2206 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
2207 intArray->iiBroadcastAddress.AddressIn.sin_addr.
2208 WS_s_addr = bcast;
2209 }
2210 }
2211 else
2212 {
2213 ERR("Unable to get interface table!\n");
2214 release_sock_fd( s, fd );
2215 HeapFree(GetProcessHeap(),0,table);
2216 WSASetLastError(WSAEINVAL);
2217 return SOCKET_ERROR;
2218 }
2219 HeapFree(GetProcessHeap(),0,table);
2220 }
2221 else
2222 {
2223 release_sock_fd( s, fd );
2224 WSASetLastError(WSAEINVAL);
2225 return SOCKET_ERROR;
2226 }
2227 }
2228 else
2229 {
2230 ERR("Unable to get interface table!\n");
2231 release_sock_fd( s, fd );
2232 WSASetLastError(WSAEINVAL);
2233 return SOCKET_ERROR;
2234 }
2235 /* Calculate the size of the array being returned */
2236 *lpcbBytesReturned = sizeof(INTERFACE_INFO) * numInt;
2237 release_sock_fd( s, fd );
2238 break;
2239 }
2240
2241 case WS_SIO_ADDRESS_LIST_CHANGE:
2242 FIXME("-> SIO_ADDRESS_LIST_CHANGE request: stub\n");
2243 /* FIXME: error and return code depend on whether socket was created
2244 * with WSA_FLAG_OVERLAPPED, but there is no easy way to get this */
2245 break;
2246
2247 case WS_SIO_ADDRESS_LIST_QUERY:
2248 {
2249 DWORD size;
2250
2251 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
2252
2253 if (!lpcbBytesReturned)
2254 {
2255 WSASetLastError(WSAEFAULT);
2256 return SOCKET_ERROR;
2257 }
2258
2259 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
2260 {
2261 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
2262 DWORD need, num;
2263
2264 if (!table || GetAdaptersInfo(table, &size))
2265 {
2266 HeapFree(GetProcessHeap(), 0, table);
2267 WSASetLastError(WSAEINVAL);
2268 return SOCKET_ERROR;
2269 }
2270
2271 for (p = table, num = 0; p; p = p->Next)
2272 if (p->IpAddressList.IpAddress.String[0]) num++;
2273
2274 need = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
2275 need += sizeof(SOCKADDR) * num;
2276 *lpcbBytesReturned = need;
2277
2278 if (need > cbOutBuffer)
2279 {
2280 HeapFree(GetProcessHeap(), 0, table);
2281 WSASetLastError(WSAEFAULT);
2282 return SOCKET_ERROR;
2283 }
2284
2285 if (lpbOutBuffer)
2286 {
2287 unsigned int i;
2288 SOCKET_ADDRESS *sa;
2289 SOCKET_ADDRESS_LIST *sa_list = (SOCKET_ADDRESS_LIST *)lpbOutBuffer;
2290 SOCKADDR_IN *sockaddr;
2291
2292 sa = sa_list->Address;
2293 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
2294 sa_list->iAddressCount = num;
2295
2296 for (p = table, i = 0; p; p = p->Next)
2297 {
2298 if (!p->IpAddressList.IpAddress.String[0]) continue;
2299
2300 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
2301 sa[i].iSockaddrLength = sizeof(SOCKADDR);
2302
2303 sockaddr[i].sin_family = AF_INET;
2304 sockaddr[i].sin_port = 0;
2305 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
2306 i++;
2307 }
2308 }
2309
2310 HeapFree(GetProcessHeap(), 0, table);
2311 return 0;
2312 }
2313 else
2314 {
2315 WARN("unable to get IP address list\n");
2316 WSASetLastError(WSAEINVAL);
2317 return SOCKET_ERROR;
2318 }
2319 }
2320 case WS_SIO_FLUSH:
2321 FIXME("SIO_FLUSH: stub.\n");
2322 break;
2323
2324 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
2325 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(lpvInBuffer));
2326 WSASetLastError(WSAEOPNOTSUPP);
2327 return SOCKET_ERROR;
2328
2329 default:
2330 FIXME("unsupported WS_IOCTL cmd (%08x)\n", dwIoControlCode);
2331 WSASetLastError(WSAEOPNOTSUPP);
2332 return SOCKET_ERROR;
2333 }
2334
2335 return 0;
2336 }
2337
2338
2339 /***********************************************************************
2340 * ioctlsocket (WS2_32.10)
2341 */
2342 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
2343 {
2344 int fd;
2345 long newcmd = cmd;
2346
2347 TRACE("socket %04lx, cmd %08x, ptr %p\n", s, cmd, argp);
2348 /* broken apps like defcon pass the argp value directly instead of a pointer to it */
2349 if(IS_INTRESOURCE(argp))
2350 {
2351 SetLastError(WSAEFAULT);
2352 return SOCKET_ERROR;
2353 }
2354
2355 switch( cmd )
2356 {
2357 case WS_FIONREAD:
2358 newcmd=FIONREAD;
2359 break;
2360
2361 case WS_FIONBIO:
2362 if( _get_sock_mask(s) )
2363 {
2364 /* AsyncSelect()'ed sockets are always nonblocking */
2365 if (*argp) return 0;
2366 SetLastError(WSAEINVAL);
2367 return SOCKET_ERROR;
2368 }
2369 fd = get_sock_fd( s, 0, NULL );
2370 if (fd != -1)
2371 {
2372 int ret;
2373 if (*argp)
2374 {
2375 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
2376 ret = fcntl( fd, F_SETFL, O_NONBLOCK );
2377 }
2378 else
2379 {
2380 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
2381 ret = fcntl( fd, F_SETFL, 0 );
2382 }
2383 release_sock_fd( s, fd );
2384 if (!ret) return 0;
2385 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2386 }
2387 return SOCKET_ERROR;
2388
2389 case WS_SIOCATMARK:
2390 newcmd=SIOCATMARK;
2391 break;
2392
2393 case WS_FIOASYNC:
2394 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
2395 SetLastError(WSAEINVAL);
2396 return SOCKET_ERROR;
2397
2398 case SIOCGIFBRDADDR:
2399 case SIOCGIFNETMASK:
2400 case SIOCGIFADDR:
2401 /* These don't need any special handling. They are used by
2402 WsControl, and are here to suppress an unnecessary warning. */
2403 break;
2404
2405 default:
2406 /* Netscape tries hard to use bogus ioctl 0x667e */
2407 /* FIXME: 0x667e above is ('f' << 8) | 126, and is a low word of
2408 * FIONBIO (_IOW('f', 126, u_long)), how that should be handled?
2409 */
2410 WARN("\tunknown WS_IOCTL cmd (%08x)\n", cmd);
2411 break;
2412 }
2413
2414 fd = get_sock_fd( s, 0, NULL );
2415 if (fd != -1)
2416 {
2417 if( ioctl(fd, newcmd, (char*)argp ) == 0 )
2418 {
2419 release_sock_fd( s, fd );
2420 return 0;
2421 }
2422 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2423 release_sock_fd( s, fd );
2424 }
2425 return SOCKET_ERROR;
2426 }
2427
2428 /***********************************************************************
2429 * listen (WS2_32.13)
2430 */
2431 int WINAPI WS_listen(SOCKET s, int backlog)
2432 {
2433 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2434
2435 TRACE("socket %04lx, backlog %d\n", s, backlog);
2436 if (fd != -1)
2437 {
2438 if (listen(fd, backlog) == 0)
2439 {
2440 release_sock_fd( s, fd );
2441 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
2442 FD_WINE_LISTENING,
2443 FD_CONNECT|FD_WINE_CONNECTED);
2444 return 0;
2445 }
2446 SetLastError(wsaErrno());
2447 release_sock_fd( s, fd );
2448 }
2449 return SOCKET_ERROR;
2450 }
2451
2452 /***********************************************************************
2453 * recv (WS2_32.16)
2454 */
2455 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
2456 {
2457 DWORD n, dwFlags = flags;
2458 WSABUF wsabuf;
2459
2460 wsabuf.len = len;
2461 wsabuf.buf = buf;
2462
2463 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
2464 return SOCKET_ERROR;
2465 else
2466 return n;
2467 }
2468
2469 /***********************************************************************
2470 * recvfrom (WS2_32.17)
2471 */
2472 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
2473 struct WS_sockaddr *from, int *fromlen)
2474 {
2475 DWORD n, dwFlags = flags;
2476 WSABUF wsabuf;
2477
2478 wsabuf.len = len;
2479 wsabuf.buf = buf;
2480
2481 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL) == SOCKET_ERROR )
2482 return SOCKET_ERROR;
2483 else
2484 return n;
2485 }
2486
2487 /* allocate a poll array for the corresponding fd sets */
2488 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
2489 const WS_fd_set *exceptfds, int *count_ptr )
2490 {
2491 int i, j = 0, count = 0;
2492 struct pollfd *fds;
2493
2494 if (readfds) count += readfds->fd_count;
2495 if (writefds) count += writefds->fd_count;
2496 if (exceptfds) count += exceptfds->fd_count;
2497 *count_ptr = count;
2498 if (!count) return NULL;
2499 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0])))) return NULL;
2500 if (readfds)
2501 for (i = 0; i < readfds->fd_count; i++, j++)
2502 {
2503 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
2504 fds[j].events = POLLIN;
2505 fds[j].revents = 0;
2506 }
2507 if (writefds)
2508 for (i = 0; i < writefds->fd_count; i++, j++)
2509 {
2510 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
2511 fds[j].events = POLLOUT;
2512 fds[j].revents = 0;
2513 }
2514 if (exceptfds)
2515 for (i = 0; i < exceptfds->fd_count; i++, j++)
2516 {
2517 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
2518 fds[j].events = POLLHUP;
2519 fds[j].revents = 0;
2520 }
2521 return fds;
2522 }
2523
2524 /* release the file descriptor obtained in fd_sets_to_poll */
2525 /* must be called with the original fd_set arrays, before calling get_poll_results */
2526 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
2527 const WS_fd_set *exceptfds, struct pollfd *fds )
2528 {
2529 int i, j = 0;
2530
2531 if (readfds)
2532 {
2533 for (i = 0; i < readfds->fd_count; i++, j++)
2534 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
2535 }
2536 if (writefds)
2537 {
2538 for (i = 0; i < writefds->fd_count; i++, j++)
2539 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
2540 }
2541 if (exceptfds)
2542 {
2543 for (i = 0; i < exceptfds->fd_count; i++, j++)
2544 if (fds[j].fd != -1)
2545 {
2546 /* make sure we have a real error before releasing the fd */
2547 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
2548 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
2549 }
2550 }
2551 }
2552
2553 /* map the poll results back into the Windows fd sets */
2554 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
2555 const struct pollfd *fds )
2556 {
2557 int i, j = 0, k, total = 0;
2558
2559 if (readfds)
2560 {
2561 for (i = k = 0; i < readfds->fd_count; i++, j++)
2562 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
2563 readfds->fd_count = k;
2564 total += k;
2565 }
2566 if (writefds)
2567 {
2568 for (i = k = 0; i < writefds->fd_count; i++, j++)
2569 if (fds[j].revents) writefds->fd_array[k++] = writefds->fd_array[i];
2570 writefds->fd_count = k;
2571 total += k;
2572 }
2573 if (exceptfds)
2574 {
2575 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
2576 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
2577 exceptfds->fd_count = k;
2578 total += k;
2579 }
2580 return total;
2581 }
2582
2583
2584 /***********************************************************************
2585 * select (WS2_32.18)
2586 */
2587 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
2588 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
2589 const struct WS_timeval* ws_timeout)
2590 {
2591 struct pollfd *pollfds;
2592 int count, ret, timeout = -1;
2593
2594 TRACE("read %p, write %p, excp %p timeout %p\n",
2595 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
2596
2597 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )) && count)
2598 {
2599 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2600 return SOCKET_ERROR;
2601 }
2602
2603 if (ws_timeout) timeout = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
2604
2605 ret = poll( pollfds, count, timeout );
2606 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2607
2608 if (ret == -1) SetLastError(wsaErrno());
2609 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2610 HeapFree( GetProcessHeap(), 0, pollfds );
2611 return ret;
2612 }
2613
2614 /* helper to send completion messages for client-only i/o operation case */
2615 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus, ULONG_PTR Information )
2616 {
2617 NTSTATUS status;
2618
2619 SERVER_START_REQ( add_fd_completion )
2620 {
2621 req->handle = SOCKET2HANDLE(sock);
2622 req->cvalue = CompletionValue;
2623 req->status = CompletionStatus;
2624 req->information = Information;
2625 status = wine_server_call( req );
2626 }
2627 SERVER_END_REQ;
2628 }
2629
2630
2631 /***********************************************************************
2632 * send (WS2_32.19)
2633 */
2634 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
2635 {
2636 DWORD n;
2637 WSABUF wsabuf;
2638
2639 wsabuf.len = len;
2640 wsabuf.buf = (char*) buf;
2641
2642 if ( WSASendTo( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
2643 return SOCKET_ERROR;
2644 else
2645 return n;
2646 }
2647
2648 /***********************************************************************
2649 * WSASend (WS2_32.72)
2650 */
2651 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2652 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2653 LPWSAOVERLAPPED lpOverlapped,
2654 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2655 {
2656 return WSASendTo( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
2657 NULL, 0, lpOverlapped, lpCompletionRoutine );
2658 }
2659
2660 /***********************************************************************
2661 * WSASendDisconnect (WS2_32.73)
2662 */
2663 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
2664 {
2665 return WS_shutdown( s, SD_SEND );
2666 }
2667
2668
2669 /***********************************************************************
2670 * WSASendTo (WS2_32.74)
2671 */
2672 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2673 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2674 const struct WS_sockaddr *to, int tolen,
2675 LPWSAOVERLAPPED lpOverlapped,
2676 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2677 {
2678 unsigned int i, options;
2679 int n, fd, err;
2680 struct iovec iovec[WS_MSG_MAXIOVLEN];
2681 int totalLength = 0;
2682 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
2683
2684 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
2685 s, lpBuffers, dwBufferCount, dwFlags,
2686 to, tolen, lpOverlapped, lpCompletionRoutine);
2687
2688 if (dwBufferCount > WS_MSG_MAXIOVLEN)
2689 {
2690 WSASetLastError( WSAEINVAL );
2691 return SOCKET_ERROR;
2692 }
2693
2694 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
2695 TRACE( "fd=%d, options=%x\n", fd, options );
2696
2697 if ( fd == -1 ) return SOCKET_ERROR;
2698
2699 if ( !lpNumberOfBytesSent )
2700 {
2701 err = WSAEFAULT;
2702 goto error;
2703 }
2704
2705 for ( i = 0; i < dwBufferCount; i++ )
2706 {
2707 iovec[i].iov_base = lpBuffers[i].buf;
2708 iovec[i].iov_len = lpBuffers[i].len;
2709 totalLength += lpBuffers[i].len;
2710 }
2711
2712 for (;;)
2713 {
2714 n = WS2_send( fd, iovec, dwBufferCount, to, tolen, dwFlags );
2715 if (n != -1 || errno != EINTR) break;
2716 }
2717 if (n == -1 && errno != EAGAIN)
2718 {
2719 err = wsaErrno();
2720 if (cvalue) WS_AddCompletion( s, cvalue, err, 0 );
2721 goto error;
2722 }
2723
2724 if ((lpOverlapped || lpCompletionRoutine) &&
2725 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
2726 {
2727 IO_STATUS_BLOCK *iosb;
2728 struct ws2_async *wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
2729
2730 if ( !wsa )
2731 {
2732 err = WSAEFAULT;
2733 goto error;
2734 }
2735 release_sock_fd( s, fd );
2736
2737 wsa->hSocket = SOCKET2HANDLE(s);
2738 wsa->addr = (struct WS_sockaddr *)to;
2739 wsa->addrlen.val = tolen;
2740 wsa->flags = 0;
2741 wsa->user_overlapped = lpOverlapped;
2742 wsa->completion_func = lpCompletionRoutine;
2743 wsa->n_iovecs = dwBufferCount;
2744 memcpy( wsa->iovec, iovec, dwBufferCount * sizeof(*iovec) );
2745
2746 iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
2747 if (n == -1)
2748 {
2749 iosb->u.Status = STATUS_PENDING;
2750 iosb->Information = 0;
2751
2752 SERVER_START_REQ( register_async )
2753 {
2754 req->handle = wsa->hSocket;
2755 req->type = ASYNC_TYPE_WRITE;
2756 req->async.callback = WS2_async_send;
2757 req->async.iosb = iosb;
2758 req->async.arg = wsa;
2759 req->async.apc = ws2_async_apc;
2760 req->async.event = lpCompletionRoutine ? 0 : lpOverlapped->hEvent;
2761 req->async.cvalue = cvalue;
2762 err = wine_server_call( req );
2763 }
2764 SERVER_END_REQ;
2765
2766 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
2767 WSASetLastError( NtStatusToWSAError( err ));
2768 return SOCKET_ERROR;
2769 }
2770
2771 iosb->u.Status = STATUS_SUCCESS;
2772 iosb->Information = n;
2773 *lpNumberOfBytesSent = n;
2774 if (!wsa->completion_func)
2775 {
2776 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
2777 SetEvent( lpOverlapped->hEvent );
2778 HeapFree( GetProcessHeap(), 0, wsa );
2779 }
2780 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
2781 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
2782 WSASetLastError(0);
2783 return 0;
2784 }
2785
2786 if ( _is_blocking(s) )
2787 {
2788 /* On a blocking non-overlapped stream socket,
2789 * sending blocks until the entire buffer is sent. */
2790 DWORD timeout_start = GetTickCount();
2791 unsigned int first_buff = 0;
2792
2793 *lpNumberOfBytesSent = 0;
2794
2795 while (first_buff < dwBufferCount)
2796 {
2797 struct pollfd pfd;
2798 int timeout = GET_SNDTIMEO(fd);
2799
2800 if (n >= 0)
2801 {
2802 *lpNumberOfBytesSent += n;
2803 while (first_buff < dwBufferCount && iovec[first_buff].iov_len <= n)
2804 n -= iovec[first_buff++].iov_len;
2805 if (first_buff >= dwBufferCount) break;
2806 iovec[first_buff].iov_base = (char*)iovec[first_buff].iov_base + n;
2807 iovec[first_buff].iov_len -= n;
2808 }
2809
2810 if (timeout != -1)
2811 {
2812 timeout -= GetTickCount() - timeout_start;
2813 if (timeout < 0) timeout = 0;
2814 }
2815
2816 pfd.fd = fd;
2817 pfd.events = POLLOUT;
2818
2819 if (!timeout || !poll( &pfd, 1, timeout ))
2820 {
2821 err = WSAETIMEDOUT;
2822 goto error; /* msdn says a timeout in send is fatal */
2823 }
2824
2825 n = WS2_send( fd, iovec + first_buff, dwBufferCount - first_buff, to, tolen, dwFlags );
2826 if (n == -1 && errno != EAGAIN && errno != EINTR)
2827 {
2828 err = wsaErrno();
2829 goto error;
2830 }
2831 }
2832 }
2833 else /* non-blocking */
2834 {
2835 if (n < totalLength)
2836 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
2837 if (n == -1)
2838 {
2839 err = WSAEWOULDBLOCK;
2840 goto error;
2841 }
2842 *lpNumberOfBytesSent = n;
2843 }
2844
2845 TRACE(" -> %i bytes\n", *lpNumberOfBytesSent);
2846
2847 release_sock_fd( s, fd );
2848 WSASetLastError(0);
2849 return 0;
2850
2851 error:
2852 release_sock_fd( s, fd );
2853 WARN(" -> ERROR %d\n", err);
2854 WSASetLastError(err);
2855 return SOCKET_ERROR;
2856 }
2857
2858 /***********************************************************************
2859 * sendto (WS2_32.20)
2860 */
2861 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
2862 const struct WS_sockaddr *to, int tolen)
2863 {
2864 DWORD n;
2865 WSABUF wsabuf;
2866
2867 wsabuf.len = len;
2868 wsabuf.buf = (char*) buf;
2869
2870 if ( WSASendTo(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
2871 return SOCKET_ERROR;
2872 else
2873 return n;
2874 }
2875
2876 /***********************************************************************
2877 * setsockopt (WS2_32.21)
2878 */
2879 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
2880 const char *optval, int optlen)
2881 {
2882 int fd;
2883 int woptval;
2884 struct linger linger;
2885 struct timeval tval;
2886
2887 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
2888 s, level, optname, optval, optlen);
2889
2890 /* some broken apps pass the value directly instead of a pointer to it */
2891 if(IS_INTRESOURCE(optval))
2892 {
2893 SetLastError(WSAEFAULT);
2894 return SOCKET_ERROR;
2895 }
2896
2897 switch(level)
2898 {
2899 case WS_SOL_SOCKET:
2900 switch(optname)
2901 {
2902 /* Some options need some conversion before they can be sent to
2903 * setsockopt. The conversions are done here, then they will fall though
2904 * to the general case. Special options that are not passed to
2905 * setsockopt follow below that.*/
2906
2907 case WS_SO_DONTLINGER:
2908 linger.l_onoff = *((const int*)optval) ? 0: 1;
2909 linger.l_linger = 0;
2910 level = SOL_SOCKET;
2911 optname = SO_LINGER;
2912 optval = (char*)&linger;
2913 optlen = sizeof(struct linger);
2914 break;
2915
2916 case WS_SO_LINGER:
2917 linger.l_onoff = ((LINGER*)optval)->l_onoff;
2918 linger.l_linger = ((LINGER*)optval)->l_linger;
2919 /* FIXME: what is documented behavior if SO_LINGER optval
2920 is null?? */
2921 level = SOL_SOCKET;
2922 optname = SO_LINGER;
2923 optval = (char*)&linger;
2924 optlen = sizeof(struct linger);
2925 break;
2926
2927 case WS_SO_RCVBUF:
2928 if (*(const int*)optval < 2048)
2929 {
2930 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
2931 return 0;
2932 }
2933 /* Fall through */
2934
2935 /* The options listed here don't need any special handling. Thanks to
2936 * the conversion happening above, options from there will fall through
2937 * to this, too.*/
2938 case WS_SO_ACCEPTCONN:
2939 case WS_SO_BROADCAST:
2940 case WS_SO_ERROR:
2941 case WS_SO_KEEPALIVE:
2942 case WS_SO_OOBINLINE:
2943 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
2944 * however, using it the BSD way fixes bug 8513 and seems to be what
2945 * most programmers assume, anyway */
2946 case WS_SO_REUSEADDR:
2947 case WS_SO_SNDBUF:
2948 case WS_SO_TYPE:
2949 convert_sockopt(&level, &optname);
2950 break;
2951
2952 /* SO_DEBUG is a privileged operation, ignore it. */
2953 case WS_SO_DEBUG:
2954 TRACE("Ignoring SO_DEBUG\n");
2955 return 0;
2956
2957 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
2958 * socket. According to MSDN, this option is silently ignored.*/
2959 case WS_SO_DONTROUTE:
2960 TRACE("Ignoring SO_DONTROUTE\n");
2961 return 0;
2962
2963 /* Stops two sockets from being bound to the same port. Always happens
2964 * on unix systems, so just drop it. */
2965 case WS_SO_EXCLUSIVEADDRUSE:
2966 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
2967 return 0;
2968
2969 /* SO_OPENTYPE does not require a valid socket handle. */
2970 case WS_SO_OPENTYPE:
2971 if (!optlen || optlen < sizeof(int) || !optval)
2972 {
2973 SetLastError(WSAEFAULT);
2974 return SOCKET_ERROR;
2975 }
2976 get_per_thread_data()->opentype = *(const int *)optval;
2977 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
2978 return 0;
2979
2980 #ifdef SO_RCVTIMEO
2981 case WS_SO_RCVTIMEO:
2982 #endif
2983 #ifdef SO_SNDTIMEO
2984 case WS_SO_SNDTIMEO:
2985 #endif
2986 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
2987 if (optval && optlen == sizeof(UINT32)) {
2988 /* WinSock passes milliseconds instead of struct timeval */
2989 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
2990 tval.tv_sec = *(const UINT32*)optval / 1000;
2991 /* min of 500 milliseconds */
2992 if (tval.tv_sec == 0 && tval.tv_usec < 500000)
2993 tval.tv_usec = 500000;
2994 optlen = sizeof(struct timeval);
2995 optval = (char*)&tval;
2996 } else if (optlen == sizeof(struct timeval)) {
2997 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
2998 } else {
2999 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
3000 return 0;
3001 }
3002 convert_sockopt(&level, &optname);
3003 break;
3004 #endif
3005
3006 default:
3007 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
3008 SetLastError(WSAENOPROTOOPT);
3009 return SOCKET_ERROR;
3010 }
3011 break; /* case WS_SOL_SOCKET */
3012
3013 #ifdef HAVE_IPX
3014 case NSPROTO_IPX:
3015 switch(optname)
3016 {
3017 case IPX_PTYPE:
3018 fd = get_sock_fd( s, 0, NULL );
3019 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", *(const int*)optval, fd);
3020
3021 /* We try to set the ipx type on ipx socket level. */
3022 #ifdef SOL_IPX
3023 if(setsockopt(fd, SOL_IPX, IPX_TYPE, optval, optlen) == -1)
3024 {
3025 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
3026 release_sock_fd( s, fd );
3027 return SOCKET_ERROR;
3028 }
3029 #else
3030 {
3031 struct ipx val;
3032 /* Should we retrieve val using a getsockopt call and then
3033 * set the modified one? */
3034 val.ipx_pt = *optval;
3035 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
3036 }
3037 #endif
3038 release_sock_fd( s, fd );
3039 return 0;
3040
3041 case IPX_FILTERPTYPE:
3042 /* Sets the receive filter packet type, at the moment we don't support it */
3043 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
3044 /* Returning 0 is better for now than returning a SOCKET_ERROR */
3045 return 0;
3046
3047 default:
3048 FIXME("opt_name:%x\n", optname);
3049 return SOCKET_ERROR;
3050 }
3051 break; /* case NSPROTO_IPX */
3052 #endif
3053
3054 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3055 case WS_IPPROTO_TCP:
3056 switch(optname)
3057 {
3058 case WS_TCP_NODELAY:
3059 convert_sockopt(&level, &optname);
3060 break;
3061 default:
3062 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3063 return SOCKET_ERROR;
3064 }
3065 break;
3066
3067 case WS_IPPROTO_IP:
3068 switch(optname)
3069 {
3070 case WS_IP_ADD_MEMBERSHIP:
3071 case WS_IP_DROP_MEMBERSHIP:
3072 #ifdef IP_HDRINCL
3073 case WS_IP_HDRINCL:
3074 #endif
3075 case WS_IP_MULTICAST_IF:
3076 case WS_IP_MULTICAST_LOOP:
3077 case WS_IP_MULTICAST_TTL:
3078 case WS_IP_OPTIONS:
3079 case WS_IP_TOS:
3080 case WS_IP_TTL:
3081 convert_sockopt(&level, &optname);
3082 break;
3083 case WS_IP_DONTFRAGMENT:
3084 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
3085 return 0;
3086 default:
3087 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3088 return SOCKET_ERROR;
3089 }
3090 break;
3091
3092 default:
3093 FIXME("Unknown level: 0x%08x\n", level);
3094 return SOCKET_ERROR;
3095 } /* end switch(level) */
3096
3097 /* avoid endianness issues if argument is a 16-bit int */
3098 if (optval && optlen < sizeof(int))
3099 {
3100 woptval= *((const INT16 *) optval);
3101 optval= (char*) &woptval;
3102 optlen=sizeof(int);
3103 }
3104 fd = get_sock_fd( s, 0, NULL );
3105 if (fd == -1) return SOCKET_ERROR;
3106
3107 if (setsockopt(fd, level, optname, optval, optlen) == 0)
3108 {
3109 release_sock_fd( s, fd );
3110 return 0;
3111 }
3112 TRACE("Setting socket error, %d\n", wsaErrno());
3113 SetLastError(wsaErrno());
3114 release_sock_fd( s, fd );
3115
3116 return SOCKET_ERROR;
3117 }
3118
3119 /***********************************************************************
3120 * shutdown (WS2_32.22)
3121 */
3122 int WINAPI WS_shutdown(SOCKET s, int how)
3123 {
3124 int fd, err = WSAENOTSOCK;
3125 unsigned int options, clear_flags = 0;
3126
3127 fd = get_sock_fd( s, 0, &options );
3128 TRACE("socket %04lx, how %i %x\n", s, how, options );
3129
3130 if (fd == -1)
3131 return SOCKET_ERROR;
3132
3133 switch( how )
3134 {
3135 case 0: /* drop receives */
3136 clear_flags |= FD_READ;
3137 break;
3138 case 1: /* drop sends */
3139 clear_flags |= FD_WRITE;
3140 break;
3141 case 2: /* drop all */
3142 clear_flags |= FD_READ|FD_WRITE;
3143 default:
3144 clear_flags |= FD_WINE_LISTENING;
3145 }
3146
3147 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
3148 {
3149 switch ( how )
3150 {
3151 case SD_RECEIVE:
3152 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3153 break;
3154 case SD_SEND:
3155 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3156 break;
3157 case SD_BOTH:
3158 default:
3159 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3160 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3161 break;
3162 }
3163 if (err) goto error;
3164 }
3165 else /* non-overlapped mode */
3166 {
3167 if ( shutdown( fd, how ) )
3168 {
3169 err = wsaErrno();
3170 goto error;
3171 }
3172 }
3173
3174 release_sock_fd( s, fd );
3175 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3176 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
3177 return 0;
3178
3179 error:
3180 release_sock_fd( s, fd );
3181 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3182 WSASetLastError( err );
3183 return SOCKET_ERROR;
3184 }
3185
3186 /***********************************************************************
3187 * socket (WS2_32.23)
3188 */
3189 SOCKET WINAPI WS_socket(int af, int type, int protocol)
3190 {
3191 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
3192
3193 return WSASocketA( af, type, protocol, NULL, 0,
3194 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
3195 }
3196
3197
3198 /***********************************************************************
3199 * gethostbyaddr (WS2_32.51)
3200 */
3201 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
3202 {
3203 struct WS_hostent *retval = NULL;
3204 struct hostent* host;
3205
3206 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3207 char *extrabuf;
3208 int ebufsize=1024;
3209 struct hostent hostentry;
3210 int locerr=ENOBUFS;
3211 host = NULL;
3212 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3213 while(extrabuf) {
3214 int res = gethostbyaddr_r(addr, len, type,
3215 &hostentry, extrabuf, ebufsize, &host, &locerr);
3216 if( res != ERANGE) break;
3217 ebufsize *=2;
3218 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3219 }
3220 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3221 #else
3222 EnterCriticalSection( &csWSgetXXXbyYYY );
3223 host = gethostbyaddr(addr, len, type);
3224 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3225 #endif
3226 if( host != NULL ) retval = WS_dup_he(host);
3227 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3228 HeapFree(GetProcessHeap(),0,extrabuf);
3229 #else
3230 LeaveCriticalSection( &csWSgetXXXbyYYY );
3231 #endif
3232 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
3233 return retval;
3234 }
3235
3236 /***********************************************************************
3237 * gethostbyname (WS2_32.52)
3238 */
3239 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
3240 {
3241 struct WS_hostent *retval = NULL;
3242 struct hostent* host;
3243 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3244 char *extrabuf;
3245 int ebufsize=1024;
3246 struct hostent hostentry;
3247 int locerr = ENOBUFS;
3248 #endif
3249 char buf[100];
3250 if( !name || !name[0]) {
3251 name = buf;
3252 if( gethostname( buf, 100) == -1) {
3253 SetLastError( WSAENOBUFS); /* appropriate ? */
3254 return retval;
3255 }
3256 }
3257 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3258 host = NULL;
3259 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3260 while(extrabuf) {
3261 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
3262 if( res != ERANGE) break;
3263 ebufsize *=2;
3264 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3265 }
3266 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3267 #else
3268 EnterCriticalSection( &csWSgetXXXbyYYY );
3269 host = gethostbyname(name);
3270 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3271 #endif
3272 if (host) retval = WS_dup_he(host);
3273 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3274 HeapFree(GetProcessHeap(),0,extrabuf);
3275 #else
3276 LeaveCriticalSection( &csWSgetXXXbyYYY );
3277 #endif
3278 if (retval && retval->h_addr_list[0][0] == 127 &&
3279 strcmp(name, "localhost") != 0)
3280 {
3281 /* hostname != "localhost" but has loopback address. replace by our
3282 * special address.*/
3283 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
3284 }
3285 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3286 return retval;
3287 }
3288
3289
3290 /***********************************************************************
3291 * getprotobyname (WS2_32.53)
3292 */
3293 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
3294 {
3295 struct WS_protoent* retval = NULL;
3296 #ifdef HAVE_GETPROTOBYNAME
3297 struct protoent* proto;
3298 EnterCriticalSection( &csWSgetXXXbyYYY );
3299 if( (proto = getprotobyname(name)) != NULL )
3300 {
3301 retval = WS_dup_pe(proto);
3302 }
3303 else {
3304 MESSAGE("protocol %s not found; You might want to add "
3305 "this to /etc/protocols\n", debugstr_a(name) );
3306 SetLastError(WSANO_DATA);
3307 }
3308 LeaveCriticalSection( &csWSgetXXXbyYYY );
3309 #endif
3310 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3311 return retval;
3312 }
3313
3314
3315 /***********************************************************************
3316 * getprotobynumber (WS2_32.54)
3317 */
3318 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
3319 {
3320 struct WS_protoent* retval = NULL;
3321 #ifdef HAVE_GETPROTOBYNUMBER
3322 struct protoent* proto;
3323 EnterCriticalSection( &csWSgetXXXbyYYY );
3324 if( (proto = getprotobynumber(number)) != NULL )
3325 {
3326 retval = WS_dup_pe(proto);
3327 }
3328 else {
3329 MESSAGE("protocol number %d not found; You might want to add "
3330 "this to /etc/protocols\n", number );
3331 SetLastError(WSANO_DATA);
3332 }
3333 LeaveCriticalSection( &csWSgetXXXbyYYY );
3334 #endif
3335 TRACE("%i ret %p\n", number, retval);
3336 return retval;
3337 }
3338
3339
3340 /***********************************************************************
3341 * getservbyname (WS2_32.55)
3342 */
3343 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
3344 {
3345 struct WS_servent* retval = NULL;
3346 struct servent* serv;
3347 char *name_str;
3348 char *proto_str = NULL;
3349
3350 if (!(name_str = strdup_lower(name))) return NULL;
3351
3352 if (proto && *proto)
3353 {
3354 if (!(proto_str = strdup_lower(proto)))
3355 {
3356 HeapFree( GetProcessHeap(), 0, name_str );
3357 return NULL;
3358 }
3359 }
3360
3361 EnterCriticalSection( &csWSgetXXXbyYYY );
3362 serv = getservbyname(name_str, proto_str);
3363 if( serv != NULL )
3364 {
3365 retval = WS_dup_se(serv);
3366 }
3367 else SetLastError(WSANO_DATA);
3368 LeaveCriticalSection( &csWSgetXXXbyYYY );
3369 HeapFree( GetProcessHeap(), 0, proto_str );
3370 HeapFree( GetProcessHeap(), 0, name_str );
3371 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
3372 return retval;
3373 }
3374
3375 /***********************************************************************
3376 * freeaddrinfo (WS2_32.@)
3377 */
3378 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
3379 {
3380 while (res) {
3381 struct WS_addrinfo *next;
3382
3383 HeapFree(GetProcessHeap(),0,res->ai_canonname);
3384 HeapFree(GetProcessHeap(),0,res->ai_addr);
3385 next = res->ai_next;
3386 HeapFree(GetProcessHeap(),0,res);
3387 res = next;
3388 }
3389 }
3390
3391 /* helper functions for getaddrinfo()/getnameinfo() */
3392 static int convert_aiflag_w2u(int winflags) {
3393 int i, unixflags = 0;
3394
3395 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3396 if (ws_aiflag_map[i][0] & winflags) {
3397 unixflags |= ws_aiflag_map[i][1];
3398 winflags &= ~ws_aiflag_map[i][0];
3399 }
3400 if (winflags)
3401 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
3402 return unixflags;
3403 }
3404
3405 static int convert_niflag_w2u(int winflags) {
3406 int i, unixflags = 0;
3407
3408 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
3409 if (ws_niflag_map[i][0] & winflags) {
3410 unixflags |= ws_niflag_map[i][1];
3411 winflags &= ~ws_niflag_map[i][0];
3412 }
3413 if (winflags)
3414 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
3415 return unixflags;
3416 }
3417
3418 static int convert_aiflag_u2w(int unixflags) {
3419 int i, winflags = 0;
3420
3421 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3422 if (ws_aiflag_map[i][1] & unixflags) {
3423 winflags |= ws_aiflag_map[i][0];
3424 unixflags &= ~ws_aiflag_map[i][1];
3425 }
3426 if (unixflags) /* will warn usually */
3427 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
3428 return winflags;
3429 }
3430
3431 static int convert_eai_u2w(int unixret) {
3432 int i;
3433
3434 for (i=0;ws_eai_map[i][0];i++)
3435 if (ws_eai_map[i][1] == unixret)
3436 return ws_eai_map[i][0];
3437 return unixret;
3438 }
3439
3440 /***********************************************************************
3441 * getaddrinfo (WS2_32.@)
3442 */
3443 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
3444 {
3445 #ifdef HAVE_GETADDRINFO
3446 struct addrinfo *unixaires = NULL;
3447 int result;
3448 struct addrinfo unixhints, *punixhints = NULL;
3449 CHAR *node = NULL, *serv = NULL;
3450
3451 if (nodename)
3452 if (!(node = strdup_lower(nodename))) return WSA_NOT_ENOUGH_MEMORY;
3453
3454 if (servname) {
3455 if (!(serv = strdup_lower(servname))) {
3456 HeapFree(GetProcessHeap(), 0, node);
3457 return WSA_NOT_ENOUGH_MEMORY;
3458 }
3459 }
3460
3461 if (hints) {
3462 punixhints = &unixhints;
3463
3464 memset(&unixhints, 0, sizeof(unixhints));
3465 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
3466 if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
3467 punixhints->ai_family = 0;
3468 else
3469 punixhints->ai_family = convert_af_w2u(hints->ai_family);
3470 if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
3471 punixhints->ai_socktype = 0;
3472 else
3473 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
3474 if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
3475 punixhints->ai_protocol = 0;
3476 else
3477 punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
3478 }
3479
3480 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
3481 result = getaddrinfo(nodename, servname, punixhints, &unixaires);
3482
3483 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
3484
3485 HeapFree(GetProcessHeap(), 0, node);
3486 HeapFree(GetProcessHeap(), 0, serv);
3487
3488 if (!result) {
3489 struct addrinfo *xuai = unixaires;
3490 struct WS_addrinfo **xai = res;
3491
3492 *xai = NULL;
3493 while (xuai) {
3494 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
3495 int len;
3496
3497 if (!ai)
3498 goto outofmem;
3499
3500 *xai = ai;xai = &ai->ai_next;
3501 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
3502 ai->ai_family = convert_af_u2w(xuai->ai_family);
3503 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
3504 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
3505 if (xuai->ai_canonname) {
3506 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
3507 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
3508 if (!ai->ai_canonname)
3509 goto outofmem;
3510 strcpy(ai->ai_canonname,xuai->ai_canonname);
3511 }
3512 len = xuai->ai_addrlen;
3513 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
3514 if (!ai->ai_addr)
3515 goto outofmem;
3516 ai->ai_addrlen = len;
3517 do {
3518 int winlen = ai->ai_addrlen;
3519
3520 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
3521 ai->ai_addrlen = winlen;
3522 break;
3523 }
3524 len = 2*len;
3525 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
3526 if (!ai->ai_addr)
3527 goto outofmem;
3528 ai->ai_addrlen = len;
3529 } while (1);
3530 xuai = xuai->ai_next;
3531 }
3532 freeaddrinfo(unixaires);
3533 } else {
3534 result = convert_eai_u2w(result);
3535 *res = NULL;
3536 }
3537 return result;
3538
3539 outofmem:
3540 if (*res) WS_freeaddrinfo(*res);
3541 if (unixaires) freeaddrinfo(unixaires);
3542 *res = NULL;
3543 return WSA_NOT_ENOUGH_MEMORY;
3544 #else
3545 FIXME("getaddrinfo() failed, not found during buildtime.\n");
3546 return EAI_FAIL;
3547 #endif
3548 }
3549
3550 /***********************************************************************
3551 * GetAddrInfoW (WS2_32.@)
3552 */
3553 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
3554 {
3555 FIXME("empty stub!\n");
3556 return EAI_FAIL;
3557 }
3558
3559 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
3560 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
3561 {
3562 #ifdef HAVE_GETNAMEINFO
3563 int ret;
3564 union generic_unix_sockaddr sa_u;
3565 unsigned int size;
3566
3567 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
3568 serv, servlen, flags);
3569
3570 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
3571 if (!size)
3572 {
3573 WSASetLastError(WSAEFAULT);
3574 return WSA_NOT_ENOUGH_MEMORY;
3575 }
3576 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
3577 return convert_eai_u2w(ret);
3578 #else
3579 FIXME("getnameinfo() failed, not found during buildtime.\n");
3580 return EAI_FAIL;
3581 #endif
3582 }
3583
3584 /***********************************************************************
3585 * getservbyport (WS2_32.56)
3586 */
3587 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
3588 {
3589 struct WS_servent* retval = NULL;
3590 #ifdef HAVE_GETSERVBYPORT
3591 struct servent* serv;
3592 char *proto_str = NULL;
3593
3594 if (proto && *proto)
3595 {
3596 if (!(proto_str = strdup_lower(proto))) return NULL;
3597 }
3598 EnterCriticalSection( &csWSgetXXXbyYYY );
3599 if( (serv = getservbyport(port, proto_str)) != NULL ) {
3600 retval = WS_dup_se(serv);
3601 }
3602 else SetLastError(WSANO_DATA);
3603 LeaveCriticalSection( &csWSgetXXXbyYYY );
3604 HeapFree( GetProcessHeap(), 0, proto_str );
3605 #endif
3606 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
3607 return retval;
3608 }
3609
3610
3611 /***********************************************************************
3612 * gethostname (WS2_32.57)
3613 */
3614 int WINAPI WS_gethostname(char *name, int namelen)
3615 {
3616 TRACE("name %p, len %d\n", name, namelen);
3617
3618 if (gethostname(name, namelen) == 0)
3619 {
3620 TRACE("<- '%s'\n", name);
3621 return 0;
3622 }
3623 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
3624 TRACE("<- ERROR !\n");
3625 return SOCKET_ERROR;
3626 }
3627
3628
3629 /* ------------------------------------- Windows sockets extensions -- *
3630 * *
3631 * ------------------------------------------------------------------- */
3632
3633 /***********************************************************************
3634 * WSAEnumNetworkEvents (WS2_32.36)
3635 */
3636 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
3637 {
3638 int ret;
3639
3640 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
3641
3642 SERVER_START_REQ( get_socket_event )
3643 {
3644 req->handle = SOCKET2HANDLE(s);
3645 req->service = TRUE;
3646 req->c_event = hEvent;
3647 wine_server_set_reply( req, lpEvent->iErrorCode, sizeof(lpEvent->iErrorCode) );
3648 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
3649 }
3650 SERVER_END_REQ;
3651 if (!ret) return 0;
3652 SetLastError(WSAEINVAL);
3653 return SOCKET_ERROR;
3654 }