server: Consume events triggered.
[wine/hramrach.git] / dlls / ws2_32 / socket.c
blob2597c8d0d298e26f3e1790954cf0db209f7a471e
1 /*
2 * based on Windows Sockets 1.1 specs
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
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.
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.
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
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).
27 #include "config.h"
28 #include "wine/port.h"
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
47 #if defined(__EMX__)
48 # include <sys/so_ioctl.h>
49 #endif
51 #ifdef HAVE_SYS_PARAM_H
52 # include <sys/param.h>
53 #endif
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
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 # ifdef HAVE_LINUX_TYPES_H
107 # include <linux/types.h>
108 # endif
109 # include <linux/ipx.h>
110 # define HAVE_IPX
111 #endif
113 #ifdef HAVE_LINUX_IRDA_H
114 # ifdef HAVE_LINUX_TYPES_H
115 # include <linux/types.h>
116 # endif
117 # include <linux/irda.h>
118 # define HAVE_IRDA
119 #endif
121 #ifdef HAVE_POLL_H
122 #include <poll.h>
123 #endif
124 #ifdef HAVE_SYS_POLL_H
125 # include <sys/poll.h>
126 #endif
127 #ifdef HAVE_SYS_TIME_H
128 # include <sys/time.h>
129 #endif
131 #define NONAMELESSUNION
132 #define NONAMELESSSTRUCT
133 #include "ntstatus.h"
134 #define WIN32_NO_STATUS
135 #include "windef.h"
136 #include "winbase.h"
137 #include "wingdi.h"
138 #include "winuser.h"
139 #include "winerror.h"
140 #include "winnls.h"
141 #include "winsock2.h"
142 #include "mswsock.h"
143 #include "ws2tcpip.h"
144 #include "ws2spi.h"
145 #include "wsipx.h"
146 #include "mstcpip.h"
147 #include "af_irda.h"
148 #include "winnt.h"
149 #include "iphlpapi.h"
150 #include "wine/server.h"
151 #include "wine/debug.h"
152 #include "wine/exception.h"
153 #include "wine/unicode.h"
155 #ifdef HAVE_IPX
156 # include "wsnwlink.h"
157 #endif
160 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
161 # define sipx_network sipx_addr.x_net
162 # define sipx_node sipx_addr.x_host.c_host
163 #endif /* __FreeBSD__ */
165 #ifndef INADDR_NONE
166 #define INADDR_NONE ~0UL
167 #endif
169 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
170 WINE_DECLARE_DEBUG_CHANNEL(winediag);
174 * The actual definition of WSASendTo/WSARecvFrom, wrapped in a different
175 * function name, so that internal calls from ws2_32 itself will not trigger
176 * programs like Garena, which hooks WSASendTo/WSARecvFrom calls.
178 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
179 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
180 const struct WS_sockaddr *to, int tolen,
181 LPWSAOVERLAPPED lpOverlapped,
182 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine );
184 static int WS2_recvfrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
185 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
186 struct WS_sockaddr *lpFrom,
187 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
188 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine );
190 /* critical section to protect some non-reentrant net function */
191 static CRITICAL_SECTION csWSgetXXXbyYYY;
192 static CRITICAL_SECTION_DEBUG critsect_debug =
194 0, 0, &csWSgetXXXbyYYY,
195 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
196 0, 0, { (DWORD_PTR)(__FILE__ ": csWSgetXXXbyYYY") }
198 static CRITICAL_SECTION csWSgetXXXbyYYY = { &critsect_debug, -1, 0, 0, 0, 0 };
200 union generic_unix_sockaddr
202 struct sockaddr addr;
203 char data[128]; /* should be big enough for all families */
206 static inline const char *debugstr_sockaddr( const struct WS_sockaddr *a )
208 if (!a) return "(nil)";
209 switch (a->sa_family)
211 case WS_AF_INET:
212 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
213 inet_ntoa(((const struct sockaddr_in *)a)->sin_addr),
214 ntohs(((const struct sockaddr_in *)a)->sin_port));
215 case WS_AF_INET6:
217 char buf[46];
218 const char *p;
219 struct WS_sockaddr_in6 *sin = (struct WS_sockaddr_in6 *)a;
221 p = WS_inet_ntop( WS_AF_INET6, &sin->sin6_addr, buf, sizeof(buf) );
222 if (!p)
223 p = "(unknown IPv6 address)";
224 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
225 p, ntohs(sin->sin6_port));
227 case WS_AF_IRDA:
229 DWORD addr;
231 memcpy( &addr, ((const SOCKADDR_IRDA *)a)->irdaDeviceID, sizeof(addr) );
232 addr = ntohl( addr );
233 return wine_dbg_sprintf("{ family AF_IRDA, addr %08x, name %s }",
234 addr,
235 ((const SOCKADDR_IRDA *)a)->irdaServiceName);
237 default:
238 return wine_dbg_sprintf("{ family %d }", a->sa_family);
242 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
243 #define SOCKET2HANDLE(s) ((HANDLE)(s))
244 #define HANDLE2SOCKET(h) ((SOCKET)(h))
246 /****************************************************************
247 * Async IO declarations
248 ****************************************************************/
250 typedef struct ws2_async
252 HANDLE hSocket;
253 int type;
254 LPWSAOVERLAPPED user_overlapped;
255 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
256 IO_STATUS_BLOCK local_iosb;
257 struct WS_sockaddr *addr;
258 union
260 int val; /* for send operations */
261 int *ptr; /* for recv operations */
262 } addrlen;
263 DWORD flags;
264 unsigned int n_iovecs;
265 unsigned int first_iovec;
266 struct iovec iovec[1];
267 } ws2_async;
269 /****************************************************************/
271 /* ----------------------------------- internal data */
273 /* ws_... struct conversion flags */
275 typedef struct /* WSAAsyncSelect() control struct */
277 HANDLE service, event, sock;
278 HWND hWnd;
279 UINT uMsg;
280 LONG lEvent;
281 } ws_select_info;
283 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
284 #define WS_MAX_UDP_DATAGRAM 1024
285 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
287 /* hostent's, servent's and protent's are stored in one buffer per thread,
288 * as documented on MSDN for the functions that return any of the buffers */
289 struct per_thread_data
291 int opentype;
292 struct WS_hostent *he_buffer;
293 struct WS_servent *se_buffer;
294 struct WS_protoent *pe_buffer;
295 int he_len;
296 int se_len;
297 int pe_len;
300 /* internal: routing description information */
301 struct route {
302 struct in_addr addr;
303 DWORD interface;
304 DWORD metric;
307 static INT num_startup; /* reference counter */
308 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
310 /* function prototypes */
311 static struct WS_hostent *WS_create_he(char *name, int aliases, int addresses, int fill_addresses);
312 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
313 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
314 static struct WS_servent *WS_dup_se(const struct servent* p_se);
316 int WSAIOCTL_GetInterfaceCount(void);
317 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
319 #define MAP_OPTION(opt) { WS_##opt, opt }
321 static const int ws_sock_map[][2] =
323 MAP_OPTION( SO_DEBUG ),
324 MAP_OPTION( SO_ACCEPTCONN ),
325 MAP_OPTION( SO_REUSEADDR ),
326 MAP_OPTION( SO_KEEPALIVE ),
327 MAP_OPTION( SO_DONTROUTE ),
328 MAP_OPTION( SO_BROADCAST ),
329 MAP_OPTION( SO_LINGER ),
330 MAP_OPTION( SO_OOBINLINE ),
331 MAP_OPTION( SO_SNDBUF ),
332 MAP_OPTION( SO_RCVBUF ),
333 MAP_OPTION( SO_ERROR ),
334 MAP_OPTION( SO_TYPE ),
335 #ifdef SO_RCVTIMEO
336 MAP_OPTION( SO_RCVTIMEO ),
337 #endif
338 #ifdef SO_SNDTIMEO
339 MAP_OPTION( SO_SNDTIMEO ),
340 #endif
343 static const int ws_tcp_map[][2] =
345 #ifdef TCP_NODELAY
346 MAP_OPTION( TCP_NODELAY ),
347 #endif
350 static const int ws_ip_map[][2] =
352 MAP_OPTION( IP_MULTICAST_IF ),
353 MAP_OPTION( IP_MULTICAST_TTL ),
354 MAP_OPTION( IP_MULTICAST_LOOP ),
355 MAP_OPTION( IP_ADD_MEMBERSHIP ),
356 MAP_OPTION( IP_DROP_MEMBERSHIP ),
357 MAP_OPTION( IP_OPTIONS ),
358 #ifdef IP_HDRINCL
359 MAP_OPTION( IP_HDRINCL ),
360 #endif
361 MAP_OPTION( IP_TOS ),
362 MAP_OPTION( IP_TTL ),
365 static const int ws_ipv6_map[][2] =
367 #ifdef IPV6_ADD_MEMBERSHIP
368 MAP_OPTION( IPV6_ADD_MEMBERSHIP ),
369 #endif
370 #ifdef IPV6_DROP_MEMBERSHIP
371 MAP_OPTION( IPV6_DROP_MEMBERSHIP ),
372 #endif
373 MAP_OPTION( IPV6_MULTICAST_IF ),
374 MAP_OPTION( IPV6_MULTICAST_HOPS ),
375 MAP_OPTION( IPV6_MULTICAST_LOOP ),
376 MAP_OPTION( IPV6_UNICAST_HOPS ),
377 MAP_OPTION( IPV6_V6ONLY ),
380 static const int ws_af_map[][2] =
382 MAP_OPTION( AF_UNSPEC ),
383 MAP_OPTION( AF_INET ),
384 MAP_OPTION( AF_INET6 ),
385 #ifdef HAVE_IPX
386 MAP_OPTION( AF_IPX ),
387 #endif
388 #ifdef AF_IRDA
389 MAP_OPTION( AF_IRDA ),
390 #endif
391 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
394 static const int ws_socktype_map[][2] =
396 MAP_OPTION( SOCK_DGRAM ),
397 MAP_OPTION( SOCK_STREAM ),
398 MAP_OPTION( SOCK_RAW ),
399 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
402 static const int ws_proto_map[][2] =
404 MAP_OPTION( IPPROTO_IP ),
405 MAP_OPTION( IPPROTO_TCP ),
406 MAP_OPTION( IPPROTO_UDP ),
407 MAP_OPTION( IPPROTO_ICMP ),
408 MAP_OPTION( IPPROTO_IGMP ),
409 MAP_OPTION( IPPROTO_RAW ),
410 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
413 static const int ws_aiflag_map[][2] =
415 MAP_OPTION( AI_PASSIVE ),
416 MAP_OPTION( AI_CANONNAME ),
417 MAP_OPTION( AI_NUMERICHOST ),
418 /* Linux/UNIX knows a lot more. But Windows only
419 * has 3 as far as I could see. -Marcus
423 static const int ws_niflag_map[][2] =
425 MAP_OPTION( NI_NOFQDN ),
426 MAP_OPTION( NI_NUMERICHOST ),
427 MAP_OPTION( NI_NAMEREQD ),
428 MAP_OPTION( NI_NUMERICSERV ),
429 MAP_OPTION( NI_DGRAM ),
432 static const int ws_eai_map[][2] =
434 MAP_OPTION( EAI_AGAIN ),
435 MAP_OPTION( EAI_BADFLAGS ),
436 MAP_OPTION( EAI_FAIL ),
437 MAP_OPTION( EAI_FAMILY ),
438 MAP_OPTION( EAI_MEMORY ),
439 /* Note: EAI_NODATA is deprecated, but still
440 * used by Windows and Linux... We map the newer
441 * EAI_NONAME to EAI_NODATA for now until Windows
442 * changes too.
444 #ifdef EAI_NODATA
445 MAP_OPTION( EAI_NODATA ),
446 #endif
447 #ifdef EAI_NONAME
448 { WS_EAI_NODATA, EAI_NONAME },
449 #endif
451 MAP_OPTION( EAI_SERVICE ),
452 MAP_OPTION( EAI_SOCKTYPE ),
453 { 0, 0 }
456 static const char magic_loopback_addr[] = {127, 12, 34, 56};
458 /* ----------------------------------- error handling */
460 static NTSTATUS sock_get_ntstatus( int err )
462 switch ( err )
464 case EBADF: return STATUS_INVALID_HANDLE;
465 case EBUSY: return STATUS_DEVICE_BUSY;
466 case EPERM:
467 case EACCES: return STATUS_ACCESS_DENIED;
468 case EFAULT: return STATUS_NO_MEMORY;
469 case EINVAL: return STATUS_INVALID_PARAMETER;
470 case ENFILE:
471 case EMFILE: return STATUS_TOO_MANY_OPENED_FILES;
472 case EWOULDBLOCK: return STATUS_CANT_WAIT;
473 case EINPROGRESS: return STATUS_PENDING;
474 case EALREADY: return STATUS_NETWORK_BUSY;
475 case ENOTSOCK: return STATUS_OBJECT_TYPE_MISMATCH;
476 case EDESTADDRREQ: return STATUS_INVALID_PARAMETER;
477 case EMSGSIZE: return STATUS_BUFFER_OVERFLOW;
478 case EPROTONOSUPPORT:
479 case ESOCKTNOSUPPORT:
480 case EPFNOSUPPORT:
481 case EAFNOSUPPORT:
482 case EPROTOTYPE: return STATUS_NOT_SUPPORTED;
483 case ENOPROTOOPT: return STATUS_INVALID_PARAMETER;
484 case EOPNOTSUPP: return STATUS_NOT_SUPPORTED;
485 case EADDRINUSE: return STATUS_ADDRESS_ALREADY_ASSOCIATED;
486 case EADDRNOTAVAIL: return STATUS_INVALID_PARAMETER;
487 case ECONNREFUSED: return STATUS_CONNECTION_REFUSED;
488 case ESHUTDOWN: return STATUS_PIPE_DISCONNECTED;
489 case ENOTCONN: return STATUS_CONNECTION_DISCONNECTED;
490 case ETIMEDOUT: return STATUS_IO_TIMEOUT;
491 case ENETUNREACH: return STATUS_NETWORK_UNREACHABLE;
492 case ENETDOWN: return STATUS_NETWORK_BUSY;
493 case EPIPE:
494 case ECONNRESET: return STATUS_CONNECTION_RESET;
495 case ECONNABORTED: return STATUS_CONNECTION_ABORTED;
497 case 0: return STATUS_SUCCESS;
498 default:
499 WARN("Unknown errno %d!\n", err);
500 return STATUS_UNSUCCESSFUL;
504 static UINT sock_get_error( int err )
506 switch(err)
508 case EINTR: return WSAEINTR;
509 case EBADF: return WSAEBADF;
510 case EPERM:
511 case EACCES: return WSAEACCES;
512 case EFAULT: return WSAEFAULT;
513 case EINVAL: return WSAEINVAL;
514 case EMFILE: return WSAEMFILE;
515 case EWOULDBLOCK: return WSAEWOULDBLOCK;
516 case EINPROGRESS: return WSAEINPROGRESS;
517 case EALREADY: return WSAEALREADY;
518 case ENOTSOCK: return WSAENOTSOCK;
519 case EDESTADDRREQ: return WSAEDESTADDRREQ;
520 case EMSGSIZE: return WSAEMSGSIZE;
521 case EPROTOTYPE: return WSAEPROTOTYPE;
522 case ENOPROTOOPT: return WSAENOPROTOOPT;
523 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
524 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
525 case EOPNOTSUPP: return WSAEOPNOTSUPP;
526 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
527 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
528 case EADDRINUSE: return WSAEADDRINUSE;
529 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
530 case ENETDOWN: return WSAENETDOWN;
531 case ENETUNREACH: return WSAENETUNREACH;
532 case ENETRESET: return WSAENETRESET;
533 case ECONNABORTED: return WSAECONNABORTED;
534 case EPIPE:
535 case ECONNRESET: return WSAECONNRESET;
536 case ENOBUFS: return WSAENOBUFS;
537 case EISCONN: return WSAEISCONN;
538 case ENOTCONN: return WSAENOTCONN;
539 case ESHUTDOWN: return WSAESHUTDOWN;
540 case ETOOMANYREFS: return WSAETOOMANYREFS;
541 case ETIMEDOUT: return WSAETIMEDOUT;
542 case ECONNREFUSED: return WSAECONNREFUSED;
543 case ELOOP: return WSAELOOP;
544 case ENAMETOOLONG: return WSAENAMETOOLONG;
545 case EHOSTDOWN: return WSAEHOSTDOWN;
546 case EHOSTUNREACH: return WSAEHOSTUNREACH;
547 case ENOTEMPTY: return WSAENOTEMPTY;
548 #ifdef EPROCLIM
549 case EPROCLIM: return WSAEPROCLIM;
550 #endif
551 #ifdef EUSERS
552 case EUSERS: return WSAEUSERS;
553 #endif
554 #ifdef EDQUOT
555 case EDQUOT: return WSAEDQUOT;
556 #endif
557 #ifdef ESTALE
558 case ESTALE: return WSAESTALE;
559 #endif
560 #ifdef EREMOTE
561 case EREMOTE: return WSAEREMOTE;
562 #endif
564 /* just in case we ever get here and there are no problems */
565 case 0: return 0;
566 default:
567 WARN("Unknown errno %d!\n", err);
568 return WSAEOPNOTSUPP;
572 static UINT wsaErrno(void)
574 int loc_errno = errno;
575 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
577 return sock_get_error( loc_errno );
580 /* most ws2 overlapped functions return an ntstatus-based error code */
581 static NTSTATUS wsaErrStatus(void)
583 int loc_errno = errno;
584 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
586 return sock_get_ntstatus(loc_errno);
589 static UINT wsaHerrno(int loc_errno)
591 WARN("h_errno %d.\n", loc_errno);
593 switch(loc_errno)
595 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
596 case TRY_AGAIN: return WSATRY_AGAIN;
597 case NO_RECOVERY: return WSANO_RECOVERY;
598 case NO_DATA: return WSANO_DATA;
599 case ENOBUFS: return WSAENOBUFS;
601 case 0: return 0;
602 default:
603 WARN("Unknown h_errno %d!\n", loc_errno);
604 return WSAEOPNOTSUPP;
608 static inline DWORD NtStatusToWSAError( const DWORD status )
610 /* We only need to cover the status codes set by server async request handling */
611 DWORD wserr;
612 switch ( status )
614 case STATUS_SUCCESS: wserr = 0; break;
615 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
616 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
617 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
618 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
619 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
620 case STATUS_NETWORK_BUSY: wserr = WSAEALREADY; break;
621 case STATUS_NETWORK_UNREACHABLE: wserr = WSAENETUNREACH; break;
622 case STATUS_CONNECTION_REFUSED: wserr = WSAECONNREFUSED; break;
623 case STATUS_CONNECTION_DISCONNECTED: wserr = WSAENOTCONN; break;
624 case STATUS_CONNECTION_RESET: wserr = WSAECONNRESET; break;
625 case STATUS_CONNECTION_ABORTED: wserr = WSAECONNABORTED; break;
626 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
627 case STATUS_ADDRESS_ALREADY_ASSOCIATED: wserr = WSAEADDRINUSE; break;
628 case STATUS_IO_TIMEOUT:
629 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
630 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
631 case STATUS_ACCESS_DENIED: wserr = WSAEACCES; break;
632 case STATUS_TOO_MANY_OPENED_FILES: wserr = WSAEMFILE; break;
633 case STATUS_CANT_WAIT: wserr = WSAEWOULDBLOCK; break;
634 case STATUS_BUFFER_OVERFLOW: wserr = WSAEMSGSIZE; break;
635 case STATUS_NOT_SUPPORTED: wserr = WSAEOPNOTSUPP; break;
636 case STATUS_HOST_UNREACHABLE: wserr = WSAEHOSTUNREACH; break;
638 default:
639 wserr = RtlNtStatusToDosError( status );
640 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
642 return wserr;
645 /* set last error code from NT status without mapping WSA errors */
646 static inline unsigned int set_error( unsigned int err )
648 if (err)
650 err = NtStatusToWSAError( err );
651 SetLastError( err );
653 return err;
656 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
658 int fd;
659 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
660 return -1;
661 return fd;
664 static inline void release_sock_fd( SOCKET s, int fd )
666 wine_server_release_fd( SOCKET2HANDLE(s), fd );
669 static void _enable_event( HANDLE s, unsigned int event,
670 unsigned int sstate, unsigned int cstate )
672 SERVER_START_REQ( enable_socket_event )
674 req->handle = wine_server_obj_handle( s );
675 req->mask = event;
676 req->sstate = sstate;
677 req->cstate = cstate;
678 wine_server_call( req );
680 SERVER_END_REQ;
683 static int _is_blocking(SOCKET s)
685 int ret;
686 SERVER_START_REQ( get_socket_event )
688 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
689 req->service = FALSE;
690 req->c_event = 0;
691 wine_server_call( req );
692 ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
694 SERVER_END_REQ;
695 return ret;
698 static unsigned int _get_sock_mask(SOCKET s)
700 unsigned int ret;
701 SERVER_START_REQ( get_socket_event )
703 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
704 req->service = FALSE;
705 req->c_event = 0;
706 wine_server_call( req );
707 ret = reply->mask;
709 SERVER_END_REQ;
710 return ret;
713 static void _sync_sock_state(SOCKET s)
715 /* do a dummy wineserver request in order to let
716 the wineserver run through its select loop once */
717 (void)_is_blocking(s);
720 static int _get_sock_error(SOCKET s, unsigned int bit)
722 int events[FD_MAX_EVENTS];
724 SERVER_START_REQ( get_socket_event )
726 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
727 req->service = FALSE;
728 req->c_event = 0;
729 wine_server_set_reply( req, events, sizeof(events) );
730 wine_server_call( req );
732 SERVER_END_REQ;
733 return events[bit];
736 static struct per_thread_data *get_per_thread_data(void)
738 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
739 /* lazy initialization */
740 if (!ptb)
742 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
743 NtCurrentTeb()->WinSockData = ptb;
745 return ptb;
748 static void free_per_thread_data(void)
750 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
752 if (!ptb) return;
754 /* delete scratch buffers */
755 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
756 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
757 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
758 ptb->he_buffer = NULL;
759 ptb->se_buffer = NULL;
760 ptb->pe_buffer = NULL;
762 HeapFree( GetProcessHeap(), 0, ptb );
763 NtCurrentTeb()->WinSockData = NULL;
766 /***********************************************************************
767 * DllMain (WS2_32.init)
769 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
771 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
772 switch (fdwReason) {
773 case DLL_PROCESS_ATTACH:
774 break;
775 case DLL_PROCESS_DETACH:
776 free_per_thread_data();
777 num_startup = 0;
778 break;
779 case DLL_THREAD_DETACH:
780 free_per_thread_data();
781 break;
783 return TRUE;
786 /***********************************************************************
787 * convert_sockopt()
789 * Converts socket flags from Windows format.
790 * Return 1 if converted, 0 if not (error).
792 static int convert_sockopt(INT *level, INT *optname)
794 unsigned int i;
795 switch (*level)
797 case WS_SOL_SOCKET:
798 *level = SOL_SOCKET;
799 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
800 if( ws_sock_map[i][0] == *optname )
802 *optname = ws_sock_map[i][1];
803 return 1;
806 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
807 break;
808 case WS_IPPROTO_TCP:
809 *level = IPPROTO_TCP;
810 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
811 if ( ws_tcp_map[i][0] == *optname )
813 *optname = ws_tcp_map[i][1];
814 return 1;
817 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
818 break;
819 case WS_IPPROTO_IP:
820 *level = IPPROTO_IP;
821 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
822 if (ws_ip_map[i][0] == *optname )
824 *optname = ws_ip_map[i][1];
825 return 1;
828 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
829 break;
830 case WS_IPPROTO_IPV6:
831 *level = IPPROTO_IPV6;
832 for(i=0; i<sizeof(ws_ipv6_map)/sizeof(ws_ipv6_map[0]); i++) {
833 if (ws_ipv6_map[i][0] == *optname )
835 *optname = ws_ipv6_map[i][1];
836 return 1;
839 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname);
840 break;
841 default: FIXME("Unimplemented or unknown socket level\n");
843 return 0;
846 /* ----------------------------------- Per-thread info (or per-process?) */
848 static char *strdup_lower(const char *str)
850 int i;
851 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
853 if (ret)
855 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
856 ret[i] = 0;
858 else SetLastError(WSAENOBUFS);
859 return ret;
862 static inline int sock_error_p(int s)
864 unsigned int optval, optlen;
866 optlen = sizeof(optval);
867 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
868 if (optval) WARN("\t[%i] error: %d\n", s, optval);
869 return optval != 0;
872 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
873 * from an fd and return the value converted to milli seconds
874 * or -1 if there is an infinite time out */
875 static inline int get_rcvsnd_timeo( int fd, int optname)
877 struct timeval tv;
878 unsigned int len = sizeof(tv);
879 int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
880 if( ret >= 0)
881 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
882 if( ret <= 0 ) /* tv == {0,0} means infinite time out */
883 return -1;
884 return ret;
887 /* macro wrappers for portability */
888 #ifdef SO_RCVTIMEO
889 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
890 #else
891 #define GET_RCVTIMEO(fd) (-1)
892 #endif
894 #ifdef SO_SNDTIMEO
895 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
896 #else
897 #define GET_SNDTIMEO(fd) (-1)
898 #endif
900 /* utility: given an fd, will block until one of the events occurs */
901 static inline int do_block( int fd, int events, int timeout )
903 struct pollfd pfd;
904 int ret;
906 pfd.fd = fd;
907 pfd.events = events;
909 while ((ret = poll(&pfd, 1, timeout)) < 0)
911 if (errno != EINTR)
912 return -1;
914 if( ret == 0 )
915 return 0;
916 return pfd.revents;
919 static int
920 convert_af_w2u(int windowsaf) {
921 unsigned int i;
923 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
924 if (ws_af_map[i][0] == windowsaf)
925 return ws_af_map[i][1];
926 FIXME("unhandled Windows address family %d\n", windowsaf);
927 return -1;
930 static int
931 convert_af_u2w(int unixaf) {
932 unsigned int i;
934 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
935 if (ws_af_map[i][1] == unixaf)
936 return ws_af_map[i][0];
937 FIXME("unhandled UNIX address family %d\n", unixaf);
938 return -1;
941 static int
942 convert_proto_w2u(int windowsproto) {
943 unsigned int i;
945 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
946 if (ws_proto_map[i][0] == windowsproto)
947 return ws_proto_map[i][1];
948 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
949 return -1;
952 static int
953 convert_proto_u2w(int unixproto) {
954 unsigned int i;
956 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
957 if (ws_proto_map[i][1] == unixproto)
958 return ws_proto_map[i][0];
959 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
960 return -1;
963 static int
964 convert_socktype_w2u(int windowssocktype) {
965 unsigned int i;
967 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
968 if (ws_socktype_map[i][0] == windowssocktype)
969 return ws_socktype_map[i][1];
970 FIXME("unhandled Windows socket type %d\n", windowssocktype);
971 return -1;
974 static int
975 convert_socktype_u2w(int unixsocktype) {
976 unsigned int i;
978 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
979 if (ws_socktype_map[i][1] == unixsocktype)
980 return ws_socktype_map[i][0];
981 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
982 return -1;
985 /* ----------------------------------- API -----
987 * Init / cleanup / error checking.
990 /***********************************************************************
991 * WSAStartup (WS2_32.115)
993 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
995 TRACE("verReq=%x\n", wVersionRequested);
997 if (LOBYTE(wVersionRequested) < 1)
998 return WSAVERNOTSUPPORTED;
1000 if (!lpWSAData) return WSAEINVAL;
1002 num_startup++;
1004 /* that's the whole of the negotiation for now */
1005 lpWSAData->wVersion = wVersionRequested;
1006 /* return winsock information */
1007 lpWSAData->wHighVersion = 0x0202;
1008 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
1009 strcpy(lpWSAData->szSystemStatus, "Running" );
1010 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
1011 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
1012 /* don't do anything with lpWSAData->lpVendorInfo */
1013 /* (some apps don't allocate the space for this field) */
1015 TRACE("succeeded\n");
1016 return 0;
1020 /***********************************************************************
1021 * WSACleanup (WS2_32.116)
1023 INT WINAPI WSACleanup(void)
1025 if (num_startup) {
1026 num_startup--;
1027 return 0;
1029 SetLastError(WSANOTINITIALISED);
1030 return SOCKET_ERROR;
1034 /***********************************************************************
1035 * WSAGetLastError (WS2_32.111)
1037 INT WINAPI WSAGetLastError(void)
1039 return GetLastError();
1042 /***********************************************************************
1043 * WSASetLastError (WS2_32.112)
1045 void WINAPI WSASetLastError(INT iError) {
1046 SetLastError(iError);
1049 static struct WS_hostent *check_buffer_he(int size)
1051 struct per_thread_data * ptb = get_per_thread_data();
1052 if (ptb->he_buffer)
1054 if (ptb->he_len >= size ) return ptb->he_buffer;
1055 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1057 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
1058 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
1059 return ptb->he_buffer;
1062 static struct WS_servent *check_buffer_se(int size)
1064 struct per_thread_data * ptb = get_per_thread_data();
1065 if (ptb->se_buffer)
1067 if (ptb->se_len >= size ) return ptb->se_buffer;
1068 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1070 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
1071 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
1072 return ptb->se_buffer;
1075 static struct WS_protoent *check_buffer_pe(int size)
1077 struct per_thread_data * ptb = get_per_thread_data();
1078 if (ptb->pe_buffer)
1080 if (ptb->pe_len >= size ) return ptb->pe_buffer;
1081 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1083 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
1084 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
1085 return ptb->pe_buffer;
1088 /* ----------------------------------- i/o APIs */
1090 static inline BOOL supported_pf(int pf)
1092 switch (pf)
1094 case WS_AF_INET:
1095 case WS_AF_INET6:
1096 return TRUE;
1097 #ifdef HAVE_IPX
1098 case WS_AF_IPX:
1099 return TRUE;
1100 #endif
1101 #ifdef HAVE_IRDA
1102 case WS_AF_IRDA:
1103 return TRUE;
1104 #endif
1105 default:
1106 return FALSE;
1111 /**********************************************************************/
1113 /* Returns the length of the converted address if successful, 0 if it was too small to
1114 * start with.
1116 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
1117 union generic_unix_sockaddr *uaddr)
1119 unsigned int uaddrlen = 0;
1121 switch (wsaddr->sa_family)
1123 #ifdef HAVE_IPX
1124 case WS_AF_IPX:
1126 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
1127 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
1129 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
1130 return 0;
1132 uaddrlen = sizeof(struct sockaddr_ipx);
1133 memset( uaddr, 0, uaddrlen );
1134 uipx->sipx_family=AF_IPX;
1135 uipx->sipx_port=wsipx->sa_socket;
1136 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1137 * in one go
1139 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
1140 #ifdef IPX_FRAME_NONE
1141 uipx->sipx_type=IPX_FRAME_NONE;
1142 #endif
1143 break;
1145 #endif
1146 case WS_AF_INET6: {
1147 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
1148 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
1150 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1151 * scope_id, one without.
1153 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
1154 uaddrlen = sizeof(struct sockaddr_in6);
1155 memset( uaddr, 0, uaddrlen );
1156 uin6->sin6_family = AF_INET6;
1157 uin6->sin6_port = win6->sin6_port;
1158 uin6->sin6_flowinfo = win6->sin6_flowinfo;
1159 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1160 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
1161 #endif
1162 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
1163 break;
1165 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
1166 return 0;
1168 case WS_AF_INET: {
1169 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
1170 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
1172 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
1173 return 0;
1174 uaddrlen = sizeof(struct sockaddr_in);
1175 memset( uaddr, 0, uaddrlen );
1176 uin->sin_family = AF_INET;
1177 uin->sin_port = win->sin_port;
1178 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
1179 break;
1181 #ifdef HAVE_IRDA
1182 case WS_AF_IRDA: {
1183 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
1184 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
1186 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
1187 return 0;
1188 uaddrlen = sizeof(struct sockaddr_irda);
1189 memset( uaddr, 0, uaddrlen );
1190 uin->sir_family = AF_IRDA;
1191 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1193 unsigned int lsap_sel;
1195 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
1196 uin->sir_lsap_sel = lsap_sel;
1198 else
1200 uin->sir_lsap_sel = LSAP_ANY;
1201 memcpy( uin->sir_name, win->irdaServiceName, 25 );
1203 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
1204 break;
1206 #endif
1207 case WS_AF_UNSPEC: {
1208 /* Try to determine the needed space by the passed windows sockaddr space */
1209 switch (wsaddrlen) {
1210 default: /* likely a ipv4 address */
1211 case sizeof(struct WS_sockaddr_in):
1212 uaddrlen = sizeof(struct sockaddr_in);
1213 break;
1214 #ifdef HAVE_IPX
1215 case sizeof(struct WS_sockaddr_ipx):
1216 uaddrlen = sizeof(struct sockaddr_ipx);
1217 break;
1218 #endif
1219 #ifdef HAVE_IRDA
1220 case sizeof(SOCKADDR_IRDA):
1221 uaddrlen = sizeof(struct sockaddr_irda);
1222 break;
1223 #endif
1224 case sizeof(struct WS_sockaddr_in6):
1225 case sizeof(struct WS_sockaddr_in6_old):
1226 uaddrlen = sizeof(struct sockaddr_in6);
1227 break;
1229 memset( uaddr, 0, uaddrlen );
1230 break;
1232 default:
1233 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1234 return 0;
1236 return uaddrlen;
1239 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
1241 switch (uaddr->sa_family)
1243 #ifdef HAVE_IPX
1244 case AF_IPX:
1245 FIXME("don't know how to tell if IPX socket is bound, assuming it is!\n");
1246 return TRUE;
1247 #endif
1248 case AF_INET6:
1250 static const struct sockaddr_in6 emptyAddr;
1251 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
1252 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
1254 case AF_INET:
1256 static const struct sockaddr_in emptyAddr;
1257 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
1258 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
1260 case AF_UNSPEC:
1261 return FALSE;
1262 default:
1263 FIXME("unknown address family %d\n", uaddr->sa_family);
1264 return TRUE;
1268 /* Returns 0 if successful, -1 if the buffer is too small */
1269 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
1271 int res;
1273 switch(uaddr->sa_family)
1275 #ifdef HAVE_IPX
1276 case AF_IPX:
1278 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
1279 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
1281 res=-1;
1282 switch (*wsaddrlen) /* how much can we copy? */
1284 default:
1285 res=0; /* enough */
1286 *wsaddrlen = sizeof(*wsipx);
1287 wsipx->sa_socket=uipx->sipx_port;
1288 /* fall through */
1289 case 13:
1290 case 12:
1291 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1292 /* fall through */
1293 case 11:
1294 case 10:
1295 case 9:
1296 case 8:
1297 case 7:
1298 case 6:
1299 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1300 /* fall through */
1301 case 5:
1302 case 4:
1303 case 3:
1304 case 2:
1305 wsipx->sa_family=WS_AF_IPX;
1306 /* fall through */
1307 case 1:
1308 case 0:
1309 /* way too small */
1310 break;
1313 break;
1314 #endif
1315 #ifdef HAVE_IRDA
1316 case AF_IRDA: {
1317 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
1318 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
1320 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
1321 return -1;
1322 win->irdaAddressFamily = WS_AF_IRDA;
1323 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
1324 if (uin->sir_lsap_sel != LSAP_ANY)
1325 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
1326 else
1327 memcpy( win->irdaServiceName, uin->sir_name,
1328 sizeof(win->irdaServiceName) );
1329 return 0;
1331 #endif
1332 case AF_INET6: {
1333 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1334 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1336 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1337 return -1;
1338 win6old->sin6_family = WS_AF_INET6;
1339 win6old->sin6_port = uin6->sin6_port;
1340 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1341 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1342 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1343 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1344 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1345 win6->sin6_scope_id = uin6->sin6_scope_id;
1346 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1348 else
1349 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1350 #else
1351 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1352 #endif
1353 return 0;
1355 case AF_INET: {
1356 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1357 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1359 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1360 return -1;
1361 win->sin_family = WS_AF_INET;
1362 win->sin_port = uin->sin_port;
1363 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1364 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1365 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1366 return 0;
1368 case AF_UNSPEC: {
1369 memset(wsaddr,0,*wsaddrlen);
1370 return 0;
1372 default:
1373 FIXME("Unknown address family %d\n", uaddr->sa_family);
1374 return -1;
1376 return res;
1379 /**************************************************************************
1380 * Functions for handling overlapped I/O
1381 **************************************************************************/
1383 /* user APC called upon async completion */
1384 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1386 ws2_async *wsa = arg;
1388 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
1389 iosb->Information, wsa->user_overlapped,
1390 wsa->flags );
1391 HeapFree( GetProcessHeap(), 0, wsa );
1394 /***********************************************************************
1395 * WS2_recv (INTERNAL)
1397 * Workhorse for both synchronous and asynchronous recv() operations.
1399 static int WS2_recv( int fd, struct ws2_async *wsa )
1401 struct msghdr hdr;
1402 union generic_unix_sockaddr unix_sockaddr;
1403 int n;
1405 hdr.msg_name = NULL;
1407 if (wsa->addr)
1409 hdr.msg_namelen = sizeof(unix_sockaddr);
1410 hdr.msg_name = &unix_sockaddr;
1412 else
1413 hdr.msg_namelen = 0;
1415 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1416 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1417 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1418 hdr.msg_accrights = NULL;
1419 hdr.msg_accrightslen = 0;
1420 #else
1421 hdr.msg_control = NULL;
1422 hdr.msg_controllen = 0;
1423 hdr.msg_flags = 0;
1424 #endif
1426 if ( (n = recvmsg(fd, &hdr, wsa->flags)) == -1 )
1427 return -1;
1429 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1430 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1432 * quoting linux 2.6 net/ipv4/tcp.c:
1433 * "According to UNIX98, msg_name/msg_namelen are ignored
1434 * on connected socket. I was just happy when found this 8) --ANK"
1436 * likewise MSDN says that lpFrom and lpFromlen are ignored for
1437 * connection-oriented sockets, so don't try to update lpFrom.
1439 if (wsa->addr && hdr.msg_namelen)
1440 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
1442 return n;
1445 /***********************************************************************
1446 * WS2_async_recv (INTERNAL)
1448 * Handler for overlapped recv() operations.
1450 static NTSTATUS WS2_async_recv( void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1452 ws2_async* wsa = user;
1453 int result = 0, fd;
1455 switch (status)
1457 case STATUS_ALERTED:
1458 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
1459 break;
1461 result = WS2_recv( fd, wsa );
1462 wine_server_release_fd( wsa->hSocket, fd );
1463 if (result >= 0)
1465 status = STATUS_SUCCESS;
1466 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1468 else
1470 if (errno == EINTR || errno == EAGAIN)
1472 status = STATUS_PENDING;
1473 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1475 else
1477 result = 0;
1478 status = wsaErrStatus();
1481 break;
1483 if (status != STATUS_PENDING)
1485 iosb->u.Status = status;
1486 iosb->Information = result;
1487 *apc = ws2_async_apc;
1489 return status;
1492 /***********************************************************************
1493 * WS2_send (INTERNAL)
1495 * Workhorse for both synchronous and asynchronous send() operations.
1497 static int WS2_send( int fd, struct ws2_async *wsa )
1499 struct msghdr hdr;
1500 union generic_unix_sockaddr unix_addr;
1502 hdr.msg_name = NULL;
1503 hdr.msg_namelen = 0;
1505 if (wsa->addr)
1507 hdr.msg_name = &unix_addr;
1508 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
1509 if ( !hdr.msg_namelen )
1511 errno = EFAULT;
1512 return -1;
1515 #if defined(HAVE_IPX) && defined(SOL_IPX)
1516 if(wsa->addr->sa_family == WS_AF_IPX)
1518 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
1519 int val=0;
1520 unsigned int len=sizeof(int);
1522 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
1523 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
1524 * the packet type and then we can retrieve it using getsockopt. After that we can set the
1525 * ipx type in the sockaddr_opx structure with the stored value.
1527 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
1528 uipx->sipx_type = val;
1530 #endif
1533 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1534 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1535 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1536 hdr.msg_accrights = NULL;
1537 hdr.msg_accrightslen = 0;
1538 #else
1539 hdr.msg_control = NULL;
1540 hdr.msg_controllen = 0;
1541 hdr.msg_flags = 0;
1542 #endif
1544 return sendmsg(fd, &hdr, wsa->flags);
1547 /***********************************************************************
1548 * WS2_async_send (INTERNAL)
1550 * Handler for overlapped send() operations.
1552 static NTSTATUS WS2_async_send(void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1554 ws2_async* wsa = user;
1555 int result = 0, fd;
1557 switch (status)
1559 case STATUS_ALERTED:
1560 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
1561 break;
1563 /* check to see if the data is ready (non-blocking) */
1564 result = WS2_send( fd, wsa );
1565 wine_server_release_fd( wsa->hSocket, fd );
1567 if (result >= 0)
1569 int totalLength = 0;
1570 unsigned int i;
1571 status = STATUS_SUCCESS;
1572 for (i = 0; i < wsa->n_iovecs; i++)
1573 totalLength += wsa->iovec[i].iov_len;
1574 if (result < totalLength)
1575 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1577 else
1579 if (errno == EINTR || errno == EAGAIN)
1581 status = STATUS_PENDING;
1582 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1584 else
1586 status = wsaErrStatus();
1587 result = 0;
1590 break;
1592 if (status != STATUS_PENDING)
1594 iosb->u.Status = status;
1595 iosb->Information = result;
1596 *apc = ws2_async_apc;
1598 return status;
1601 /***********************************************************************
1602 * WS2_async_shutdown (INTERNAL)
1604 * Handler for shutdown() operations on overlapped sockets.
1606 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
1608 ws2_async* wsa = user;
1609 int fd, err = 1;
1611 switch (status)
1613 case STATUS_ALERTED:
1614 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
1615 break;
1617 switch ( wsa->type )
1619 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
1620 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
1622 status = err ? wsaErrStatus() : STATUS_SUCCESS;
1623 wine_server_release_fd( wsa->hSocket, fd );
1624 break;
1626 iosb->u.Status = status;
1627 iosb->Information = 0;
1628 *apc = ws2_async_apc;
1629 return status;
1632 /***********************************************************************
1633 * WS2_register_async_shutdown (INTERNAL)
1635 * Helper function for WS_shutdown() on overlapped sockets.
1637 static int WS2_register_async_shutdown( SOCKET s, int type )
1639 struct ws2_async *wsa;
1640 NTSTATUS status;
1642 TRACE("s %ld type %d\n", s, type);
1644 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
1645 if ( !wsa )
1646 return WSAEFAULT;
1648 wsa->hSocket = SOCKET2HANDLE(s);
1649 wsa->type = type;
1650 wsa->completion_func = NULL;
1652 SERVER_START_REQ( register_async )
1654 req->type = type;
1655 req->async.handle = wine_server_obj_handle( wsa->hSocket );
1656 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
1657 req->async.iosb = wine_server_client_ptr( &wsa->local_iosb );
1658 req->async.arg = wine_server_client_ptr( wsa );
1659 req->async.cvalue = 0;
1660 status = wine_server_call( req );
1662 SERVER_END_REQ;
1664 if (status != STATUS_PENDING)
1666 HeapFree( GetProcessHeap(), 0, wsa );
1667 return NtStatusToWSAError( status );
1669 return 0;
1672 /***********************************************************************
1673 * accept (WS2_32.1)
1675 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr,
1676 int *addrlen32)
1678 NTSTATUS status;
1679 SOCKET as;
1680 BOOL is_blocking;
1682 TRACE("socket %04lx\n", s );
1683 is_blocking = _is_blocking(s);
1685 do {
1686 /* try accepting first (if there is a deferred connection) */
1687 SERVER_START_REQ( accept_socket )
1689 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1690 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
1691 req->attributes = OBJ_INHERIT;
1692 status = wine_server_call( req );
1693 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
1695 SERVER_END_REQ;
1696 if (!status)
1698 if (addr) WS_getpeername(as, addr, addrlen32);
1699 return as;
1701 if (is_blocking && status == STATUS_CANT_WAIT)
1703 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1704 /* block here */
1705 do_block(fd, POLLIN, -1);
1706 _sync_sock_state(s); /* let wineserver notice connection */
1707 release_sock_fd( s, fd );
1709 } while (is_blocking && status == STATUS_CANT_WAIT);
1711 set_error(status);
1712 return INVALID_SOCKET;
1715 /***********************************************************************
1716 * bind (WS2_32.2)
1718 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
1720 int fd = get_sock_fd( s, 0, NULL );
1721 int res = SOCKET_ERROR;
1723 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1725 if (fd != -1)
1727 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
1729 SetLastError(WSAEAFNOSUPPORT);
1731 else
1733 union generic_unix_sockaddr uaddr;
1734 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1735 if (!uaddrlen)
1737 SetLastError(WSAEFAULT);
1739 else
1741 #ifdef IPV6_V6ONLY
1742 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
1743 if (name->sa_family == WS_AF_INET6 &&
1744 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
1746 int enable = 1;
1747 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
1749 release_sock_fd( s, fd );
1750 SetLastError(WSAEAFNOSUPPORT);
1751 return SOCKET_ERROR;
1754 #endif
1755 if (name->sa_family == WS_AF_INET)
1757 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
1758 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
1760 /* Trying to bind to the default host interface, using
1761 * INADDR_ANY instead*/
1762 WARN("Trying to bind to magic IP address, using "
1763 "INADDR_ANY instead.\n");
1764 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
1767 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
1769 int loc_errno = errno;
1770 WARN("\tfailure - errno = %i\n", errno);
1771 errno = loc_errno;
1772 switch (errno)
1774 case EBADF:
1775 SetLastError(WSAENOTSOCK);
1776 break;
1777 case EADDRNOTAVAIL:
1778 SetLastError(WSAEINVAL);
1779 break;
1780 default:
1781 SetLastError(wsaErrno());
1782 break;
1785 else
1787 res=0; /* success */
1791 release_sock_fd( s, fd );
1793 return res;
1796 /***********************************************************************
1797 * closesocket (WS2_32.3)
1799 int WINAPI WS_closesocket(SOCKET s)
1801 TRACE("socket %04lx\n", s);
1802 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
1803 return SOCKET_ERROR;
1806 /***********************************************************************
1807 * connect (WS2_32.4)
1809 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
1811 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1813 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1815 if (fd != -1)
1817 union generic_unix_sockaddr uaddr;
1818 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1820 if (!uaddrlen)
1822 SetLastError(WSAEFAULT);
1824 else
1826 if (name->sa_family == WS_AF_INET)
1828 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
1829 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
1831 /* Trying to connect to magic replace-loopback address,
1832 * assuming we really want to connect to localhost */
1833 TRACE("Trying to connect to magic IP address, using "
1834 "INADDR_LOOPBACK instead.\n");
1835 in4->sin_addr.s_addr = htonl(WS_INADDR_LOOPBACK);
1839 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
1840 goto connect_success;
1843 if (errno == EINPROGRESS)
1845 /* tell wineserver that a connection is in progress */
1846 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1847 FD_CONNECT|FD_READ|FD_WRITE,
1848 FD_WINE_CONNECTED|FD_WINE_LISTENING);
1849 if (_is_blocking(s))
1851 int result;
1852 /* block here */
1853 do_block(fd, POLLIN | POLLOUT, -1);
1854 _sync_sock_state(s); /* let wineserver notice connection */
1855 /* retrieve any error codes from it */
1856 result = _get_sock_error(s, FD_CONNECT_BIT);
1857 if (result)
1858 SetLastError(NtStatusToWSAError(result));
1859 else
1861 goto connect_success;
1864 else
1866 SetLastError(WSAEWOULDBLOCK);
1869 else
1871 SetLastError(wsaErrno());
1873 release_sock_fd( s, fd );
1875 return SOCKET_ERROR;
1877 connect_success:
1878 release_sock_fd( s, fd );
1879 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1880 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
1881 FD_CONNECT|FD_WINE_LISTENING);
1882 return 0;
1885 /***********************************************************************
1886 * WSAConnect (WS2_32.30)
1888 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
1889 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
1890 LPQOS lpSQOS, LPQOS lpGQOS )
1892 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
1893 FIXME("unsupported parameters!\n");
1894 return WS_connect( s, name, namelen );
1898 /***********************************************************************
1899 * getpeername (WS2_32.5)
1901 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
1903 int fd;
1904 int res;
1906 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, namelen?*namelen:0);
1908 fd = get_sock_fd( s, 0, NULL );
1909 res = SOCKET_ERROR;
1911 if (fd != -1)
1913 union generic_unix_sockaddr uaddr;
1914 unsigned int uaddrlen = sizeof(uaddr);
1916 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
1918 if (!name || !namelen)
1919 SetLastError(WSAEFAULT);
1920 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1921 /* The buffer was too small */
1922 SetLastError(WSAEFAULT);
1923 else
1924 res = 0;
1926 else
1927 SetLastError(wsaErrno());
1928 release_sock_fd( s, fd );
1930 return res;
1933 /***********************************************************************
1934 * getsockname (WS2_32.6)
1936 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
1938 int fd;
1939 int res;
1941 TRACE("socket: %04lx, ptr %p, len %8x\n", s, name, *namelen);
1943 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1944 if( (name == NULL) || (namelen == NULL) )
1946 SetLastError( WSAEFAULT );
1947 return SOCKET_ERROR;
1950 fd = get_sock_fd( s, 0, NULL );
1951 res = SOCKET_ERROR;
1953 if (fd != -1)
1955 union generic_unix_sockaddr uaddr;
1956 unsigned int uaddrlen = sizeof(uaddr);
1958 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
1960 SetLastError(wsaErrno());
1962 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
1964 SetLastError(WSAEINVAL);
1966 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1968 /* The buffer was too small */
1969 SetLastError(WSAEFAULT);
1971 else
1973 res=0;
1975 release_sock_fd( s, fd );
1977 return res;
1980 /***********************************************************************
1981 * getsockopt (WS2_32.7)
1983 INT WINAPI WS_getsockopt(SOCKET s, INT level,
1984 INT optname, char *optval, INT *optlen)
1986 int fd;
1987 INT ret = 0;
1989 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
1990 s, level, optname, optval, *optlen);
1992 switch(level)
1994 case WS_SOL_SOCKET:
1996 switch(optname)
1998 /* Handle common cases. The special cases are below, sorted
1999 * alphabetically */
2000 case WS_SO_ACCEPTCONN:
2001 case WS_SO_BROADCAST:
2002 case WS_SO_DEBUG:
2003 case WS_SO_ERROR:
2004 case WS_SO_KEEPALIVE:
2005 case WS_SO_OOBINLINE:
2006 case WS_SO_RCVBUF:
2007 case WS_SO_REUSEADDR:
2008 case WS_SO_SNDBUF:
2009 case WS_SO_TYPE:
2010 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2011 return SOCKET_ERROR;
2012 convert_sockopt(&level, &optname);
2013 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2015 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2016 ret = SOCKET_ERROR;
2018 release_sock_fd( s, fd );
2019 return ret;
2021 case WS_SO_DONTLINGER:
2023 struct linger lingval;
2024 unsigned int len = sizeof(struct linger);
2026 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
2028 SetLastError(WSAEFAULT);
2029 return SOCKET_ERROR;
2031 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2032 return SOCKET_ERROR;
2034 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
2036 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2037 ret = SOCKET_ERROR;
2039 else
2041 *(BOOL *)optval = (lingval.l_onoff) ? FALSE : TRUE;
2042 *optlen = sizeof(BOOL);
2045 release_sock_fd( s, fd );
2046 return ret;
2049 /* As mentioned in setsockopt, Windows ignores this, so we
2050 * always return true here */
2051 case WS_SO_DONTROUTE:
2052 if (!optlen || *optlen < sizeof(BOOL) || !optval)
2054 SetLastError(WSAEFAULT);
2055 return SOCKET_ERROR;
2057 *(BOOL *)optval = TRUE;
2058 *optlen = sizeof(BOOL);
2059 return 0;
2061 case WS_SO_LINGER:
2063 struct linger lingval;
2064 unsigned int len = sizeof(struct linger);
2066 /* struct linger and LINGER have different sizes */
2067 if (!optlen || *optlen < sizeof(LINGER) || !optval)
2069 SetLastError(WSAEFAULT);
2070 return SOCKET_ERROR;
2072 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2073 return SOCKET_ERROR;
2075 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
2077 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2078 ret = SOCKET_ERROR;
2080 else
2082 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
2083 ((LINGER *)optval)->l_linger = lingval.l_linger;
2084 *optlen = sizeof(struct linger);
2087 release_sock_fd( s, fd );
2088 return ret;
2091 case WS_SO_MAX_MSG_SIZE:
2092 if (!optlen || *optlen < sizeof(int) || !optval)
2094 SetLastError(WSAEFAULT);
2095 return SOCKET_ERROR;
2097 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
2098 *(int *)optval = 65507;
2099 *optlen = sizeof(int);
2100 return 0;
2102 /* SO_OPENTYPE does not require a valid socket handle. */
2103 case WS_SO_OPENTYPE:
2104 if (!optlen || *optlen < sizeof(int) || !optval)
2106 SetLastError(WSAEFAULT);
2107 return SOCKET_ERROR;
2109 *(int *)optval = get_per_thread_data()->opentype;
2110 *optlen = sizeof(int);
2111 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
2112 return 0;
2114 #ifdef SO_RCVTIMEO
2115 case WS_SO_RCVTIMEO:
2116 #endif
2117 #ifdef SO_SNDTIMEO
2118 case WS_SO_SNDTIMEO:
2119 #endif
2120 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
2122 struct timeval tv;
2123 unsigned int len = sizeof(struct timeval);
2125 if (!optlen || *optlen < sizeof(int)|| !optval)
2127 SetLastError(WSAEFAULT);
2128 return SOCKET_ERROR;
2130 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2131 return SOCKET_ERROR;
2133 convert_sockopt(&level, &optname);
2134 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
2136 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2137 ret = SOCKET_ERROR;
2139 else
2141 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
2142 *optlen = sizeof(int);
2145 release_sock_fd( s, fd );
2146 return ret;
2148 #endif
2149 default:
2150 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
2151 SetLastError(WSAENOPROTOOPT);
2152 return SOCKET_ERROR;
2153 } /* end switch(optname) */
2154 }/* end case WS_SOL_SOCKET */
2155 #ifdef HAVE_IPX
2156 case NSPROTO_IPX:
2158 struct WS_sockaddr_ipx addr;
2159 IPX_ADDRESS_DATA *data;
2160 int namelen;
2161 switch(optname)
2163 case IPX_PTYPE:
2164 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
2165 #ifdef SOL_IPX
2166 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (unsigned int*)optlen) == -1)
2168 ret = SOCKET_ERROR;
2170 #else
2172 struct ipx val;
2173 socklen_t len=sizeof(struct ipx);
2174 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
2175 ret = SOCKET_ERROR;
2176 else
2177 *optval = (int)val.ipx_pt;
2179 #endif
2180 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
2181 release_sock_fd( s, fd );
2182 return ret;
2184 case IPX_ADDRESS:
2186 * On a Win2000 system with one network card there are usually
2187 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
2188 * Using this call you can then retrieve info about this all.
2189 * In case of Linux it is a bit different. Usually you have
2190 * only "one" device active and further it is not possible to
2191 * query things like the linkspeed.
2193 FIXME("IPX_ADDRESS\n");
2194 namelen = sizeof(struct WS_sockaddr_ipx);
2195 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
2196 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
2198 data = (IPX_ADDRESS_DATA*)optval;
2199 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
2200 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
2201 data->adapternum = 0;
2202 data->wan = FALSE; /* We are not on a wan for now .. */
2203 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
2204 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
2205 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
2206 * note 1MB = 1000kB in this case */
2207 return 0;
2209 case IPX_MAX_ADAPTER_NUM:
2210 FIXME("IPX_MAX_ADAPTER_NUM\n");
2211 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
2212 return 0;
2214 default:
2215 FIXME("IPX optname:%x\n", optname);
2216 return SOCKET_ERROR;
2217 }/* end switch(optname) */
2218 } /* end case NSPROTO_IPX */
2219 #endif
2221 #ifdef HAVE_IRDA
2222 case WS_SOL_IRLMP:
2223 switch(optname)
2225 case WS_IRLMP_ENUMDEVICES:
2227 static const int MAX_IRDA_DEVICES = 10;
2228 char buf[sizeof(struct irda_device_list) +
2229 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
2230 int fd, res;
2231 socklen_t len = sizeof(buf);
2233 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2234 return SOCKET_ERROR;
2235 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
2236 if (res < 0)
2238 SetLastError(wsaErrno());
2239 return SOCKET_ERROR;
2241 else
2243 struct irda_device_list *src = (struct irda_device_list *)buf;
2244 DEVICELIST *dst = (DEVICELIST *)optval;
2245 INT needed = sizeof(DEVICELIST), i;
2247 if (src->len > 0)
2248 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
2249 if (*optlen < needed)
2251 SetLastError(WSAEFAULT);
2252 return SOCKET_ERROR;
2254 *optlen = needed;
2255 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
2256 dst->numDevice = src->len;
2257 for (i = 0; i < src->len; i++)
2259 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
2260 src->dev[i].saddr, src->dev[i].daddr,
2261 src->dev[i].info, src->dev[i].hints[0],
2262 src->dev[i].hints[1]);
2263 memcpy( dst->Device[i].irdaDeviceID,
2264 &src->dev[i].daddr,
2265 sizeof(dst->Device[i].irdaDeviceID) ) ;
2266 memcpy( dst->Device[i].irdaDeviceName,
2267 &src->dev[i].info,
2268 sizeof(dst->Device[i].irdaDeviceName) ) ;
2269 memcpy( &dst->Device[i].irdaDeviceHints1,
2270 &src->dev[i].hints[0],
2271 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
2272 memcpy( &dst->Device[i].irdaDeviceHints2,
2273 &src->dev[i].hints[1],
2274 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
2275 dst->Device[i].irdaCharSet = src->dev[i].charset;
2277 return 0;
2280 default:
2281 FIXME("IrDA optname:0x%x\n", optname);
2282 return SOCKET_ERROR;
2284 break; /* case WS_SOL_IRLMP */
2285 #endif
2287 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
2288 case WS_IPPROTO_TCP:
2289 switch(optname)
2291 case WS_TCP_NODELAY:
2292 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2293 return SOCKET_ERROR;
2294 convert_sockopt(&level, &optname);
2295 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2297 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2298 ret = SOCKET_ERROR;
2300 release_sock_fd( s, fd );
2301 return ret;
2303 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
2304 return SOCKET_ERROR;
2306 case WS_IPPROTO_IP:
2307 switch(optname)
2309 case WS_IP_ADD_MEMBERSHIP:
2310 case WS_IP_DROP_MEMBERSHIP:
2311 #ifdef IP_HDRINCL
2312 case WS_IP_HDRINCL:
2313 #endif
2314 case WS_IP_MULTICAST_IF:
2315 case WS_IP_MULTICAST_LOOP:
2316 case WS_IP_MULTICAST_TTL:
2317 case WS_IP_OPTIONS:
2318 case WS_IP_TOS:
2319 case WS_IP_TTL:
2320 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2321 return SOCKET_ERROR;
2322 convert_sockopt(&level, &optname);
2323 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2325 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2326 ret = SOCKET_ERROR;
2328 release_sock_fd( s, fd );
2329 return ret;
2330 case WS_IP_DONTFRAGMENT:
2331 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
2332 *(BOOL*)optval = FALSE;
2333 return 0;
2335 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
2336 return SOCKET_ERROR;
2338 case WS_IPPROTO_IPV6:
2339 switch(optname)
2341 #ifdef IPV6_ADD_MEMBERSHIP
2342 case WS_IPV6_ADD_MEMBERSHIP:
2343 #endif
2344 #ifdef IPV6_DROP_MEMBERSHIP
2345 case WS_IPV6_DROP_MEMBERSHIP:
2346 #endif
2347 case WS_IPV6_MULTICAST_IF:
2348 case WS_IPV6_MULTICAST_HOPS:
2349 case WS_IPV6_MULTICAST_LOOP:
2350 case WS_IPV6_UNICAST_HOPS:
2351 case WS_IPV6_V6ONLY:
2352 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2353 return SOCKET_ERROR;
2354 convert_sockopt(&level, &optname);
2355 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2357 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2358 ret = SOCKET_ERROR;
2360 release_sock_fd( s, fd );
2361 return ret;
2362 case WS_IPV6_DONTFRAG:
2363 FIXME("WS_IPV6_DONTFRAG is always false!\n");
2364 *(BOOL*)optval = FALSE;
2365 return 0;
2367 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
2368 return SOCKET_ERROR;
2370 default:
2371 WARN("Unknown level: 0x%08x\n", level);
2372 SetLastError(WSAEINVAL);
2373 return SOCKET_ERROR;
2374 } /* end switch(level) */
2377 /***********************************************************************
2378 * htonl (WS2_32.8)
2380 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
2382 return htonl(hostlong);
2386 /***********************************************************************
2387 * htons (WS2_32.9)
2389 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
2391 return htons(hostshort);
2394 /***********************************************************************
2395 * WSAHtonl (WS2_32.46)
2396 * From MSDN description of error codes, this function should also
2397 * check if WinSock has been initialized and the socket is a valid
2398 * socket. But why? This function only translates a host byte order
2399 * u_long into a network byte order u_long...
2401 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
2403 if (lpnetlong)
2405 *lpnetlong = htonl(hostlong);
2406 return 0;
2408 WSASetLastError(WSAEFAULT);
2409 return SOCKET_ERROR;
2412 /***********************************************************************
2413 * WSAHtons (WS2_32.47)
2414 * From MSDN description of error codes, this function should also
2415 * check if WinSock has been initialized and the socket is a valid
2416 * socket. But why? This function only translates a host byte order
2417 * u_short into a network byte order u_short...
2419 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
2422 if (lpnetshort)
2424 *lpnetshort = htons(hostshort);
2425 return 0;
2427 WSASetLastError(WSAEFAULT);
2428 return SOCKET_ERROR;
2432 /***********************************************************************
2433 * inet_addr (WS2_32.11)
2435 WS_u_long WINAPI WS_inet_addr(const char *cp)
2437 if (!cp) return INADDR_NONE;
2438 return inet_addr(cp);
2442 /***********************************************************************
2443 * ntohl (WS2_32.14)
2445 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
2447 return ntohl(netlong);
2451 /***********************************************************************
2452 * ntohs (WS2_32.15)
2454 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
2456 return ntohs(netshort);
2460 /***********************************************************************
2461 * inet_ntoa (WS2_32.12)
2463 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
2465 /* use "buffer for dummies" here because some applications have a
2466 * propensity to decode addresses in ws_hostent structure without
2467 * saving them first...
2469 static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
2471 char* s = inet_ntoa(*((struct in_addr*)&in));
2472 if( s )
2474 strcpy(dbuffer, s);
2475 return dbuffer;
2477 SetLastError(wsaErrno());
2478 return NULL;
2481 /**********************************************************************
2482 * WSAIoctl (WS2_32.50)
2485 INT WINAPI WSAIoctl(SOCKET s,
2486 DWORD dwIoControlCode,
2487 LPVOID lpvInBuffer,
2488 DWORD cbInBuffer,
2489 LPVOID lpbOutBuffer,
2490 DWORD cbOutBuffer,
2491 LPDWORD lpcbBytesReturned,
2492 LPWSAOVERLAPPED lpOverlapped,
2493 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2495 TRACE("%ld, 0x%08x, %p, %d, %p, %d, %p, %p, %p\n",
2496 s, dwIoControlCode, lpvInBuffer, cbInBuffer, lpbOutBuffer,
2497 cbOutBuffer, lpcbBytesReturned, lpOverlapped, lpCompletionRoutine);
2499 switch( dwIoControlCode )
2501 case WS_FIONBIO:
2502 if (cbInBuffer != sizeof(WS_u_long)) {
2503 WSASetLastError(WSAEFAULT);
2504 return SOCKET_ERROR;
2506 return WS_ioctlsocket( s, WS_FIONBIO, lpvInBuffer);
2508 case WS_FIONREAD:
2509 if (cbOutBuffer != sizeof(WS_u_long)) {
2510 WSASetLastError(WSAEFAULT);
2511 return SOCKET_ERROR;
2513 return WS_ioctlsocket( s, WS_FIONREAD, lpbOutBuffer);
2515 case WS_SIO_GET_INTERFACE_LIST:
2517 INTERFACE_INFO* intArray = (INTERFACE_INFO*)lpbOutBuffer;
2518 DWORD size, numInt, apiReturn;
2519 int fd;
2521 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
2523 if (!lpbOutBuffer)
2525 WSASetLastError(WSAEFAULT);
2526 return SOCKET_ERROR;
2528 if (!lpcbBytesReturned)
2530 WSASetLastError(WSAEFAULT);
2531 return SOCKET_ERROR;
2534 fd = get_sock_fd( s, 0, NULL );
2535 if (fd == -1) return SOCKET_ERROR;
2537 apiReturn = GetAdaptersInfo(NULL, &size);
2538 if (apiReturn == ERROR_NO_DATA)
2540 numInt = 0;
2542 else if (apiReturn == ERROR_BUFFER_OVERFLOW)
2544 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
2546 if (table)
2548 if (GetAdaptersInfo(table, &size) == NO_ERROR)
2550 PIP_ADAPTER_INFO ptr;
2552 if (size*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > cbOutBuffer)
2554 WARN("Buffer too small = %u, cbOutBuffer = %u\n", size, cbOutBuffer);
2555 HeapFree(GetProcessHeap(),0,table);
2556 release_sock_fd( s, fd );
2557 WSASetLastError(WSAEFAULT);
2558 return SOCKET_ERROR;
2560 for (ptr = table, numInt = 0; ptr;
2561 ptr = ptr->Next, intArray++, numInt++)
2563 unsigned int addr, mask, bcast;
2564 struct ifreq ifInfo;
2566 /* Socket Status Flags */
2567 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
2568 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
2570 ERR("Error obtaining status flags for socket!\n");
2571 HeapFree(GetProcessHeap(),0,table);
2572 release_sock_fd( s, fd );
2573 WSASetLastError(WSAEINVAL);
2574 return SOCKET_ERROR;
2576 else
2578 /* set flags; the values of IFF_* are not the same
2579 under Linux and Windows, therefore must generate
2580 new flags */
2581 intArray->iiFlags = 0;
2582 if (ifInfo.ifr_flags & IFF_BROADCAST)
2583 intArray->iiFlags |= WS_IFF_BROADCAST;
2584 #ifdef IFF_POINTOPOINT
2585 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
2586 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
2587 #endif
2588 if (ifInfo.ifr_flags & IFF_LOOPBACK)
2589 intArray->iiFlags |= WS_IFF_LOOPBACK;
2590 if (ifInfo.ifr_flags & IFF_UP)
2591 intArray->iiFlags |= WS_IFF_UP;
2592 if (ifInfo.ifr_flags & IFF_MULTICAST)
2593 intArray->iiFlags |= WS_IFF_MULTICAST;
2596 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
2597 mask = inet_addr(ptr->IpAddressList.IpMask.String);
2598 bcast = addr | ~mask;
2599 intArray->iiAddress.AddressIn.sin_family = AF_INET;
2600 intArray->iiAddress.AddressIn.sin_port = 0;
2601 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
2602 addr;
2603 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
2604 intArray->iiNetmask.AddressIn.sin_port = 0;
2605 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
2606 mask;
2607 intArray->iiBroadcastAddress.AddressIn.sin_family =
2608 AF_INET;
2609 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
2610 intArray->iiBroadcastAddress.AddressIn.sin_addr.
2611 WS_s_addr = bcast;
2614 else
2616 ERR("Unable to get interface table!\n");
2617 release_sock_fd( s, fd );
2618 HeapFree(GetProcessHeap(),0,table);
2619 WSASetLastError(WSAEINVAL);
2620 return SOCKET_ERROR;
2622 HeapFree(GetProcessHeap(),0,table);
2624 else
2626 release_sock_fd( s, fd );
2627 WSASetLastError(WSAEINVAL);
2628 return SOCKET_ERROR;
2631 else
2633 ERR("Unable to get interface table!\n");
2634 release_sock_fd( s, fd );
2635 WSASetLastError(WSAEINVAL);
2636 return SOCKET_ERROR;
2638 /* Calculate the size of the array being returned */
2639 *lpcbBytesReturned = sizeof(INTERFACE_INFO) * numInt;
2640 release_sock_fd( s, fd );
2641 break;
2644 case WS_SIO_ADDRESS_LIST_CHANGE:
2645 FIXME("-> SIO_ADDRESS_LIST_CHANGE request: stub\n");
2646 /* FIXME: error and return code depend on whether socket was created
2647 * with WSA_FLAG_OVERLAPPED, but there is no easy way to get this */
2648 break;
2650 case WS_SIO_ADDRESS_LIST_QUERY:
2652 DWORD size;
2654 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
2656 if (!lpcbBytesReturned)
2658 WSASetLastError(WSAEFAULT);
2659 return SOCKET_ERROR;
2662 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
2664 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
2665 DWORD need, num;
2667 if (!table || GetAdaptersInfo(table, &size))
2669 HeapFree(GetProcessHeap(), 0, table);
2670 WSASetLastError(WSAEINVAL);
2671 return SOCKET_ERROR;
2674 for (p = table, num = 0; p; p = p->Next)
2675 if (p->IpAddressList.IpAddress.String[0]) num++;
2677 need = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
2678 need += sizeof(SOCKADDR) * num;
2679 *lpcbBytesReturned = need;
2681 if (need > cbOutBuffer)
2683 HeapFree(GetProcessHeap(), 0, table);
2684 WSASetLastError(WSAEFAULT);
2685 return SOCKET_ERROR;
2688 if (lpbOutBuffer)
2690 unsigned int i;
2691 SOCKET_ADDRESS *sa;
2692 SOCKET_ADDRESS_LIST *sa_list = (SOCKET_ADDRESS_LIST *)lpbOutBuffer;
2693 SOCKADDR_IN *sockaddr;
2695 sa = sa_list->Address;
2696 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
2697 sa_list->iAddressCount = num;
2699 for (p = table, i = 0; p; p = p->Next)
2701 if (!p->IpAddressList.IpAddress.String[0]) continue;
2703 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
2704 sa[i].iSockaddrLength = sizeof(SOCKADDR);
2706 sockaddr[i].sin_family = AF_INET;
2707 sockaddr[i].sin_port = 0;
2708 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
2709 i++;
2713 HeapFree(GetProcessHeap(), 0, table);
2714 return 0;
2716 else
2718 WARN("unable to get IP address list\n");
2719 WSASetLastError(WSAEINVAL);
2720 return SOCKET_ERROR;
2723 case WS_SIO_FLUSH:
2724 FIXME("SIO_FLUSH: stub.\n");
2725 break;
2727 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
2729 static const GUID connectex_guid = WSAID_CONNECTEX;
2730 static const GUID disconnectex_guid = WSAID_DISCONNECTEX;
2731 static const GUID acceptex_guid = WSAID_ACCEPTEX;
2732 static const GUID getaccepexsockaddrs_guid = WSAID_GETACCEPTEXSOCKADDRS;
2733 static const GUID transmitfile_guid = WSAID_TRANSMITFILE;
2734 static const GUID transmitpackets_guid = WSAID_TRANSMITPACKETS;
2735 static const GUID wsarecvmsg_guid = WSAID_WSARECVMSG;
2736 static const GUID wsasendmsg_guid = WSAID_WSASENDMSG;
2738 if ( IsEqualGUID(&connectex_guid, lpvInBuffer) )
2740 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented ConnectEx\n");
2742 else if ( IsEqualGUID(&disconnectex_guid, lpvInBuffer) )
2744 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented DisconnectEx\n");
2746 else if ( IsEqualGUID(&acceptex_guid, lpvInBuffer) )
2748 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented AcceptEx\n");
2750 else if ( IsEqualGUID(&getaccepexsockaddrs_guid, lpvInBuffer) )
2752 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented GetAcceptExSockaddrs\n");
2754 else if ( IsEqualGUID(&transmitfile_guid, lpvInBuffer) )
2756 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitFile\n");
2758 else if ( IsEqualGUID(&transmitpackets_guid, lpvInBuffer) )
2760 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
2762 else if ( IsEqualGUID(&wsarecvmsg_guid, lpvInBuffer) )
2764 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented WSARecvMsg\n");
2766 else if ( IsEqualGUID(&wsasendmsg_guid, lpvInBuffer) )
2768 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented WSASendMsg\n");
2770 else
2771 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(lpvInBuffer));
2773 WSASetLastError(WSAEOPNOTSUPP);
2774 return SOCKET_ERROR;
2777 case WS_SIO_KEEPALIVE_VALS:
2779 int fd;
2780 struct tcp_keepalive *k = lpvInBuffer;
2781 int keepalive = k->onoff ? 1 : 0;
2782 int keepidle = k->keepalivetime / 1000;
2783 int keepintvl = k->keepaliveinterval / 1000;
2785 if (!lpvInBuffer)
2787 WSASetLastError(WSAEINVAL);
2788 return SOCKET_ERROR;
2791 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
2793 fd = get_sock_fd(s, 0, NULL);
2794 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
2796 release_sock_fd(s, fd);
2797 WSASetLastError(WSAEINVAL);
2798 return SOCKET_ERROR;
2800 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
2801 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
2803 release_sock_fd(s, fd);
2804 WSASetLastError(WSAEINVAL);
2805 return SOCKET_ERROR;
2807 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
2809 release_sock_fd(s, fd);
2810 WSASetLastError(WSAEINVAL);
2811 return SOCKET_ERROR;
2813 #else
2814 FIXME("ignoring keepalive interval and timeout\n");
2815 #endif
2817 release_sock_fd(s, fd);
2818 break;
2820 case WS_SIO_UDP_CONNRESET:
2821 FIXME("WS_SIO_UDP_CONNRESET stub\n");
2822 break;
2823 default:
2824 FIXME("unsupported WS_IOCTL cmd (%08x)\n", dwIoControlCode);
2825 WSASetLastError(WSAEOPNOTSUPP);
2826 return SOCKET_ERROR;
2829 return 0;
2833 /***********************************************************************
2834 * ioctlsocket (WS2_32.10)
2836 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
2838 int fd;
2839 LONG newcmd = cmd;
2841 TRACE("socket %04lx, cmd %08x, ptr %p\n", s, cmd, argp);
2842 /* broken apps like defcon pass the argp value directly instead of a pointer to it */
2843 if(IS_INTRESOURCE(argp))
2845 SetLastError(WSAEFAULT);
2846 return SOCKET_ERROR;
2849 switch( cmd )
2851 case WS_FIONREAD:
2852 newcmd=FIONREAD;
2853 break;
2855 case WS_FIONBIO:
2856 if( _get_sock_mask(s) )
2858 /* AsyncSelect()'ed sockets are always nonblocking */
2859 if (*argp) return 0;
2860 SetLastError(WSAEINVAL);
2861 return SOCKET_ERROR;
2863 if (*argp)
2864 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
2865 else
2866 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
2867 return 0;
2869 case WS_SIOCATMARK:
2870 newcmd=SIOCATMARK;
2871 break;
2873 case WS_FIOASYNC:
2874 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
2875 SetLastError(WSAEINVAL);
2876 return SOCKET_ERROR;
2878 case SIOCGIFBRDADDR:
2879 case SIOCGIFNETMASK:
2880 case SIOCGIFADDR:
2881 /* These don't need any special handling. They are used by
2882 WsControl, and are here to suppress an unnecessary warning. */
2883 break;
2885 default:
2886 /* Netscape tries hard to use bogus ioctl 0x667e */
2887 /* FIXME: 0x667e above is ('f' << 8) | 126, and is a low word of
2888 * FIONBIO (_IOW('f', 126, u_long)), how that should be handled?
2890 WARN("\tunknown WS_IOCTL cmd (%08x)\n", cmd);
2891 break;
2894 fd = get_sock_fd( s, 0, NULL );
2895 if (fd != -1)
2897 if( ioctl(fd, newcmd, (char*)argp ) == 0 )
2899 release_sock_fd( s, fd );
2900 return 0;
2902 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2903 release_sock_fd( s, fd );
2905 return SOCKET_ERROR;
2908 /***********************************************************************
2909 * listen (WS2_32.13)
2911 int WINAPI WS_listen(SOCKET s, int backlog)
2913 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2915 TRACE("socket %04lx, backlog %d\n", s, backlog);
2916 if (fd != -1)
2918 if (listen(fd, backlog) == 0)
2920 release_sock_fd( s, fd );
2921 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
2922 FD_WINE_LISTENING,
2923 FD_CONNECT|FD_WINE_CONNECTED);
2924 return 0;
2926 SetLastError(wsaErrno());
2927 release_sock_fd( s, fd );
2929 return SOCKET_ERROR;
2932 /***********************************************************************
2933 * recv (WS2_32.16)
2935 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
2937 DWORD n, dwFlags = flags;
2938 WSABUF wsabuf;
2940 wsabuf.len = len;
2941 wsabuf.buf = buf;
2943 if ( WS2_recvfrom(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
2944 return SOCKET_ERROR;
2945 else
2946 return n;
2949 /***********************************************************************
2950 * recvfrom (WS2_32.17)
2952 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
2953 struct WS_sockaddr *from, int *fromlen)
2955 DWORD n, dwFlags = flags;
2956 WSABUF wsabuf;
2958 wsabuf.len = len;
2959 wsabuf.buf = buf;
2961 if ( WS2_recvfrom(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL) == SOCKET_ERROR )
2962 return SOCKET_ERROR;
2963 else
2964 return n;
2967 /* allocate a poll array for the corresponding fd sets */
2968 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
2969 const WS_fd_set *exceptfds, int *count_ptr )
2971 unsigned int i, j = 0, count = 0;
2972 struct pollfd *fds;
2974 if (readfds) count += readfds->fd_count;
2975 if (writefds) count += writefds->fd_count;
2976 if (exceptfds) count += exceptfds->fd_count;
2977 *count_ptr = count;
2978 if (!count) return NULL;
2979 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0])))) return NULL;
2980 if (readfds)
2981 for (i = 0; i < readfds->fd_count; i++, j++)
2983 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
2984 fds[j].events = POLLIN;
2985 fds[j].revents = 0;
2987 if (writefds)
2988 for (i = 0; i < writefds->fd_count; i++, j++)
2990 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
2991 fds[j].events = POLLOUT;
2992 fds[j].revents = 0;
2994 if (exceptfds)
2995 for (i = 0; i < exceptfds->fd_count; i++, j++)
2997 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
2998 fds[j].events = POLLHUP;
2999 fds[j].revents = 0;
3001 return fds;
3004 /* release the file descriptor obtained in fd_sets_to_poll */
3005 /* must be called with the original fd_set arrays, before calling get_poll_results */
3006 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
3007 const WS_fd_set *exceptfds, struct pollfd *fds )
3009 unsigned int i, j = 0;
3011 if (readfds)
3013 for (i = 0; i < readfds->fd_count; i++, j++)
3014 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
3016 if (writefds)
3018 for (i = 0; i < writefds->fd_count; i++, j++)
3019 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
3021 if (exceptfds)
3023 for (i = 0; i < exceptfds->fd_count; i++, j++)
3024 if (fds[j].fd != -1)
3026 /* make sure we have a real error before releasing the fd */
3027 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
3028 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
3033 /* map the poll results back into the Windows fd sets */
3034 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
3035 const struct pollfd *fds )
3037 unsigned int i, j = 0, k, total = 0;
3039 if (readfds)
3041 for (i = k = 0; i < readfds->fd_count; i++, j++)
3042 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
3043 readfds->fd_count = k;
3044 total += k;
3046 if (writefds)
3048 for (i = k = 0; i < writefds->fd_count; i++, j++)
3049 if (fds[j].revents) writefds->fd_array[k++] = writefds->fd_array[i];
3050 writefds->fd_count = k;
3051 total += k;
3053 if (exceptfds)
3055 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
3056 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
3057 exceptfds->fd_count = k;
3058 total += k;
3060 return total;
3064 /***********************************************************************
3065 * select (WS2_32.18)
3067 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
3068 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
3069 const struct WS_timeval* ws_timeout)
3071 struct pollfd *pollfds;
3072 struct timeval tv1, tv2;
3073 int torig = 0;
3074 int count, ret, timeout = -1;
3076 TRACE("read %p, write %p, excp %p timeout %p\n",
3077 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
3079 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )) && count)
3081 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
3082 return SOCKET_ERROR;
3085 if (ws_timeout)
3087 torig = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
3088 timeout = torig;
3089 gettimeofday( &tv1, 0 );
3092 while ((ret = poll( pollfds, count, timeout )) < 0)
3094 if (errno == EINTR)
3096 if (!ws_timeout) continue;
3097 gettimeofday( &tv2, 0 );
3099 tv2.tv_sec -= tv1.tv_sec;
3100 tv2.tv_usec -= tv1.tv_usec;
3101 if (tv2.tv_usec < 0)
3103 tv2.tv_usec += 1000000;
3104 tv2.tv_sec -= 1;
3107 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
3108 if (timeout <= 0) break;
3109 } else break;
3111 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
3113 if (ret == -1) SetLastError(wsaErrno());
3114 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
3115 HeapFree( GetProcessHeap(), 0, pollfds );
3116 return ret;
3119 /* helper to send completion messages for client-only i/o operation case */
3120 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
3121 ULONG Information )
3123 SERVER_START_REQ( add_fd_completion )
3125 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
3126 req->cvalue = CompletionValue;
3127 req->status = CompletionStatus;
3128 req->information = Information;
3129 wine_server_call( req );
3131 SERVER_END_REQ;
3135 /***********************************************************************
3136 * send (WS2_32.19)
3138 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
3140 DWORD n;
3141 WSABUF wsabuf;
3143 wsabuf.len = len;
3144 wsabuf.buf = (char*) buf;
3146 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
3147 return SOCKET_ERROR;
3148 else
3149 return n;
3152 /***********************************************************************
3153 * WSASend (WS2_32.72)
3155 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3156 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
3157 LPWSAOVERLAPPED lpOverlapped,
3158 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3160 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
3161 NULL, 0, lpOverlapped, lpCompletionRoutine );
3164 /***********************************************************************
3165 * WSASendDisconnect (WS2_32.73)
3167 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
3169 return WS_shutdown( s, SD_SEND );
3173 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3174 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
3175 const struct WS_sockaddr *to, int tolen,
3176 LPWSAOVERLAPPED lpOverlapped,
3177 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3179 unsigned int i, options;
3180 int n, fd, err;
3181 struct ws2_async *wsa;
3182 int totalLength = 0;
3183 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
3185 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
3186 s, lpBuffers, dwBufferCount, dwFlags,
3187 to, tolen, lpOverlapped, lpCompletionRoutine);
3189 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
3190 TRACE( "fd=%d, options=%x\n", fd, options );
3192 if ( fd == -1 ) return SOCKET_ERROR;
3194 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
3196 err = WSAEFAULT;
3197 goto error;
3200 wsa->hSocket = SOCKET2HANDLE(s);
3201 wsa->addr = (struct WS_sockaddr *)to;
3202 wsa->addrlen.val = tolen;
3203 wsa->flags = dwFlags;
3204 wsa->n_iovecs = dwBufferCount;
3205 wsa->first_iovec = 0;
3206 for ( i = 0; i < dwBufferCount; i++ )
3208 wsa->iovec[i].iov_base = lpBuffers[i].buf;
3209 wsa->iovec[i].iov_len = lpBuffers[i].len;
3210 totalLength += lpBuffers[i].len;
3213 if (!lpNumberOfBytesSent)
3215 err = WSAEFAULT;
3216 goto error;
3219 for (;;)
3221 n = WS2_send( fd, wsa );
3222 if (n != -1 || errno != EINTR) break;
3224 if (n == -1 && errno != EAGAIN)
3226 int loc_errno = errno;
3227 err = wsaErrno();
3228 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
3229 goto error;
3232 if ((lpOverlapped || lpCompletionRoutine) &&
3233 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
3235 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
3237 wsa->user_overlapped = lpOverlapped;
3238 wsa->completion_func = lpCompletionRoutine;
3239 release_sock_fd( s, fd );
3241 if (n == -1)
3243 iosb->u.Status = STATUS_PENDING;
3244 iosb->Information = 0;
3246 SERVER_START_REQ( register_async )
3248 req->type = ASYNC_TYPE_WRITE;
3249 req->async.handle = wine_server_obj_handle( wsa->hSocket );
3250 req->async.callback = wine_server_client_ptr( WS2_async_send );
3251 req->async.iosb = wine_server_client_ptr( iosb );
3252 req->async.arg = wine_server_client_ptr( wsa );
3253 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
3254 req->async.cvalue = cvalue;
3255 err = wine_server_call( req );
3257 SERVER_END_REQ;
3259 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
3260 WSASetLastError( NtStatusToWSAError( err ));
3261 return SOCKET_ERROR;
3264 iosb->u.Status = STATUS_SUCCESS;
3265 iosb->Information = n;
3266 *lpNumberOfBytesSent = n;
3267 if (!wsa->completion_func)
3269 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
3270 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
3271 HeapFree( GetProcessHeap(), 0, wsa );
3273 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
3274 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
3275 WSASetLastError(0);
3276 return 0;
3279 if ( _is_blocking(s) )
3281 /* On a blocking non-overlapped stream socket,
3282 * sending blocks until the entire buffer is sent. */
3283 DWORD timeout_start = GetTickCount();
3285 *lpNumberOfBytesSent = 0;
3287 while (wsa->first_iovec < dwBufferCount)
3289 struct pollfd pfd;
3290 int timeout = GET_SNDTIMEO(fd);
3292 if (n >= 0)
3294 *lpNumberOfBytesSent += n;
3295 while (wsa->first_iovec < dwBufferCount && wsa->iovec[wsa->first_iovec].iov_len <= n)
3296 n -= wsa->iovec[wsa->first_iovec++].iov_len;
3297 if (wsa->first_iovec >= dwBufferCount) break;
3298 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
3299 wsa->iovec[wsa->first_iovec].iov_len -= n;
3302 if (timeout != -1)
3304 timeout -= GetTickCount() - timeout_start;
3305 if (timeout < 0) timeout = 0;
3308 pfd.fd = fd;
3309 pfd.events = POLLOUT;
3311 if (!timeout || !poll( &pfd, 1, timeout ))
3313 err = WSAETIMEDOUT;
3314 goto error; /* msdn says a timeout in send is fatal */
3317 n = WS2_send( fd, wsa );
3318 if (n == -1 && errno != EAGAIN && errno != EINTR)
3320 err = wsaErrno();
3321 goto error;
3325 else /* non-blocking */
3327 if (n < totalLength)
3328 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
3329 if (n == -1)
3331 err = WSAEWOULDBLOCK;
3332 goto error;
3334 *lpNumberOfBytesSent = n;
3337 TRACE(" -> %i bytes\n", *lpNumberOfBytesSent);
3339 HeapFree( GetProcessHeap(), 0, wsa );
3340 release_sock_fd( s, fd );
3341 WSASetLastError(0);
3342 return 0;
3344 error:
3345 HeapFree( GetProcessHeap(), 0, wsa );
3346 release_sock_fd( s, fd );
3347 WARN(" -> ERROR %d\n", err);
3348 WSASetLastError(err);
3349 return SOCKET_ERROR;
3352 /***********************************************************************
3353 * WSASendTo (WS2_32.74)
3355 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3356 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
3357 const struct WS_sockaddr *to, int tolen,
3358 LPWSAOVERLAPPED lpOverlapped,
3359 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3361 return WS2_sendto( s, lpBuffers, dwBufferCount,
3362 lpNumberOfBytesSent, dwFlags,
3363 to, tolen,
3364 lpOverlapped, lpCompletionRoutine );
3367 /***********************************************************************
3368 * sendto (WS2_32.20)
3370 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
3371 const struct WS_sockaddr *to, int tolen)
3373 DWORD n;
3374 WSABUF wsabuf;
3376 wsabuf.len = len;
3377 wsabuf.buf = (char*) buf;
3379 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
3380 return SOCKET_ERROR;
3381 else
3382 return n;
3385 /***********************************************************************
3386 * setsockopt (WS2_32.21)
3388 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
3389 const char *optval, int optlen)
3391 int fd;
3392 int woptval;
3393 struct linger linger;
3394 struct timeval tval;
3396 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
3397 s, level, optname, optval, optlen);
3399 /* some broken apps pass the value directly instead of a pointer to it */
3400 if(IS_INTRESOURCE(optval))
3402 SetLastError(WSAEFAULT);
3403 return SOCKET_ERROR;
3406 switch(level)
3408 case WS_SOL_SOCKET:
3409 switch(optname)
3411 /* Some options need some conversion before they can be sent to
3412 * setsockopt. The conversions are done here, then they will fall though
3413 * to the general case. Special options that are not passed to
3414 * setsockopt follow below that.*/
3416 case WS_SO_DONTLINGER:
3417 linger.l_onoff = *((const int*)optval) ? 0: 1;
3418 linger.l_linger = 0;
3419 level = SOL_SOCKET;
3420 optname = SO_LINGER;
3421 optval = (char*)&linger;
3422 optlen = sizeof(struct linger);
3423 break;
3425 case WS_SO_LINGER:
3426 linger.l_onoff = ((LINGER*)optval)->l_onoff;
3427 linger.l_linger = ((LINGER*)optval)->l_linger;
3428 /* FIXME: what is documented behavior if SO_LINGER optval
3429 is null?? */
3430 level = SOL_SOCKET;
3431 optname = SO_LINGER;
3432 optval = (char*)&linger;
3433 optlen = sizeof(struct linger);
3434 break;
3436 case WS_SO_RCVBUF:
3437 if (*(const int*)optval < 2048)
3439 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
3440 return 0;
3442 /* Fall through */
3444 /* The options listed here don't need any special handling. Thanks to
3445 * the conversion happening above, options from there will fall through
3446 * to this, too.*/
3447 case WS_SO_ACCEPTCONN:
3448 case WS_SO_BROADCAST:
3449 case WS_SO_ERROR:
3450 case WS_SO_KEEPALIVE:
3451 case WS_SO_OOBINLINE:
3452 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
3453 * however, using it the BSD way fixes bug 8513 and seems to be what
3454 * most programmers assume, anyway */
3455 case WS_SO_REUSEADDR:
3456 case WS_SO_SNDBUF:
3457 case WS_SO_TYPE:
3458 convert_sockopt(&level, &optname);
3459 break;
3461 /* SO_DEBUG is a privileged operation, ignore it. */
3462 case WS_SO_DEBUG:
3463 TRACE("Ignoring SO_DEBUG\n");
3464 return 0;
3466 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
3467 * socket. According to MSDN, this option is silently ignored.*/
3468 case WS_SO_DONTROUTE:
3469 TRACE("Ignoring SO_DONTROUTE\n");
3470 return 0;
3472 /* Stops two sockets from being bound to the same port. Always happens
3473 * on unix systems, so just drop it. */
3474 case WS_SO_EXCLUSIVEADDRUSE:
3475 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
3476 return 0;
3478 /* SO_OPENTYPE does not require a valid socket handle. */
3479 case WS_SO_OPENTYPE:
3480 if (!optlen || optlen < sizeof(int) || !optval)
3482 SetLastError(WSAEFAULT);
3483 return SOCKET_ERROR;
3485 get_per_thread_data()->opentype = *(const int *)optval;
3486 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
3487 return 0;
3489 #ifdef SO_RCVTIMEO
3490 case WS_SO_RCVTIMEO:
3491 #endif
3492 #ifdef SO_SNDTIMEO
3493 case WS_SO_SNDTIMEO:
3494 #endif
3495 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
3496 if (optval && optlen == sizeof(UINT32)) {
3497 /* WinSock passes milliseconds instead of struct timeval */
3498 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
3499 tval.tv_sec = *(const UINT32*)optval / 1000;
3500 /* min of 500 milliseconds */
3501 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
3502 tval.tv_usec = 500000;
3503 optlen = sizeof(struct timeval);
3504 optval = (char*)&tval;
3505 } else if (optlen == sizeof(struct timeval)) {
3506 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
3507 } else {
3508 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
3509 return 0;
3511 convert_sockopt(&level, &optname);
3512 break;
3513 #endif
3515 default:
3516 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
3517 SetLastError(WSAENOPROTOOPT);
3518 return SOCKET_ERROR;
3520 break; /* case WS_SOL_SOCKET */
3522 #ifdef HAVE_IPX
3523 case NSPROTO_IPX:
3524 switch(optname)
3526 case IPX_PTYPE:
3527 fd = get_sock_fd( s, 0, NULL );
3528 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", *(const int*)optval, fd);
3530 /* We try to set the ipx type on ipx socket level. */
3531 #ifdef SOL_IPX
3532 if(setsockopt(fd, SOL_IPX, IPX_TYPE, optval, optlen) == -1)
3534 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
3535 release_sock_fd( s, fd );
3536 return SOCKET_ERROR;
3538 #else
3540 struct ipx val;
3541 /* Should we retrieve val using a getsockopt call and then
3542 * set the modified one? */
3543 val.ipx_pt = *optval;
3544 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
3546 #endif
3547 release_sock_fd( s, fd );
3548 return 0;
3550 case IPX_FILTERPTYPE:
3551 /* Sets the receive filter packet type, at the moment we don't support it */
3552 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
3553 /* Returning 0 is better for now than returning a SOCKET_ERROR */
3554 return 0;
3556 default:
3557 FIXME("opt_name:%x\n", optname);
3558 return SOCKET_ERROR;
3560 break; /* case NSPROTO_IPX */
3561 #endif
3563 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3564 case WS_IPPROTO_TCP:
3565 switch(optname)
3567 case WS_TCP_NODELAY:
3568 convert_sockopt(&level, &optname);
3569 break;
3570 default:
3571 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3572 return SOCKET_ERROR;
3574 break;
3576 case WS_IPPROTO_IP:
3577 switch(optname)
3579 case WS_IP_ADD_MEMBERSHIP:
3580 case WS_IP_DROP_MEMBERSHIP:
3581 #ifdef IP_HDRINCL
3582 case WS_IP_HDRINCL:
3583 #endif
3584 case WS_IP_MULTICAST_IF:
3585 case WS_IP_MULTICAST_LOOP:
3586 case WS_IP_MULTICAST_TTL:
3587 case WS_IP_OPTIONS:
3588 case WS_IP_TOS:
3589 case WS_IP_TTL:
3590 convert_sockopt(&level, &optname);
3591 break;
3592 case WS_IP_DONTFRAGMENT:
3593 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
3594 return 0;
3595 default:
3596 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3597 return SOCKET_ERROR;
3599 break;
3601 case WS_IPPROTO_IPV6:
3602 switch(optname)
3604 #ifdef IPV6_ADD_MEMBERSHIP
3605 case WS_IPV6_ADD_MEMBERSHIP:
3606 #endif
3607 #ifdef IPV6_DROP_MEMBERSHIP
3608 case WS_IPV6_DROP_MEMBERSHIP:
3609 #endif
3610 case WS_IPV6_MULTICAST_IF:
3611 case WS_IPV6_MULTICAST_HOPS:
3612 case WS_IPV6_MULTICAST_LOOP:
3613 case WS_IPV6_UNICAST_HOPS:
3614 case WS_IPV6_V6ONLY:
3615 convert_sockopt(&level, &optname);
3616 break;
3617 case WS_IPV6_DONTFRAG:
3618 FIXME("IPV6_DONTFRAG is silently ignored!\n");
3619 return 0;
3620 default:
3621 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
3622 return SOCKET_ERROR;
3624 break;
3626 default:
3627 WARN("Unknown level: 0x%08x\n", level);
3628 SetLastError(WSAEINVAL);
3629 return SOCKET_ERROR;
3630 } /* end switch(level) */
3632 /* avoid endianness issues if argument is a 16-bit int */
3633 if (optval && optlen < sizeof(int))
3635 woptval= *((const INT16 *) optval);
3636 optval= (char*) &woptval;
3637 optlen=sizeof(int);
3639 fd = get_sock_fd( s, 0, NULL );
3640 if (fd == -1) return SOCKET_ERROR;
3642 if (setsockopt(fd, level, optname, optval, optlen) == 0)
3644 release_sock_fd( s, fd );
3645 return 0;
3647 TRACE("Setting socket error, %d\n", wsaErrno());
3648 SetLastError(wsaErrno());
3649 release_sock_fd( s, fd );
3651 return SOCKET_ERROR;
3654 /***********************************************************************
3655 * shutdown (WS2_32.22)
3657 int WINAPI WS_shutdown(SOCKET s, int how)
3659 int fd, err = WSAENOTSOCK;
3660 unsigned int options, clear_flags = 0;
3662 fd = get_sock_fd( s, 0, &options );
3663 TRACE("socket %04lx, how %i %x\n", s, how, options );
3665 if (fd == -1)
3666 return SOCKET_ERROR;
3668 switch( how )
3670 case 0: /* drop receives */
3671 clear_flags |= FD_READ;
3672 break;
3673 case 1: /* drop sends */
3674 clear_flags |= FD_WRITE;
3675 break;
3676 case 2: /* drop all */
3677 clear_flags |= FD_READ|FD_WRITE;
3678 default:
3679 clear_flags |= FD_WINE_LISTENING;
3682 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
3684 switch ( how )
3686 case SD_RECEIVE:
3687 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3688 break;
3689 case SD_SEND:
3690 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3691 break;
3692 case SD_BOTH:
3693 default:
3694 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3695 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3696 break;
3698 if (err) goto error;
3700 else /* non-overlapped mode */
3702 if ( shutdown( fd, how ) )
3704 err = wsaErrno();
3705 goto error;
3709 release_sock_fd( s, fd );
3710 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3711 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
3712 return 0;
3714 error:
3715 release_sock_fd( s, fd );
3716 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3717 WSASetLastError( err );
3718 return SOCKET_ERROR;
3721 /***********************************************************************
3722 * socket (WS2_32.23)
3724 SOCKET WINAPI WS_socket(int af, int type, int protocol)
3726 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
3728 return WSASocketA( af, type, protocol, NULL, 0,
3729 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
3733 /***********************************************************************
3734 * gethostbyaddr (WS2_32.51)
3736 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
3738 struct WS_hostent *retval = NULL;
3739 struct hostent* host;
3741 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3742 char *extrabuf;
3743 int ebufsize=1024;
3744 struct hostent hostentry;
3745 int locerr=ENOBUFS;
3746 host = NULL;
3747 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3748 while(extrabuf) {
3749 int res = gethostbyaddr_r(addr, len, type,
3750 &hostentry, extrabuf, ebufsize, &host, &locerr);
3751 if( res != ERANGE) break;
3752 ebufsize *=2;
3753 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3755 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3756 #else
3757 EnterCriticalSection( &csWSgetXXXbyYYY );
3758 host = gethostbyaddr(addr, len, type);
3759 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3760 #endif
3761 if( host != NULL ) retval = WS_dup_he(host);
3762 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3763 HeapFree(GetProcessHeap(),0,extrabuf);
3764 #else
3765 LeaveCriticalSection( &csWSgetXXXbyYYY );
3766 #endif
3767 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
3768 return retval;
3771 /***********************************************************************
3772 * WS_get_local_ips (INTERNAL)
3774 * Returns the list of local IP addresses by going through the network
3775 * adapters and using the local routing table to sort the addresses
3776 * from highest routing priority to lowest routing priority. This
3777 * functionality is inferred from the description for obtaining local
3778 * IP addresses given in the Knowledge Base Article Q160215.
3780 * Please note that the returned hostent is only freed when the thread
3781 * closes and is replaced if another hostent is requested.
3783 static struct WS_hostent* WS_get_local_ips( char *hostname )
3785 int last_metric, numroutes = 0, i, j;
3786 PIP_ADAPTER_INFO adapters = NULL, k;
3787 struct WS_hostent *hostlist = NULL;
3788 PMIB_IPFORWARDTABLE routes = NULL;
3789 struct route *route_addrs = NULL;
3790 DWORD adap_size, route_size;
3792 /* Obtain the size of the adapter list and routing table, also allocate memory */
3793 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
3794 return NULL;
3795 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
3796 return NULL;
3797 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
3798 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
3799 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
3800 if (adapters == NULL || routes == NULL || route_addrs == NULL)
3801 goto cleanup;
3802 /* Obtain the adapter list and the full routing table */
3803 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
3804 goto cleanup;
3805 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
3806 goto cleanup;
3807 /* Store the interface associated with each route */
3808 for (i = 0; i < routes->dwNumEntries; i++)
3810 DWORD ifindex, ifmetric, exists = FALSE;
3812 if (routes->table[i].dwForwardType != MIB_IPROUTE_TYPE_DIRECT)
3813 continue;
3814 ifindex = routes->table[i].dwForwardIfIndex;
3815 ifmetric = routes->table[i].dwForwardMetric1;
3816 /* Only store the lowest valued metric for an interface */
3817 for (j = 0; j < numroutes; j++)
3819 if (route_addrs[j].interface == ifindex)
3821 if (route_addrs[j].metric > ifmetric)
3822 route_addrs[j].metric = ifmetric;
3823 exists = TRUE;
3826 if (exists)
3827 continue;
3828 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
3829 if (route_addrs == NULL)
3830 goto cleanup; /* Memory allocation error, fail gracefully */
3831 route_addrs[numroutes].interface = ifindex;
3832 route_addrs[numroutes].metric = ifmetric;
3833 /* If no IP is found in the next step (for whatever reason)
3834 * then fall back to the magic loopback address.
3836 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
3837 numroutes++;
3839 if (numroutes == 0)
3840 goto cleanup; /* No routes, fall back to the Magic IP */
3841 /* Find the IP address associated with each found interface */
3842 for (i = 0; i < numroutes; i++)
3844 for (k = adapters; k != NULL; k = k->Next)
3846 char *ip = k->IpAddressList.IpAddress.String;
3848 if (route_addrs[i].interface == k->Index)
3849 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
3852 /* Allocate a hostent and enough memory for all the IPs,
3853 * including the NULL at the end of the list.
3855 hostlist = WS_create_he(hostname, 1, numroutes+1, TRUE);
3856 if (hostlist == NULL)
3857 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
3858 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
3859 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
3860 hostlist->h_addrtype = AF_INET;
3861 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
3862 /* Reorder the entries when placing them in the host list, Windows expects
3863 * the IP list in order from highest priority to lowest (the critical thing
3864 * is that most applications expect the first IP to be the default route).
3866 last_metric = -1;
3867 for (i = 0; i < numroutes; i++)
3869 struct in_addr addr;
3870 int metric = 0xFFFF;
3872 memcpy(&addr, magic_loopback_addr, 4);
3873 for (j = 0; j < numroutes; j++)
3875 int this_metric = route_addrs[j].metric;
3877 if (this_metric > last_metric && this_metric < metric)
3879 addr = route_addrs[j].addr;
3880 metric = this_metric;
3883 last_metric = metric;
3884 (*(struct in_addr *) hostlist->h_addr_list[i]) = addr;
3887 /* Cleanup all allocated memory except the address list,
3888 * the address list is used by the calling app.
3890 cleanup:
3891 HeapFree(GetProcessHeap(), 0, route_addrs);
3892 HeapFree(GetProcessHeap(), 0, adapters);
3893 HeapFree(GetProcessHeap(), 0, routes);
3894 return hostlist;
3897 /***********************************************************************
3898 * gethostbyname (WS2_32.52)
3900 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
3902 struct WS_hostent *retval = NULL;
3903 struct hostent* host;
3904 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3905 char *extrabuf;
3906 int ebufsize=1024;
3907 struct hostent hostentry;
3908 int locerr = ENOBUFS;
3909 #endif
3910 char hostname[100];
3911 if( gethostname( hostname, 100) == -1) {
3912 SetLastError( WSAENOBUFS); /* appropriate ? */
3913 return retval;
3915 if( !name || !name[0]) {
3916 name = hostname;
3918 /* If the hostname of the local machine is requested then return the
3919 * complete list of local IP addresses */
3920 if(strcmp(name, hostname) == 0)
3921 retval = WS_get_local_ips(hostname);
3922 /* If any other hostname was requested (or the routing table lookup failed)
3923 * then return the IP found by the host OS */
3924 if(retval == NULL)
3926 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3927 host = NULL;
3928 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3929 while(extrabuf) {
3930 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
3931 if( res != ERANGE) break;
3932 ebufsize *=2;
3933 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3935 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3936 #else
3937 EnterCriticalSection( &csWSgetXXXbyYYY );
3938 host = gethostbyname(name);
3939 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3940 #endif
3941 if (host) retval = WS_dup_he(host);
3942 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3943 HeapFree(GetProcessHeap(),0,extrabuf);
3944 #else
3945 LeaveCriticalSection( &csWSgetXXXbyYYY );
3946 #endif
3948 if (retval && retval->h_addr_list[0][0] == 127 &&
3949 strcmp(name, "localhost") != 0)
3951 /* hostname != "localhost" but has loopback address. replace by our
3952 * special address.*/
3953 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
3955 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3956 return retval;
3960 /***********************************************************************
3961 * getprotobyname (WS2_32.53)
3963 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
3965 struct WS_protoent* retval = NULL;
3966 #ifdef HAVE_GETPROTOBYNAME
3967 struct protoent* proto;
3968 EnterCriticalSection( &csWSgetXXXbyYYY );
3969 if( (proto = getprotobyname(name)) != NULL )
3971 retval = WS_dup_pe(proto);
3973 else {
3974 MESSAGE("protocol %s not found; You might want to add "
3975 "this to /etc/protocols\n", debugstr_a(name) );
3976 SetLastError(WSANO_DATA);
3978 LeaveCriticalSection( &csWSgetXXXbyYYY );
3979 #endif
3980 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3981 return retval;
3985 /***********************************************************************
3986 * getprotobynumber (WS2_32.54)
3988 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
3990 struct WS_protoent* retval = NULL;
3991 #ifdef HAVE_GETPROTOBYNUMBER
3992 struct protoent* proto;
3993 EnterCriticalSection( &csWSgetXXXbyYYY );
3994 if( (proto = getprotobynumber(number)) != NULL )
3996 retval = WS_dup_pe(proto);
3998 else {
3999 MESSAGE("protocol number %d not found; You might want to add "
4000 "this to /etc/protocols\n", number );
4001 SetLastError(WSANO_DATA);
4003 LeaveCriticalSection( &csWSgetXXXbyYYY );
4004 #endif
4005 TRACE("%i ret %p\n", number, retval);
4006 return retval;
4010 /***********************************************************************
4011 * getservbyname (WS2_32.55)
4013 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
4015 struct WS_servent* retval = NULL;
4016 struct servent* serv;
4017 char *name_str;
4018 char *proto_str = NULL;
4020 if (!(name_str = strdup_lower(name))) return NULL;
4022 if (proto && *proto)
4024 if (!(proto_str = strdup_lower(proto)))
4026 HeapFree( GetProcessHeap(), 0, name_str );
4027 return NULL;
4031 EnterCriticalSection( &csWSgetXXXbyYYY );
4032 serv = getservbyname(name_str, proto_str);
4033 if( serv != NULL )
4035 retval = WS_dup_se(serv);
4037 else SetLastError(WSANO_DATA);
4038 LeaveCriticalSection( &csWSgetXXXbyYYY );
4039 HeapFree( GetProcessHeap(), 0, proto_str );
4040 HeapFree( GetProcessHeap(), 0, name_str );
4041 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
4042 return retval;
4045 /***********************************************************************
4046 * freeaddrinfo (WS2_32.@)
4048 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
4050 while (res) {
4051 struct WS_addrinfo *next;
4053 HeapFree(GetProcessHeap(),0,res->ai_canonname);
4054 HeapFree(GetProcessHeap(),0,res->ai_addr);
4055 next = res->ai_next;
4056 HeapFree(GetProcessHeap(),0,res);
4057 res = next;
4061 /* helper functions for getaddrinfo()/getnameinfo() */
4062 static int convert_aiflag_w2u(int winflags) {
4063 unsigned int i;
4064 int unixflags = 0;
4066 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
4067 if (ws_aiflag_map[i][0] & winflags) {
4068 unixflags |= ws_aiflag_map[i][1];
4069 winflags &= ~ws_aiflag_map[i][0];
4071 if (winflags)
4072 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
4073 return unixflags;
4076 static int convert_niflag_w2u(int winflags) {
4077 unsigned int i;
4078 int unixflags = 0;
4080 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
4081 if (ws_niflag_map[i][0] & winflags) {
4082 unixflags |= ws_niflag_map[i][1];
4083 winflags &= ~ws_niflag_map[i][0];
4085 if (winflags)
4086 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
4087 return unixflags;
4090 static int convert_aiflag_u2w(int unixflags) {
4091 unsigned int i;
4092 int winflags = 0;
4094 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
4095 if (ws_aiflag_map[i][1] & unixflags) {
4096 winflags |= ws_aiflag_map[i][0];
4097 unixflags &= ~ws_aiflag_map[i][1];
4099 if (unixflags) /* will warn usually */
4100 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
4101 return winflags;
4104 static int convert_eai_u2w(int unixret) {
4105 int i;
4107 for (i=0;ws_eai_map[i][0];i++)
4108 if (ws_eai_map[i][1] == unixret)
4109 return ws_eai_map[i][0];
4110 return unixret;
4113 /***********************************************************************
4114 * getaddrinfo (WS2_32.@)
4116 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
4118 #ifdef HAVE_GETADDRINFO
4119 struct addrinfo *unixaires = NULL;
4120 int result;
4121 struct addrinfo unixhints, *punixhints = NULL;
4122 CHAR *node = NULL, *serv = NULL;
4124 if (nodename)
4125 if (!(node = strdup_lower(nodename))) return WSA_NOT_ENOUGH_MEMORY;
4127 if (servname) {
4128 if (!(serv = strdup_lower(servname))) {
4129 HeapFree(GetProcessHeap(), 0, node);
4130 return WSA_NOT_ENOUGH_MEMORY;
4134 if (hints) {
4135 punixhints = &unixhints;
4137 memset(&unixhints, 0, sizeof(unixhints));
4138 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
4139 if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
4140 punixhints->ai_family = 0;
4141 else
4142 punixhints->ai_family = convert_af_w2u(hints->ai_family);
4143 if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
4144 punixhints->ai_socktype = 0;
4145 else
4146 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
4147 if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
4148 punixhints->ai_protocol = 0;
4149 else
4150 punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
4153 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
4154 result = getaddrinfo(nodename, servname, punixhints, &unixaires);
4156 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
4158 HeapFree(GetProcessHeap(), 0, node);
4159 HeapFree(GetProcessHeap(), 0, serv);
4161 if (!result) {
4162 struct addrinfo *xuai = unixaires;
4163 struct WS_addrinfo **xai = res;
4165 *xai = NULL;
4166 while (xuai) {
4167 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
4168 int len;
4170 if (!ai)
4171 goto outofmem;
4173 *xai = ai;xai = &ai->ai_next;
4174 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
4175 ai->ai_family = convert_af_u2w(xuai->ai_family);
4176 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
4177 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
4178 if (xuai->ai_canonname) {
4179 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
4180 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
4181 if (!ai->ai_canonname)
4182 goto outofmem;
4183 strcpy(ai->ai_canonname,xuai->ai_canonname);
4185 len = xuai->ai_addrlen;
4186 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
4187 if (!ai->ai_addr)
4188 goto outofmem;
4189 ai->ai_addrlen = len;
4190 do {
4191 int winlen = ai->ai_addrlen;
4193 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
4194 ai->ai_addrlen = winlen;
4195 break;
4197 len = 2*len;
4198 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
4199 if (!ai->ai_addr)
4200 goto outofmem;
4201 ai->ai_addrlen = len;
4202 } while (1);
4203 xuai = xuai->ai_next;
4205 freeaddrinfo(unixaires);
4206 } else {
4207 result = convert_eai_u2w(result);
4208 *res = NULL;
4210 return result;
4212 outofmem:
4213 if (*res) WS_freeaddrinfo(*res);
4214 if (unixaires) freeaddrinfo(unixaires);
4215 *res = NULL;
4216 return WSA_NOT_ENOUGH_MEMORY;
4217 #else
4218 FIXME("getaddrinfo() failed, not found during buildtime.\n");
4219 return EAI_FAIL;
4220 #endif
4223 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
4225 struct WS_addrinfoW *ret;
4227 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
4228 ret->ai_flags = ai->ai_flags;
4229 ret->ai_family = ai->ai_family;
4230 ret->ai_socktype = ai->ai_socktype;
4231 ret->ai_protocol = ai->ai_protocol;
4232 ret->ai_addrlen = ai->ai_addrlen;
4233 ret->ai_canonname = NULL;
4234 ret->ai_addr = NULL;
4235 ret->ai_next = NULL;
4236 if (ai->ai_canonname)
4238 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
4239 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
4241 HeapFree(GetProcessHeap(), 0, ret);
4242 return NULL;
4244 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
4246 if (ai->ai_addr)
4248 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
4250 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
4251 HeapFree(GetProcessHeap(), 0, ret);
4252 return NULL;
4254 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
4256 return ret;
4259 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
4261 struct WS_addrinfoW *ret, *infoW;
4263 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
4264 while (info->ai_next)
4266 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
4268 FreeAddrInfoW(ret);
4269 return NULL;
4271 infoW = infoW->ai_next;
4272 info = info->ai_next;
4274 return ret;
4277 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
4279 struct WS_addrinfo *ret;
4281 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
4282 ret->ai_flags = ai->ai_flags;
4283 ret->ai_family = ai->ai_family;
4284 ret->ai_socktype = ai->ai_socktype;
4285 ret->ai_protocol = ai->ai_protocol;
4286 ret->ai_addrlen = ai->ai_addrlen;
4287 ret->ai_canonname = NULL;
4288 ret->ai_addr = NULL;
4289 ret->ai_next = NULL;
4290 if (ai->ai_canonname)
4292 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
4293 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
4295 HeapFree(GetProcessHeap(), 0, ret);
4296 return NULL;
4298 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
4300 if (ai->ai_addr)
4302 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
4304 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
4305 HeapFree(GetProcessHeap(), 0, ret);
4306 return NULL;
4308 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
4310 return ret;
4313 /***********************************************************************
4314 * GetAddrInfoW (WS2_32.@)
4316 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
4318 int ret, len;
4319 char *nodenameA, *servnameA = NULL;
4320 struct WS_addrinfo *resA, *hintsA = NULL;
4322 if (!nodename) return WSAHOST_NOT_FOUND;
4324 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
4325 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
4326 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
4328 if (servname)
4330 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
4331 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
4333 HeapFree(GetProcessHeap(), 0, nodenameA);
4334 return EAI_MEMORY;
4336 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
4339 if (hints) hintsA = addrinfo_WtoA(hints);
4340 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
4341 WS_freeaddrinfo(hintsA);
4343 if (!ret)
4345 *res = addrinfo_list_AtoW(resA);
4346 WS_freeaddrinfo(resA);
4349 HeapFree(GetProcessHeap(), 0, nodenameA);
4350 HeapFree(GetProcessHeap(), 0, servnameA);
4351 return ret;
4354 /***********************************************************************
4355 * FreeAddrInfoW (WS2_32.@)
4357 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
4359 while (ai)
4361 ADDRINFOW *next;
4362 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
4363 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
4364 next = ai->ai_next;
4365 HeapFree(GetProcessHeap(), 0, ai);
4366 ai = next;
4370 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
4371 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
4373 #ifdef HAVE_GETNAMEINFO
4374 int ret;
4375 union generic_unix_sockaddr sa_u;
4376 unsigned int size;
4378 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
4379 serv, servlen, flags);
4381 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
4382 if (!size)
4384 WSASetLastError(WSAEFAULT);
4385 return WSA_NOT_ENOUGH_MEMORY;
4387 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
4388 return convert_eai_u2w(ret);
4389 #else
4390 FIXME("getnameinfo() failed, not found during buildtime.\n");
4391 return EAI_FAIL;
4392 #endif
4395 /***********************************************************************
4396 * getservbyport (WS2_32.56)
4398 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
4400 struct WS_servent* retval = NULL;
4401 #ifdef HAVE_GETSERVBYPORT
4402 struct servent* serv;
4403 char *proto_str = NULL;
4405 if (proto && *proto)
4407 if (!(proto_str = strdup_lower(proto))) return NULL;
4409 EnterCriticalSection( &csWSgetXXXbyYYY );
4410 if( (serv = getservbyport(port, proto_str)) != NULL ) {
4411 retval = WS_dup_se(serv);
4413 else SetLastError(WSANO_DATA);
4414 LeaveCriticalSection( &csWSgetXXXbyYYY );
4415 HeapFree( GetProcessHeap(), 0, proto_str );
4416 #endif
4417 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
4418 return retval;
4422 /***********************************************************************
4423 * gethostname (WS2_32.57)
4425 int WINAPI WS_gethostname(char *name, int namelen)
4427 TRACE("name %p, len %d\n", name, namelen);
4429 if (gethostname(name, namelen) == 0)
4431 TRACE("<- '%s'\n", name);
4432 return 0;
4434 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
4435 TRACE("<- ERROR !\n");
4436 return SOCKET_ERROR;
4440 /* ------------------------------------- Windows sockets extensions -- *
4442 * ------------------------------------------------------------------- */
4444 /***********************************************************************
4445 * WSAEnumNetworkEvents (WS2_32.36)
4447 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
4449 int ret;
4450 int i;
4451 int errors[FD_MAX_EVENTS];
4453 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
4455 SERVER_START_REQ( get_socket_event )
4457 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
4458 req->service = TRUE;
4459 req->c_event = wine_server_obj_handle( hEvent );
4460 wine_server_set_reply( req, errors, sizeof(errors) );
4461 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
4463 SERVER_END_REQ;
4464 if (!ret)
4466 for (i = 0; i < FD_MAX_EVENTS; i++)
4467 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
4468 return 0;
4470 SetLastError(WSAEINVAL);
4471 return SOCKET_ERROR;
4474 /***********************************************************************
4475 * WSAEventSelect (WS2_32.39)
4477 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
4479 int ret;
4481 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
4483 SERVER_START_REQ( set_socket_event )
4485 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
4486 req->mask = lEvent;
4487 req->event = wine_server_obj_handle( hEvent );
4488 req->window = 0;
4489 req->msg = 0;
4490 ret = wine_server_call( req );
4492 SERVER_END_REQ;
4493 if (!ret) return 0;
4494 SetLastError(WSAEINVAL);
4495 return SOCKET_ERROR;
4498 /**********************************************************************
4499 * WSAGetOverlappedResult (WS2_32.40)
4501 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
4502 LPDWORD lpcbTransfer, BOOL fWait,
4503 LPDWORD lpdwFlags )
4505 NTSTATUS status;
4507 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
4508 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
4510 if ( lpOverlapped == NULL )
4512 ERR( "Invalid pointer\n" );
4513 WSASetLastError(WSA_INVALID_PARAMETER);
4514 return FALSE;
4517 status = lpOverlapped->Internal;
4518 if (status == STATUS_PENDING)
4520 if (!fWait)
4522 SetLastError( WSA_IO_INCOMPLETE );
4523 return FALSE;
4526 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
4527 INFINITE ) == WAIT_FAILED)
4528 return FALSE;
4529 status = lpOverlapped->Internal;
4532 if ( lpcbTransfer )
4533 *lpcbTransfer = lpOverlapped->InternalHigh;
4535 if ( lpdwFlags )
4536 *lpdwFlags = lpOverlapped->u.s.Offset;
4538 if (status) SetLastError( RtlNtStatusToDosError(status) );
4539 return !status;
4543 /***********************************************************************
4544 * WSAAsyncSelect (WS2_32.101)
4546 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
4548 int ret;
4550 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
4552 SERVER_START_REQ( set_socket_event )
4554 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
4555 req->mask = lEvent;
4556 req->event = 0;
4557 req->window = wine_server_user_handle( hWnd );
4558 req->msg = uMsg;
4559 ret = wine_server_call( req );
4561 SERVER_END_REQ;
4562 if (!ret) return 0;
4563 SetLastError(WSAEINVAL);
4564 return SOCKET_ERROR;
4567 /***********************************************************************
4568 * WSACreateEvent (WS2_32.31)
4571 WSAEVENT WINAPI WSACreateEvent(void)
4573 /* Create a manual-reset event, with initial state: unsignaled */
4574 TRACE("\n");
4576 return CreateEventW(NULL, TRUE, FALSE, NULL);
4579 /***********************************************************************
4580 * WSACloseEvent (WS2_32.29)
4583 BOOL WINAPI WSACloseEvent(WSAEVENT event)
4585 TRACE ("event=%p\n", event);
4587 return CloseHandle(event);
4590 /***********************************************************************
4591 * WSASocketA (WS2_32.78)
4594 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
4595 LPWSAPROTOCOL_INFOA lpProtocolInfo,
4596 GROUP g, DWORD dwFlags)
4598 INT len;
4599 WSAPROTOCOL_INFOW info;
4601 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
4602 af, type, protocol, lpProtocolInfo, g, dwFlags);
4604 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
4606 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
4607 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
4608 info.szProtocol, WSAPROTOCOL_LEN + 1);
4610 if (!len)
4612 WSASetLastError( WSAEINVAL);
4613 return SOCKET_ERROR;
4616 return WSASocketW(af, type, protocol, &info, g, dwFlags);
4619 /***********************************************************************
4620 * WSASocketW (WS2_32.79)
4623 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
4624 LPWSAPROTOCOL_INFOW lpProtocolInfo,
4625 GROUP g, DWORD dwFlags)
4627 SOCKET ret;
4630 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
4631 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
4634 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
4635 af, type, protocol, lpProtocolInfo, g, dwFlags );
4637 /* hack for WSADuplicateSocket */
4638 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
4639 ret = lpProtocolInfo->dwCatalogEntryId;
4640 TRACE("\tgot duplicate %04lx\n", ret);
4641 return ret;
4644 /* convert the socket family and type */
4645 af = convert_af_w2u(af);
4646 type = convert_socktype_w2u(type);
4648 if (lpProtocolInfo)
4650 if (af == FROM_PROTOCOL_INFO)
4651 af = lpProtocolInfo->iAddressFamily;
4652 if (type == FROM_PROTOCOL_INFO)
4653 type = lpProtocolInfo->iSocketType;
4654 if (protocol == FROM_PROTOCOL_INFO)
4655 protocol = lpProtocolInfo->iProtocol;
4658 if ( af == AF_UNSPEC) /* did they not specify the address family? */
4659 switch(protocol)
4661 case IPPROTO_TCP:
4662 if (type == SOCK_STREAM) { af = AF_INET; break; }
4663 case IPPROTO_UDP:
4664 if (type == SOCK_DGRAM) { af = AF_INET; break; }
4665 default: SetLastError(WSAEPROTOTYPE); return INVALID_SOCKET;
4668 SERVER_START_REQ( create_socket )
4670 req->family = af;
4671 req->type = type;
4672 req->protocol = protocol;
4673 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
4674 req->attributes = OBJ_INHERIT;
4675 req->flags = dwFlags;
4676 set_error( wine_server_call( req ) );
4677 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
4679 SERVER_END_REQ;
4680 if (ret)
4682 TRACE("\tcreated %04lx\n", ret );
4683 return ret;
4686 if (GetLastError() == WSAEACCES) /* raw socket denied */
4688 if (type == SOCK_RAW)
4689 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
4690 else
4691 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
4692 SetLastError(WSAESOCKTNOSUPPORT);
4695 WARN("\t\tfailed!\n");
4696 return INVALID_SOCKET;
4699 /***********************************************************************
4700 * WSAJoinLeaf (WS2_32.58)
4703 SOCKET WINAPI WSAJoinLeaf(
4704 SOCKET s,
4705 const struct WS_sockaddr *addr,
4706 int addrlen,
4707 LPWSABUF lpCallerData,
4708 LPWSABUF lpCalleeData,
4709 LPQOS lpSQOS,
4710 LPQOS lpGQOS,
4711 DWORD dwFlags)
4713 FIXME("stub.\n");
4714 return INVALID_SOCKET;
4717 /***********************************************************************
4718 * __WSAFDIsSet (WS2_32.151)
4720 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
4722 int i = set->fd_count;
4724 TRACE("(%ld,%p(%i))\n", s, set, i);
4726 while (i--)
4727 if (set->fd_array[i] == s) return 1;
4728 return 0;
4731 /***********************************************************************
4732 * WSAIsBlocking (WS2_32.114)
4734 BOOL WINAPI WSAIsBlocking(void)
4736 /* By default WinSock should set all its sockets to non-blocking mode
4737 * and poll in PeekMessage loop when processing "blocking" ones. This
4738 * function is supposed to tell if the program is in this loop. Our
4739 * blocking calls are truly blocking so we always return FALSE.
4741 * Note: It is allowed to call this function without prior WSAStartup().
4744 TRACE("\n");
4745 return FALSE;
4748 /***********************************************************************
4749 * WSACancelBlockingCall (WS2_32.113)
4751 INT WINAPI WSACancelBlockingCall(void)
4753 TRACE("\n");
4754 return 0;
4757 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
4759 FIXME("How was this called?\n");
4760 return x();
4764 /***********************************************************************
4765 * WSASetBlockingHook (WS2_32.109)
4767 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
4769 FARPROC prev = blocking_hook;
4770 blocking_hook = lpBlockFunc;
4771 TRACE("hook %p\n", lpBlockFunc);
4772 return prev;
4776 /***********************************************************************
4777 * WSAUnhookBlockingHook (WS2_32.110)
4779 INT WINAPI WSAUnhookBlockingHook(void)
4781 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
4782 return 0;
4786 /* ----------------------------------- end of API stuff */
4788 /* ----------------------------------- helper functions -
4790 * TODO: Merge WS_dup_..() stuff into one function that
4791 * would operate with a generic structure containing internal
4792 * pointers (via a template of some kind).
4795 static int list_size(char** l, int item_size)
4797 int i,j = 0;
4798 if(l)
4799 { for(i=0;l[i];i++)
4800 j += (item_size) ? item_size : strlen(l[i]) + 1;
4801 j += (i + 1) * sizeof(char*); }
4802 return j;
4805 static int list_dup(char** l_src, char** l_to, int item_size)
4807 char *p;
4808 int i;
4810 for (i = 0; l_src[i]; i++) ;
4811 p = (char *)(l_to + i + 1);
4812 for (i = 0; l_src[i]; i++)
4814 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
4815 memcpy(p, l_src[i], count);
4816 l_to[i] = p;
4817 p += count;
4819 l_to[i] = NULL;
4820 return p - (char *)l_to;
4823 /* ----- hostent */
4825 /* create a hostent entry
4827 * Creates the entry with enough memory for the name, aliases
4828 * addresses, and the address pointers. Also copies the name
4829 * and sets up all the pointers. If "fill_addresses" is set then
4830 * sufficient memory for the addresses is also allocated and the
4831 * address pointers are set to this memory.
4833 * NOTE: The alias and address lists must be allocated with room
4834 * for the NULL item terminating the list. This is true even if
4835 * the list has no items ("aliases" and "addresses" must be
4836 * at least "1", a truly empty list is invalid).
4838 static struct WS_hostent *WS_create_he(char *name, int aliases, int addresses, int fill_addresses)
4840 struct WS_hostent *p_to;
4841 char *p;
4843 int size = (sizeof(struct WS_hostent) +
4844 strlen(name) + 1 +
4845 sizeof(char *)*aliases +
4846 sizeof(char *)*addresses);
4848 /* Allocate enough memory for the addresses */
4849 if (fill_addresses)
4850 size += sizeof(struct in_addr)*addresses;
4852 if (!(p_to = check_buffer_he(size))) return NULL;
4853 memset(p_to, 0, size);
4855 p = (char *)(p_to + 1);
4856 p_to->h_name = p;
4857 strcpy(p, name);
4858 p += strlen(p) + 1;
4860 p_to->h_aliases = (char **)p;
4861 p += sizeof(char *)*aliases;
4862 p_to->h_addr_list = (char **)p;
4863 p += sizeof(char *)*addresses;
4864 if (fill_addresses)
4866 int i;
4868 /* NOTE: h_aliases must be filled in manually, leave these
4869 * pointers NULL (already set to NULL by memset earlier).
4872 /* Fill in the list of address pointers */
4873 for (i = 0; i < addresses; i++)
4874 p_to->h_addr_list[i] = (p += sizeof(struct in_addr));
4875 p += sizeof(struct in_addr);
4877 return p_to;
4880 /* duplicate hostent entry
4881 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
4882 * Ditto for protoent and servent.
4884 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
4886 int addresses = list_size(p_he->h_addr_list, p_he->h_length);
4887 int aliases = list_size(p_he->h_aliases, 0);
4888 struct WS_hostent *p_to;
4890 p_to = WS_create_he(p_he->h_name, aliases, addresses, FALSE);
4892 if (!p_to) return NULL;
4893 p_to->h_addrtype = p_he->h_addrtype;
4894 p_to->h_length = p_he->h_length;
4896 list_dup(p_he->h_aliases, p_to->h_aliases, 0);
4897 list_dup(p_he->h_addr_list, p_to->h_addr_list, p_he->h_length);
4898 return p_to;
4901 /* ----- protoent */
4903 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
4905 char *p;
4906 struct WS_protoent *p_to;
4908 int size = (sizeof(*p_pe) +
4909 strlen(p_pe->p_name) + 1 +
4910 list_size(p_pe->p_aliases, 0));
4912 if (!(p_to = check_buffer_pe(size))) return NULL;
4913 p_to->p_proto = p_pe->p_proto;
4915 p = (char *)(p_to + 1);
4916 p_to->p_name = p;
4917 strcpy(p, p_pe->p_name);
4918 p += strlen(p) + 1;
4920 p_to->p_aliases = (char **)p;
4921 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
4922 return p_to;
4925 /* ----- servent */
4927 static struct WS_servent *WS_dup_se(const struct servent* p_se)
4929 char *p;
4930 struct WS_servent *p_to;
4932 int size = (sizeof(*p_se) +
4933 strlen(p_se->s_proto) + 1 +
4934 strlen(p_se->s_name) + 1 +
4935 list_size(p_se->s_aliases, 0));
4937 if (!(p_to = check_buffer_se(size))) return NULL;
4938 p_to->s_port = p_se->s_port;
4940 p = (char *)(p_to + 1);
4941 p_to->s_name = p;
4942 strcpy(p, p_se->s_name);
4943 p += strlen(p) + 1;
4945 p_to->s_proto = p;
4946 strcpy(p, p_se->s_proto);
4947 p += strlen(p) + 1;
4949 p_to->s_aliases = (char **)p;
4950 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
4951 return p_to;
4955 /***********************************************************************
4956 * WSARecv (WS2_32.67)
4958 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4959 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
4960 LPWSAOVERLAPPED lpOverlapped,
4961 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
4963 return WS2_recvfrom(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
4964 NULL, NULL, lpOverlapped, lpCompletionRoutine);
4967 static int WS2_recvfrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4968 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
4969 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
4970 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4973 unsigned int i, options;
4974 int n, fd, err;
4975 struct ws2_async *wsa;
4976 DWORD timeout_start = GetTickCount();
4977 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
4979 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
4980 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
4981 (lpFromlen ? *lpFromlen : -1),
4982 lpOverlapped, lpCompletionRoutine);
4984 fd = get_sock_fd( s, FILE_READ_DATA, &options );
4985 TRACE( "fd=%d, options=%x\n", fd, options );
4987 if (fd == -1) return SOCKET_ERROR;
4989 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
4991 err = WSAEFAULT;
4992 goto error;
4995 wsa->hSocket = SOCKET2HANDLE(s);
4996 wsa->flags = *lpFlags;
4997 wsa->addr = lpFrom;
4998 wsa->addrlen.ptr = lpFromlen;
4999 wsa->n_iovecs = dwBufferCount;
5000 wsa->first_iovec = 0;
5001 for (i = 0; i < dwBufferCount; i++)
5003 /* check buffer first to trigger write watches */
5004 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
5006 err = WSAEFAULT;
5007 goto error;
5009 wsa->iovec[i].iov_base = lpBuffers[i].buf;
5010 wsa->iovec[i].iov_len = lpBuffers[i].len;
5013 for (;;)
5015 n = WS2_recv( fd, wsa );
5016 if (n == -1)
5018 if (errno == EINTR) continue;
5019 if (errno != EAGAIN)
5021 int loc_errno = errno;
5022 err = wsaErrno();
5023 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
5024 goto error;
5027 else
5028 *lpNumberOfBytesRecvd = n;
5030 if ((lpOverlapped || lpCompletionRoutine) &&
5031 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
5033 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
5035 wsa->user_overlapped = lpOverlapped;
5036 wsa->completion_func = lpCompletionRoutine;
5037 release_sock_fd( s, fd );
5039 if (n == -1)
5041 iosb->u.Status = STATUS_PENDING;
5042 iosb->Information = 0;
5044 SERVER_START_REQ( register_async )
5046 req->type = ASYNC_TYPE_READ;
5047 req->async.handle = wine_server_obj_handle( wsa->hSocket );
5048 req->async.callback = wine_server_client_ptr( WS2_async_recv );
5049 req->async.iosb = wine_server_client_ptr( iosb );
5050 req->async.arg = wine_server_client_ptr( wsa );
5051 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
5052 req->async.cvalue = cvalue;
5053 err = wine_server_call( req );
5055 SERVER_END_REQ;
5057 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
5058 WSASetLastError( NtStatusToWSAError( err ));
5059 return SOCKET_ERROR;
5062 iosb->u.Status = STATUS_SUCCESS;
5063 iosb->Information = n;
5064 if (!wsa->completion_func)
5066 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
5067 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
5068 HeapFree( GetProcessHeap(), 0, wsa );
5070 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
5071 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
5072 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5073 return 0;
5076 if (n != -1) break;
5078 if ( _is_blocking(s) )
5080 struct pollfd pfd;
5081 int timeout = GET_RCVTIMEO(fd);
5082 if (timeout != -1)
5084 timeout -= GetTickCount() - timeout_start;
5085 if (timeout < 0) timeout = 0;
5088 pfd.fd = fd;
5089 pfd.events = POLLIN;
5090 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
5092 if (!timeout || !poll( &pfd, 1, timeout ))
5094 err = WSAETIMEDOUT;
5095 /* a timeout is not fatal */
5096 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5097 goto error;
5100 else
5102 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5103 err = WSAEWOULDBLOCK;
5104 goto error;
5108 TRACE(" -> %i bytes\n", n);
5109 HeapFree( GetProcessHeap(), 0, wsa );
5110 release_sock_fd( s, fd );
5111 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5113 return 0;
5115 error:
5116 HeapFree( GetProcessHeap(), 0, wsa );
5117 release_sock_fd( s, fd );
5118 WARN(" -> ERROR %d\n", err);
5119 WSASetLastError( err );
5120 return SOCKET_ERROR;
5123 /***********************************************************************
5124 * WSARecvFrom (WS2_32.69)
5126 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5127 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
5128 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
5129 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5132 return WS2_recvfrom( s, lpBuffers, dwBufferCount,
5133 lpNumberOfBytesRecvd, lpFlags,
5134 lpFrom, lpFromlen,
5135 lpOverlapped, lpCompletionRoutine );
5138 /***********************************************************************
5139 * WSCInstallProvider (WS2_32.88)
5141 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
5142 LPCWSTR lpszProviderDllPath,
5143 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
5144 DWORD dwNumberOfEntries,
5145 LPINT lpErrno )
5147 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
5148 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
5149 dwNumberOfEntries, lpErrno);
5150 *lpErrno = 0;
5151 return 0;
5155 /***********************************************************************
5156 * WSCDeinstallProvider (WS2_32.83)
5158 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
5160 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
5161 *lpErrno = 0;
5162 return 0;
5166 /***********************************************************************
5167 * WSAAccept (WS2_32.26)
5169 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
5170 LPCONDITIONPROC lpfnCondition, DWORD dwCallbackData)
5173 int ret = 0, size = 0;
5174 WSABUF CallerId, CallerData, CalleeId, CalleeData;
5175 /* QOS SQOS, GQOS; */
5176 GROUP g;
5177 SOCKET cs;
5178 SOCKADDR src_addr, dst_addr;
5180 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %d\n",
5181 s, addr, addrlen, lpfnCondition, dwCallbackData);
5184 size = sizeof(src_addr);
5185 cs = WS_accept(s, &src_addr, &size);
5187 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
5189 if (!lpfnCondition) return cs;
5191 CallerId.buf = (char *)&src_addr;
5192 CallerId.len = sizeof(src_addr);
5194 CallerData.buf = NULL;
5195 CallerData.len = 0;
5197 WS_getsockname(cs, &dst_addr, &size);
5199 CalleeId.buf = (char *)&dst_addr;
5200 CalleeId.len = sizeof(dst_addr);
5203 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
5204 &CalleeId, &CalleeData, &g, dwCallbackData);
5206 switch (ret)
5208 case CF_ACCEPT:
5209 if (addr && addrlen)
5210 addr = memcpy(addr, &src_addr, (*addrlen > size) ? size : *addrlen );
5211 return cs;
5212 case CF_DEFER:
5213 SERVER_START_REQ( set_socket_deferred )
5215 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5216 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
5217 if ( !wine_server_call_err ( req ) )
5219 SetLastError( WSATRY_AGAIN );
5220 WS_closesocket( cs );
5223 SERVER_END_REQ;
5224 return SOCKET_ERROR;
5225 case CF_REJECT:
5226 WS_closesocket(cs);
5227 SetLastError(WSAECONNREFUSED);
5228 return SOCKET_ERROR;
5229 default:
5230 FIXME("Unknown return type from Condition function\n");
5231 SetLastError(WSAENOTSOCK);
5232 return SOCKET_ERROR;
5236 /***********************************************************************
5237 * WSADuplicateSocketA (WS2_32.32)
5239 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
5241 HANDLE hProcess;
5243 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
5244 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
5245 /* FIXME: WS_getsockopt(s, WS_SOL_SOCKET, SO_PROTOCOL_INFO, lpProtocolInfo, sizeof(*lpProtocolInfo)); */
5246 /* I don't know what the real Windoze does next, this is a hack */
5247 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
5248 * the target use the global duplicate, or we could copy a reference to us to the structure
5249 * and let the target duplicate it from us, but let's do it as simple as possible */
5250 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
5251 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
5252 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
5253 0, FALSE, DUPLICATE_SAME_ACCESS);
5254 CloseHandle(hProcess);
5255 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
5256 return 0;
5259 /***********************************************************************
5260 * WSADuplicateSocketW (WS2_32.33)
5262 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
5264 HANDLE hProcess;
5266 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
5268 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
5269 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
5270 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
5271 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
5272 0, FALSE, DUPLICATE_SAME_ACCESS);
5273 CloseHandle(hProcess);
5274 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
5275 return 0;
5278 /***********************************************************************
5279 * WSAInstallServiceClassA (WS2_32.48)
5281 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
5283 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
5284 WSASetLastError(WSAEACCES);
5285 return SOCKET_ERROR;
5288 /***********************************************************************
5289 * WSAInstallServiceClassW (WS2_32.49)
5291 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
5293 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
5294 WSASetLastError(WSAEACCES);
5295 return SOCKET_ERROR;
5298 /***********************************************************************
5299 * WSARemoveServiceClass (WS2_32.70)
5301 int WINAPI WSARemoveServiceClass(LPGUID info)
5303 FIXME("Request to remove service %p\n",info);
5304 WSASetLastError(WSATYPE_NOT_FOUND);
5305 return SOCKET_ERROR;
5308 /***********************************************************************
5309 * inet_ntop (WS2_32.@)
5311 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
5313 #ifdef HAVE_INET_NTOP
5314 struct WS_in6_addr *in6;
5315 struct WS_in_addr *in;
5316 PCSTR pdst;
5318 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
5319 if (!buffer)
5321 WSASetLastError( STATUS_INVALID_PARAMETER );
5322 return NULL;
5325 switch (family)
5327 case WS_AF_INET:
5329 in = addr;
5330 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
5331 break;
5333 case WS_AF_INET6:
5335 in6 = addr;
5336 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
5337 break;
5339 default:
5340 WSASetLastError( WSAEAFNOSUPPORT );
5341 return NULL;
5344 if (!pdst) WSASetLastError( STATUS_INVALID_PARAMETER );
5345 return pdst;
5346 #else
5347 FIXME( "not supported on this platform\n" );
5348 WSASetLastError( WSAEAFNOSUPPORT );
5349 return NULL;
5350 #endif
5353 /***********************************************************************
5354 * WSAStringToAddressA (WS2_32.80)
5356 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
5357 INT AddressFamily,
5358 LPWSAPROTOCOL_INFOA lpProtocolInfo,
5359 LPSOCKADDR lpAddress,
5360 LPINT lpAddressLength)
5362 INT res=0;
5363 LPSTR workBuffer=NULL,ptrPort;
5365 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
5366 lpProtocolInfo, lpAddress, lpAddressLength );
5368 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
5370 if (!AddressString)
5372 WSASetLastError(WSAEINVAL);
5373 return SOCKET_ERROR;
5376 if (lpProtocolInfo)
5377 FIXME("ProtocolInfo not implemented.\n");
5379 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
5380 strlen(AddressString) + 1);
5381 if (!workBuffer)
5383 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5384 return SOCKET_ERROR;
5387 strcpy(workBuffer, AddressString);
5389 switch(AddressFamily)
5391 case WS_AF_INET:
5393 struct in_addr inetaddr;
5395 /* If lpAddressLength is too small, tell caller the size we need */
5396 if (*lpAddressLength < sizeof(SOCKADDR_IN))
5398 *lpAddressLength = sizeof(SOCKADDR_IN);
5399 res = WSAEFAULT;
5400 break;
5402 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
5404 ((LPSOCKADDR_IN)lpAddress)->sin_family = AF_INET;
5406 ptrPort = strchr(workBuffer, ':');
5407 if(ptrPort)
5409 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
5410 *ptrPort = '\0';
5412 else
5414 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
5417 if(inet_aton(workBuffer, &inetaddr) > 0)
5419 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
5420 res = 0;
5422 else
5423 res = WSAEINVAL;
5425 break;
5428 case WS_AF_INET6:
5430 struct in6_addr inetaddr;
5431 /* If lpAddressLength is too small, tell caller the size we need */
5432 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
5434 *lpAddressLength = sizeof(SOCKADDR_IN6);
5435 res = WSAEFAULT;
5436 break;
5438 #ifdef HAVE_INET_PTON
5439 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
5441 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
5443 /* This one is a bit tricky. An IPv6 address contains colons, so the
5444 * check from IPv4 doesn't work like that. However, IPv6 addresses that
5445 * contain a port are written with braces like [fd12:3456:7890::1]:12345
5446 * so what we will do is to look for ']', check if the next char is a
5447 * colon, and if it is, parse the port as in IPv4. */
5449 ptrPort = strchr(workBuffer, ']');
5450 if(ptrPort && *(++ptrPort) == ':')
5452 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
5453 *ptrPort = '\0';
5455 else
5457 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
5460 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
5462 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
5463 sizeof(struct in6_addr));
5464 res = 0;
5466 else
5467 #endif /* HAVE_INET_PTON */
5468 res = WSAEINVAL;
5470 break;
5472 default:
5473 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
5474 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
5475 res = WSAEINVAL;
5478 HeapFree(GetProcessHeap(), 0, workBuffer);
5480 if (!res) return 0;
5481 WSASetLastError(res);
5482 return SOCKET_ERROR;
5485 /***********************************************************************
5486 * WSAStringToAddressW (WS2_32.81)
5488 * Does anybody know if this functions allows to use hebrew/arabic/chinese... digits?
5489 * If this should be the case, it would be required to map these digits
5490 * to Unicode digits (0-9) using FoldString first.
5492 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
5493 INT AddressFamily,
5494 LPWSAPROTOCOL_INFOW lpProtocolInfo,
5495 LPSOCKADDR lpAddress,
5496 LPINT lpAddressLength)
5498 INT sBuffer,res=0;
5499 LPSTR workBuffer=NULL;
5500 WSAPROTOCOL_INFOA infoA;
5501 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
5503 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
5504 lpAddress, lpAddressLength );
5506 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
5508 /* if ProtocolInfo is available - convert to ANSI variant */
5509 if (lpProtocolInfo)
5511 lpProtoInfoA = &infoA;
5512 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
5514 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
5515 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
5517 WSASetLastError( WSAEINVAL);
5518 return SOCKET_ERROR;
5522 if (AddressString)
5524 /* Translate AddressString to ANSI code page - assumes that only
5525 standard digits 0-9 are used with this API call */
5526 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
5527 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
5529 if (workBuffer)
5531 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
5532 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
5533 lpAddress,lpAddressLength);
5534 HeapFree( GetProcessHeap(), 0, workBuffer );
5535 return res;
5537 else
5538 res = WSA_NOT_ENOUGH_MEMORY;
5540 else
5541 res = WSAEINVAL;
5543 WSASetLastError(res);
5544 return SOCKET_ERROR;
5547 /***********************************************************************
5548 * WSAAddressToStringA (WS2_32.27)
5550 * See WSAAddressToStringW
5552 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
5553 LPWSAPROTOCOL_INFOA info, LPSTR string,
5554 LPDWORD lenstr )
5556 DWORD size;
5557 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
5558 CHAR *p;
5560 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
5562 if (!sockaddr) return SOCKET_ERROR;
5563 if (!string || !lenstr) return SOCKET_ERROR;
5565 switch(sockaddr->sa_family)
5567 case WS_AF_INET:
5568 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
5569 sprintf( buffer, "%u.%u.%u.%u:%u",
5570 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
5571 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
5572 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
5573 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
5574 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
5576 p = strchr( buffer, ':' );
5577 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
5578 break;
5580 case WS_AF_INET6:
5582 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
5584 buffer[0] = 0;
5585 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
5586 if ((sockaddr6->sin6_port))
5587 strcpy(buffer, "[");
5588 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
5590 WSASetLastError(WSAEINVAL);
5591 return SOCKET_ERROR;
5593 if ((sockaddr6->sin6_scope_id))
5594 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
5595 if ((sockaddr6->sin6_port))
5596 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
5597 break;
5600 default:
5601 WSASetLastError(WSAEINVAL);
5602 return SOCKET_ERROR;
5605 size = strlen( buffer ) + 1;
5607 if (*lenstr < size)
5609 *lenstr = size;
5610 WSASetLastError(WSAEFAULT);
5611 return SOCKET_ERROR;
5614 *lenstr = size;
5615 strcpy( string, buffer );
5616 return 0;
5619 /***********************************************************************
5620 * WSAAddressToStringW (WS2_32.28)
5622 * Convert a sockaddr address into a readable address string.
5624 * PARAMS
5625 * sockaddr [I] Pointer to a sockaddr structure.
5626 * len [I] Size of the sockaddr structure.
5627 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
5628 * string [I/O] Pointer to a buffer to receive the address string.
5629 * lenstr [I/O] Size of the receive buffer in WCHARs.
5631 * RETURNS
5632 * Success: 0
5633 * Failure: SOCKET_ERROR
5635 * NOTES
5636 * The 'info' parameter is ignored.
5638 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
5639 LPWSAPROTOCOL_INFOW info, LPWSTR string,
5640 LPDWORD lenstr )
5642 INT ret;
5643 DWORD size;
5644 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
5645 CHAR bufAddr[54];
5647 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
5649 size = *lenstr;
5650 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
5652 if (ret) return ret;
5654 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
5656 if (*lenstr < size)
5658 *lenstr = size;
5659 WSASetLastError(WSAEFAULT);
5660 return SOCKET_ERROR;
5663 *lenstr = size;
5664 lstrcpyW( string, buffer );
5665 return 0;
5668 /***********************************************************************
5669 * WSAEnumNameSpaceProvidersA (WS2_32.34)
5671 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
5673 FIXME( "(%p %p) Stub!\n", len, buffer );
5674 return 0;
5677 /***********************************************************************
5678 * WSAEnumNameSpaceProvidersW (WS2_32.35)
5680 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
5682 FIXME( "(%p %p) Stub!\n", len, buffer );
5683 return 0;
5686 /***********************************************************************
5687 * WSAGetQOSByName (WS2_32.41)
5689 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
5691 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
5692 return FALSE;
5695 /***********************************************************************
5696 * WSAGetServiceClassInfoA (WS2_32.42)
5698 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
5699 LPWSASERVICECLASSINFOA info )
5701 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
5702 len, info );
5703 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5704 return SOCKET_ERROR;
5707 /***********************************************************************
5708 * WSAGetServiceClassInfoW (WS2_32.43)
5710 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
5711 LPWSASERVICECLASSINFOW info )
5713 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
5714 len, info );
5715 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5716 return SOCKET_ERROR;
5719 /***********************************************************************
5720 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
5722 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
5724 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
5725 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5726 return SOCKET_ERROR;
5729 /***********************************************************************
5730 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
5732 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
5734 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
5735 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5736 return SOCKET_ERROR;
5739 /***********************************************************************
5740 * WSALookupServiceBeginA (WS2_32.59)
5742 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
5743 DWORD dwControlFlags,
5744 LPHANDLE lphLookup)
5746 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
5747 lphLookup);
5748 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5749 return SOCKET_ERROR;
5752 /***********************************************************************
5753 * WSALookupServiceBeginW (WS2_32.60)
5755 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
5756 DWORD dwControlFlags,
5757 LPHANDLE lphLookup)
5759 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
5760 lphLookup);
5761 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5762 return SOCKET_ERROR;
5765 /***********************************************************************
5766 * WSALookupServiceBeginW (WS2_32.61)
5768 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
5770 FIXME("(%p) Stub!\n", lookup );
5771 return 0;
5774 /***********************************************************************
5775 * WSALookupServiceNextA (WS2_32.62)
5777 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
5779 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
5780 return 0;
5783 /***********************************************************************
5784 * WSALookupServiceNextW (WS2_32.63)
5786 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
5788 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
5789 return 0;
5792 /***********************************************************************
5793 * WSANtohl (WS2_32.64)
5795 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
5797 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
5799 if (!lphostlong) return WSAEFAULT;
5801 *lphostlong = ntohl( netlong );
5802 return 0;
5805 /***********************************************************************
5806 * WSANtohs (WS2_32.65)
5808 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
5810 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
5812 if (!lphostshort) return WSAEFAULT;
5814 *lphostshort = ntohs( netshort );
5815 return 0;
5818 /***********************************************************************
5819 * WSAProviderConfigChange (WS2_32.66)
5821 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
5822 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
5824 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
5825 return SOCKET_ERROR;
5828 /***********************************************************************
5829 * WSARecvDisconnect (WS2_32.68)
5831 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
5833 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
5835 return WS_shutdown( s, 0 );
5838 /***********************************************************************
5839 * WSASetServiceA (WS2_32.76)
5841 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
5843 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
5844 return 0;
5847 /***********************************************************************
5848 * WSASetServiceW (WS2_32.77)
5850 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
5852 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
5853 return 0;
5856 /***********************************************************************
5857 * WSCEnableNSProvider (WS2_32.84)
5859 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
5861 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
5862 return 0;
5865 /***********************************************************************
5866 * WSCGetProviderPath (WS2_32.86)
5868 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
5870 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
5872 if (!errcode || !provider || !len) return WSAEFAULT;
5874 *errcode = WSAEINVAL;
5875 return SOCKET_ERROR;
5878 /***********************************************************************
5879 * WSCInstallNameSpace (WS2_32.87)
5881 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
5882 DWORD version, LPGUID provider )
5884 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
5885 namespace, version, debugstr_guid(provider) );
5886 return 0;
5889 /***********************************************************************
5890 * WSCUnInstallNameSpace (WS2_32.89)
5892 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
5894 FIXME("(%p) Stub!\n", lpProviderId);
5895 return NO_ERROR;
5898 /***********************************************************************
5899 * WSCWriteProviderOrder (WS2_32.91)
5901 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
5903 FIXME("(%p 0x%08x) Stub!\n", entry, number);
5904 return 0;