winebus.sys: Process quirky DualSense bluetooth reports.
[wine.git] / server / sock.c
blob40fb0cac5354bd73c8720d7d7b5094ed2b4a0556
1 /*
2 * Server-side socket management
4 * Copyright (C) 1999 Marcus Meissner, Ove Kåven
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 * FIXME: we use read|write access in all cases. Shouldn't we depend that
21 * on the access of the current handle?
24 #include "config.h"
26 #include <assert.h>
27 #include <fcntl.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <string.h>
31 #include <stdlib.h>
32 #include <errno.h>
33 #ifdef HAVE_IFADDRS_H
34 # include <ifaddrs.h>
35 #endif
36 #ifdef HAVE_NET_IF_H
37 # include <net/if.h>
38 #endif
39 #ifdef HAVE_NETINET_IN_H
40 # include <netinet/in.h>
41 #endif
42 #include <poll.h>
43 #include <sys/time.h>
44 #include <sys/types.h>
45 #include <sys/socket.h>
46 #include <sys/ioctl.h>
47 #ifdef HAVE_SYS_FILIO_H
48 # include <sys/filio.h>
49 #endif
50 #include <time.h>
51 #include <unistd.h>
52 #include <limits.h>
53 #ifdef HAVE_LINUX_FILTER_H
54 # include <linux/filter.h>
55 #endif
56 #ifdef HAVE_LINUX_RTNETLINK_H
57 # include <linux/rtnetlink.h>
58 #endif
60 #ifdef HAVE_NETIPX_IPX_H
61 # include <netipx/ipx.h>
62 #elif defined(HAVE_LINUX_IPX_H)
63 # ifdef HAVE_ASM_TYPES_H
64 # include <asm/types.h>
65 # endif
66 # ifdef HAVE_LINUX_TYPES_H
67 # include <linux/types.h>
68 # endif
69 # include <linux/ipx.h>
70 #endif
71 #if defined(SOL_IPX) || defined(SO_DEFAULT_HEADERS)
72 # define HAS_IPX
73 #endif
75 #ifdef HAVE_LINUX_IRDA_H
76 # ifdef HAVE_LINUX_TYPES_H
77 # include <linux/types.h>
78 # endif
79 # include <linux/irda.h>
80 # define HAS_IRDA
81 #endif
83 #include "ntstatus.h"
84 #define WIN32_NO_STATUS
85 #include "windef.h"
86 #include "winternl.h"
87 #include "winerror.h"
88 #define USE_WS_PREFIX
89 #include "winsock2.h"
90 #include "ws2tcpip.h"
91 #include "wsipx.h"
92 #include "af_irda.h"
93 #include "wine/afd.h"
95 #include "process.h"
96 #include "file.h"
97 #include "handle.h"
98 #include "thread.h"
99 #include "request.h"
100 #include "user.h"
102 #if defined(linux) && !defined(IP_UNICAST_IF)
103 #define IP_UNICAST_IF 50
104 #endif
106 static const char magic_loopback_addr[] = {127, 12, 34, 56};
108 union win_sockaddr
110 struct WS_sockaddr addr;
111 struct WS_sockaddr_in in;
112 struct WS_sockaddr_in6 in6;
113 struct WS_sockaddr_ipx ipx;
114 SOCKADDR_IRDA irda;
117 static struct list poll_list = LIST_INIT( poll_list );
119 struct poll_req
121 struct list entry;
122 struct async *async;
123 struct iosb *iosb;
124 struct timeout_user *timeout;
125 timeout_t orig_timeout;
126 int exclusive;
127 unsigned int count;
128 struct
130 struct sock *sock;
131 int mask;
132 obj_handle_t handle;
133 int flags;
134 unsigned int status;
135 } sockets[1];
138 struct accept_req
140 struct list entry;
141 struct async *async;
142 struct iosb *iosb;
143 struct sock *sock, *acceptsock;
144 int accepted;
145 unsigned int recv_len, local_len;
148 struct connect_req
150 struct async *async;
151 struct iosb *iosb;
152 struct sock *sock;
153 unsigned int addr_len, send_len, send_cursor;
156 enum connection_state
158 SOCK_LISTENING,
159 SOCK_UNCONNECTED,
160 SOCK_CONNECTING,
161 SOCK_CONNECTED,
162 SOCK_CONNECTIONLESS,
165 struct sock
167 struct object obj; /* object header */
168 struct fd *fd; /* socket file descriptor */
169 enum connection_state state; /* connection state */
170 unsigned int mask; /* event mask */
171 /* pending AFD_POLL_* events which have not yet been reported to the application */
172 unsigned int pending_events;
173 /* AFD_POLL_* events which have already been reported and should not be
174 * selected for again until reset by a relevant call.
176 * For example, if AFD_POLL_READ is set here and not in pending_events, it
177 * has already been reported and consumed, and we should not report it
178 * again, even if POLLIN is signaled, until it is reset by e.g recv().
180 * If an event has been signaled and not consumed yet, it will be set in
181 * both pending_events and reported_events (as we should only ever report
182 * any event once until it is reset.) */
183 unsigned int reported_events;
184 unsigned int flags; /* socket flags */
185 unsigned short proto; /* socket protocol */
186 unsigned short type; /* socket type */
187 unsigned short family; /* socket family */
188 struct event *event; /* event object */
189 user_handle_t window; /* window to send the message to */
190 unsigned int message; /* message to send */
191 obj_handle_t wparam; /* message wparam (socket handle) */
192 int errors[AFD_POLL_BIT_COUNT]; /* event errors */
193 timeout_t connect_time;/* time the socket was connected */
194 struct sock *deferred; /* socket that waits for a deferred accept */
195 struct async_queue read_q; /* queue for asynchronous reads */
196 struct async_queue write_q; /* queue for asynchronous writes */
197 struct async_queue ifchange_q; /* queue for interface change notifications */
198 struct async_queue accept_q; /* queue for asynchronous accepts */
199 struct async_queue connect_q; /* queue for asynchronous connects */
200 struct async_queue poll_q; /* queue for asynchronous polls */
201 struct object *ifchange_obj; /* the interface change notification object */
202 struct list ifchange_entry; /* entry in ifchange notification list */
203 struct list accept_list; /* list of pending accept requests */
204 struct accept_req *accept_recv_req; /* pending accept-into request which will recv on this socket */
205 struct connect_req *connect_req; /* pending connection request */
206 struct poll_req *main_poll; /* main poll */
207 union win_sockaddr addr; /* socket name */
208 int addr_len; /* socket name length */
209 unsigned int rcvbuf; /* advisory recv buffer size */
210 unsigned int sndbuf; /* advisory send buffer size */
211 unsigned int rcvtimeo; /* receive timeout in ms */
212 unsigned int sndtimeo; /* send timeout in ms */
213 unsigned int rd_shutdown : 1; /* is the read end shut down? */
214 unsigned int wr_shutdown : 1; /* is the write end shut down? */
215 unsigned int wr_shutdown_pending : 1; /* is a write shutdown pending? */
216 unsigned int hangup : 1; /* has the read end received a hangup? */
217 unsigned int aborted : 1; /* did we get a POLLERR or irregular POLLHUP? */
218 unsigned int nonblocking : 1; /* is the socket nonblocking? */
219 unsigned int bound : 1; /* is the socket bound? */
222 static void sock_dump( struct object *obj, int verbose );
223 static struct fd *sock_get_fd( struct object *obj );
224 static int sock_close_handle( struct object *obj, struct process *process, obj_handle_t handle );
225 static void sock_destroy( struct object *obj );
226 static struct object *sock_get_ifchange( struct sock *sock );
227 static void sock_release_ifchange( struct sock *sock );
229 static int sock_get_poll_events( struct fd *fd );
230 static void sock_poll_event( struct fd *fd, int event );
231 static enum server_fd_type sock_get_fd_type( struct fd *fd );
232 static void sock_ioctl( struct fd *fd, ioctl_code_t code, struct async *async );
233 static void sock_cancel_async( struct fd *fd, struct async *async );
234 static void sock_queue_async( struct fd *fd, struct async *async, int type, int count );
235 static void sock_reselect_async( struct fd *fd, struct async_queue *queue );
237 static int accept_into_socket( struct sock *sock, struct sock *acceptsock );
238 static struct sock *accept_socket( struct sock *sock );
239 static int sock_get_ntstatus( int err );
240 static unsigned int sock_get_error( int err );
241 static void poll_socket( struct sock *poll_sock, struct async *async, int exclusive, timeout_t timeout,
242 unsigned int count, const struct afd_poll_socket_64 *sockets );
244 static const struct object_ops sock_ops =
246 sizeof(struct sock), /* size */
247 &file_type, /* type */
248 sock_dump, /* dump */
249 add_queue, /* add_queue */
250 remove_queue, /* remove_queue */
251 default_fd_signaled, /* signaled */
252 no_satisfied, /* satisfied */
253 no_signal, /* signal */
254 sock_get_fd, /* get_fd */
255 default_map_access, /* map_access */
256 default_get_sd, /* get_sd */
257 default_set_sd, /* set_sd */
258 no_get_full_name, /* get_full_name */
259 no_lookup_name, /* lookup_name */
260 no_link_name, /* link_name */
261 NULL, /* unlink_name */
262 no_open_file, /* open_file */
263 no_kernel_obj_list, /* get_kernel_obj_list */
264 sock_close_handle, /* close_handle */
265 sock_destroy /* destroy */
268 static const struct fd_ops sock_fd_ops =
270 sock_get_poll_events, /* get_poll_events */
271 sock_poll_event, /* poll_event */
272 sock_get_fd_type, /* get_fd_type */
273 no_fd_read, /* read */
274 no_fd_write, /* write */
275 no_fd_flush, /* flush */
276 default_fd_get_file_info, /* get_file_info */
277 no_fd_get_volume_info, /* get_volume_info */
278 sock_ioctl, /* ioctl */
279 sock_cancel_async, /* cancel_async */
280 sock_queue_async, /* queue_async */
281 sock_reselect_async /* reselect_async */
284 union unix_sockaddr
286 struct sockaddr addr;
287 struct sockaddr_in in;
288 struct sockaddr_in6 in6;
289 #ifdef HAS_IPX
290 struct sockaddr_ipx ipx;
291 #endif
292 #ifdef HAS_IRDA
293 struct sockaddr_irda irda;
294 #endif
297 static int sockaddr_from_unix( const union unix_sockaddr *uaddr, struct WS_sockaddr *wsaddr, socklen_t wsaddrlen )
299 memset( wsaddr, 0, wsaddrlen );
301 switch (uaddr->addr.sa_family)
303 case AF_INET:
305 struct WS_sockaddr_in win = {0};
307 if (wsaddrlen < sizeof(win)) return -1;
308 win.sin_family = WS_AF_INET;
309 win.sin_port = uaddr->in.sin_port;
310 memcpy( &win.sin_addr, &uaddr->in.sin_addr, sizeof(win.sin_addr) );
311 memcpy( wsaddr, &win, sizeof(win) );
312 return sizeof(win);
315 case AF_INET6:
317 struct WS_sockaddr_in6 win = {0};
319 if (wsaddrlen < sizeof(win)) return -1;
320 win.sin6_family = WS_AF_INET6;
321 win.sin6_port = uaddr->in6.sin6_port;
322 win.sin6_flowinfo = uaddr->in6.sin6_flowinfo;
323 memcpy( &win.sin6_addr, &uaddr->in6.sin6_addr, sizeof(win.sin6_addr) );
324 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
325 win.sin6_scope_id = uaddr->in6.sin6_scope_id;
326 #endif
327 memcpy( wsaddr, &win, sizeof(win) );
328 return sizeof(win);
331 #ifdef HAS_IPX
332 case AF_IPX:
334 struct WS_sockaddr_ipx win = {0};
336 if (wsaddrlen < sizeof(win)) return -1;
337 win.sa_family = WS_AF_IPX;
338 memcpy( win.sa_netnum, &uaddr->ipx.sipx_network, sizeof(win.sa_netnum) );
339 memcpy( win.sa_nodenum, &uaddr->ipx.sipx_node, sizeof(win.sa_nodenum) );
340 win.sa_socket = uaddr->ipx.sipx_port;
341 memcpy( wsaddr, &win, sizeof(win) );
342 return sizeof(win);
344 #endif
346 #ifdef HAS_IRDA
347 case AF_IRDA:
349 SOCKADDR_IRDA win;
351 if (wsaddrlen < sizeof(win)) return -1;
352 win.irdaAddressFamily = WS_AF_IRDA;
353 memcpy( win.irdaDeviceID, &uaddr->irda.sir_addr, sizeof(win.irdaDeviceID) );
354 if (uaddr->irda.sir_lsap_sel != LSAP_ANY)
355 snprintf( win.irdaServiceName, sizeof(win.irdaServiceName), "LSAP-SEL%u", uaddr->irda.sir_lsap_sel );
356 else
357 memcpy( win.irdaServiceName, uaddr->irda.sir_name, sizeof(win.irdaServiceName) );
358 memcpy( wsaddr, &win, sizeof(win) );
359 return sizeof(win);
361 #endif
363 case AF_UNSPEC:
364 return 0;
366 default:
367 return -1;
372 static socklen_t sockaddr_to_unix( const struct WS_sockaddr *wsaddr, int wsaddrlen, union unix_sockaddr *uaddr )
374 memset( uaddr, 0, sizeof(*uaddr) );
376 switch (wsaddr->sa_family)
378 case WS_AF_INET:
380 struct WS_sockaddr_in win = {0};
382 if (wsaddrlen < sizeof(win)) return 0;
383 memcpy( &win, wsaddr, sizeof(win) );
384 uaddr->in.sin_family = AF_INET;
385 uaddr->in.sin_port = win.sin_port;
386 memcpy( &uaddr->in.sin_addr, &win.sin_addr, sizeof(win.sin_addr) );
387 return sizeof(uaddr->in);
390 case WS_AF_INET6:
392 struct WS_sockaddr_in6 win = {0};
394 if (wsaddrlen < sizeof(win)) return 0;
395 memcpy( &win, wsaddr, sizeof(win) );
396 uaddr->in6.sin6_family = AF_INET6;
397 uaddr->in6.sin6_port = win.sin6_port;
398 uaddr->in6.sin6_flowinfo = win.sin6_flowinfo;
399 memcpy( &uaddr->in6.sin6_addr, &win.sin6_addr, sizeof(win.sin6_addr) );
400 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
401 uaddr->in6.sin6_scope_id = win.sin6_scope_id;
402 #endif
403 return sizeof(uaddr->in6);
406 #ifdef HAS_IPX
407 case WS_AF_IPX:
409 struct WS_sockaddr_ipx win = {0};
411 if (wsaddrlen < sizeof(win)) return 0;
412 memcpy( &win, wsaddr, sizeof(win) );
413 uaddr->ipx.sipx_family = AF_IPX;
414 memcpy( &uaddr->ipx.sipx_network, win.sa_netnum, sizeof(win.sa_netnum) );
415 memcpy( &uaddr->ipx.sipx_node, win.sa_nodenum, sizeof(win.sa_nodenum) );
416 uaddr->ipx.sipx_port = win.sa_socket;
417 return sizeof(uaddr->ipx);
419 #endif
421 #ifdef HAS_IRDA
422 case WS_AF_IRDA:
424 SOCKADDR_IRDA win = {0};
425 unsigned int lsap_sel;
427 if (wsaddrlen < sizeof(win)) return 0;
428 memcpy( &win, wsaddr, sizeof(win) );
429 uaddr->irda.sir_family = AF_IRDA;
430 if (sscanf( win.irdaServiceName, "LSAP-SEL%u", &lsap_sel ) == 1)
431 uaddr->irda.sir_lsap_sel = lsap_sel;
432 else
434 uaddr->irda.sir_lsap_sel = LSAP_ANY;
435 memcpy( uaddr->irda.sir_name, win.irdaServiceName, sizeof(win.irdaServiceName) );
437 memcpy( &uaddr->irda.sir_addr, win.irdaDeviceID, sizeof(win.irdaDeviceID) );
438 return sizeof(uaddr->irda);
440 #endif
442 case WS_AF_UNSPEC:
443 switch (wsaddrlen)
445 default: /* likely an ipv4 address */
446 case sizeof(struct WS_sockaddr_in):
447 return sizeof(uaddr->in);
449 #ifdef HAS_IPX
450 case sizeof(struct WS_sockaddr_ipx):
451 return sizeof(uaddr->ipx);
452 #endif
454 #ifdef HAS_IRDA
455 case sizeof(SOCKADDR_IRDA):
456 return sizeof(uaddr->irda);
457 #endif
459 case sizeof(struct WS_sockaddr_in6):
460 return sizeof(uaddr->in6);
463 default:
464 return 0;
468 /* some events are generated at the same time but must be sent in a particular
469 * order (e.g. CONNECT must be sent before READ) */
470 static const enum afd_poll_bit event_bitorder[] =
472 AFD_POLL_BIT_CONNECT,
473 AFD_POLL_BIT_CONNECT_ERR,
474 AFD_POLL_BIT_ACCEPT,
475 AFD_POLL_BIT_OOB,
476 AFD_POLL_BIT_WRITE,
477 AFD_POLL_BIT_READ,
478 AFD_POLL_BIT_RESET,
479 AFD_POLL_BIT_HUP,
480 AFD_POLL_BIT_CLOSE,
483 typedef enum {
484 SOCK_SHUTDOWN_ERROR = -1,
485 SOCK_SHUTDOWN_EOF = 0,
486 SOCK_SHUTDOWN_POLLHUP = 1
487 } sock_shutdown_t;
489 static sock_shutdown_t sock_shutdown_type = SOCK_SHUTDOWN_ERROR;
491 static sock_shutdown_t sock_check_pollhup(void)
493 sock_shutdown_t ret = SOCK_SHUTDOWN_ERROR;
494 int fd[2], n;
495 struct pollfd pfd;
496 char dummy;
498 if ( socketpair( AF_UNIX, SOCK_STREAM, 0, fd ) ) return ret;
499 if ( shutdown( fd[0], 1 ) ) goto out;
501 pfd.fd = fd[1];
502 pfd.events = POLLIN;
503 pfd.revents = 0;
505 /* Solaris' poll() sometimes returns nothing if given a 0ms timeout here */
506 n = poll( &pfd, 1, 1 );
507 if ( n != 1 ) goto out; /* error or timeout */
508 if ( pfd.revents & POLLHUP )
509 ret = SOCK_SHUTDOWN_POLLHUP;
510 else if ( pfd.revents & POLLIN &&
511 read( fd[1], &dummy, 1 ) == 0 )
512 ret = SOCK_SHUTDOWN_EOF;
514 out:
515 close( fd[0] );
516 close( fd[1] );
517 return ret;
520 void sock_init(void)
522 sock_shutdown_type = sock_check_pollhup();
524 switch ( sock_shutdown_type )
526 case SOCK_SHUTDOWN_EOF:
527 if (debug_level) fprintf( stderr, "sock_init: shutdown() causes EOF\n" );
528 break;
529 case SOCK_SHUTDOWN_POLLHUP:
530 if (debug_level) fprintf( stderr, "sock_init: shutdown() causes POLLHUP\n" );
531 break;
532 default:
533 fprintf( stderr, "sock_init: ERROR in sock_check_pollhup()\n" );
534 sock_shutdown_type = SOCK_SHUTDOWN_EOF;
538 static int sock_reselect( struct sock *sock )
540 int ev = sock_get_poll_events( sock->fd );
542 if (debug_level)
543 fprintf(stderr,"sock_reselect(%p): new mask %x\n", sock, ev);
545 set_fd_events( sock->fd, ev );
546 return ev;
549 static unsigned int afd_poll_flag_to_win32( unsigned int flags )
551 static const unsigned int map[] =
553 FD_READ, /* READ */
554 FD_OOB, /* OOB */
555 FD_WRITE, /* WRITE */
556 FD_CLOSE, /* HUP */
557 FD_CLOSE, /* RESET */
558 0, /* CLOSE */
559 FD_CONNECT, /* CONNECT */
560 FD_ACCEPT, /* ACCEPT */
561 FD_CONNECT, /* CONNECT_ERR */
564 unsigned int i, ret = 0;
566 for (i = 0; i < ARRAY_SIZE(map); ++i)
568 if (flags & (1 << i)) ret |= map[i];
571 return ret;
574 /* wake anybody waiting on the socket event or send the associated message */
575 static void sock_wake_up( struct sock *sock )
577 unsigned int events = sock->pending_events & sock->mask;
578 int i;
580 if (sock->event)
582 if (debug_level) fprintf(stderr, "signalling events %x ptr %p\n", events, sock->event );
583 if (events)
584 set_event( sock->event );
586 if (sock->window)
588 if (debug_level) fprintf(stderr, "signalling events %x win %08x\n", events, sock->window );
589 for (i = 0; i < ARRAY_SIZE(event_bitorder); i++)
591 enum afd_poll_bit event = event_bitorder[i];
592 if (events & (1 << event))
594 lparam_t lparam = afd_poll_flag_to_win32(1 << event) | (sock_get_error( sock->errors[event] ) << 16);
595 post_message( sock->window, sock->message, sock->wparam, lparam );
598 sock->pending_events = 0;
599 sock_reselect( sock );
603 static inline int sock_error( struct fd *fd )
605 unsigned int optval = 0;
606 socklen_t optlen = sizeof(optval);
608 getsockopt( get_unix_fd(fd), SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
609 return optval;
612 static void free_accept_req( void *private )
614 struct accept_req *req = private;
615 list_remove( &req->entry );
616 if (req->acceptsock)
618 req->acceptsock->accept_recv_req = NULL;
619 release_object( req->acceptsock );
621 release_object( req->async );
622 release_object( req->iosb );
623 release_object( req->sock );
624 free( req );
627 static void fill_accept_output( struct accept_req *req )
629 const data_size_t out_size = req->iosb->out_size;
630 struct async *async = req->async;
631 union unix_sockaddr unix_addr;
632 struct WS_sockaddr *win_addr;
633 unsigned int remote_len;
634 socklen_t unix_len;
635 int fd, size = 0;
636 char *out_data;
637 int win_len;
639 if (!(out_data = mem_alloc( out_size )))
641 async_terminate( async, get_error() );
642 return;
645 fd = get_unix_fd( req->acceptsock->fd );
647 if (req->recv_len && (size = recv( fd, out_data, req->recv_len, 0 )) < 0)
649 if (!req->accepted && errno == EWOULDBLOCK)
651 req->accepted = 1;
652 sock_reselect( req->acceptsock );
653 return;
656 async_terminate( async, sock_get_ntstatus( errno ) );
657 free( out_data );
658 return;
661 if (req->local_len)
663 if (req->local_len < sizeof(int))
665 async_terminate( async, STATUS_BUFFER_TOO_SMALL );
666 free( out_data );
667 return;
670 unix_len = sizeof(unix_addr);
671 win_addr = (struct WS_sockaddr *)(out_data + req->recv_len + sizeof(int));
672 if (getsockname( fd, &unix_addr.addr, &unix_len ) < 0 ||
673 (win_len = sockaddr_from_unix( &unix_addr, win_addr, req->local_len - sizeof(int) )) < 0)
675 async_terminate( async, sock_get_ntstatus( errno ) );
676 free( out_data );
677 return;
679 memcpy( out_data + req->recv_len, &win_len, sizeof(int) );
682 unix_len = sizeof(unix_addr);
683 win_addr = (struct WS_sockaddr *)(out_data + req->recv_len + req->local_len + sizeof(int));
684 remote_len = out_size - req->recv_len - req->local_len;
685 if (getpeername( fd, &unix_addr.addr, &unix_len ) < 0 ||
686 (win_len = sockaddr_from_unix( &unix_addr, win_addr, remote_len - sizeof(int) )) < 0)
688 async_terminate( async, sock_get_ntstatus( errno ) );
689 free( out_data );
690 return;
692 memcpy( out_data + req->recv_len + req->local_len, &win_len, sizeof(int) );
694 async_request_complete( req->async, STATUS_SUCCESS, size, out_size, out_data );
697 static void complete_async_accept( struct sock *sock, struct accept_req *req )
699 struct sock *acceptsock = req->acceptsock;
700 struct async *async = req->async;
702 if (debug_level) fprintf( stderr, "completing accept request for socket %p\n", sock );
704 if (acceptsock)
706 if (!accept_into_socket( sock, acceptsock ))
708 async_terminate( async, get_error() );
709 return;
711 fill_accept_output( req );
713 else
715 obj_handle_t handle;
717 if (!(acceptsock = accept_socket( sock )))
719 async_terminate( async, get_error() );
720 return;
722 handle = alloc_handle_no_access_check( async_get_thread( async )->process, &acceptsock->obj,
723 GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE, OBJ_INHERIT );
724 acceptsock->wparam = handle;
725 sock_reselect( acceptsock );
726 release_object( acceptsock );
727 if (!handle)
729 async_terminate( async, get_error() );
730 return;
733 async_request_complete_alloc( req->async, STATUS_SUCCESS, 0, sizeof(handle), &handle );
737 static void complete_async_accept_recv( struct accept_req *req )
739 if (debug_level) fprintf( stderr, "completing accept recv request for socket %p\n", req->acceptsock );
741 assert( req->recv_len );
743 fill_accept_output( req );
746 static void free_connect_req( void *private )
748 struct connect_req *req = private;
750 req->sock->connect_req = NULL;
751 release_object( req->async );
752 release_object( req->iosb );
753 release_object( req->sock );
754 free( req );
757 static void complete_async_connect( struct sock *sock )
759 struct connect_req *req = sock->connect_req;
760 const char *in_buffer;
761 size_t len;
762 int ret;
764 if (debug_level) fprintf( stderr, "completing connect request for socket %p\n", sock );
766 sock->state = SOCK_CONNECTED;
768 if (!req->send_len)
770 async_terminate( req->async, STATUS_SUCCESS );
771 return;
774 in_buffer = (const char *)req->iosb->in_data + sizeof(struct afd_connect_params) + req->addr_len;
775 len = req->send_len - req->send_cursor;
777 ret = send( get_unix_fd( sock->fd ), in_buffer + req->send_cursor, len, 0 );
778 if (ret < 0 && errno != EWOULDBLOCK)
779 async_terminate( req->async, sock_get_ntstatus( errno ) );
780 else if (ret == len)
781 async_request_complete( req->async, STATUS_SUCCESS, req->send_len, 0, NULL );
782 else
783 req->send_cursor += ret;
786 static void free_poll_req( void *private )
788 struct poll_req *req = private;
789 unsigned int i;
791 if (req->timeout) remove_timeout_user( req->timeout );
793 for (i = 0; i < req->count; ++i)
794 release_object( req->sockets[i].sock );
795 release_object( req->async );
796 release_object( req->iosb );
797 list_remove( &req->entry );
798 free( req );
801 static int is_oobinline( struct sock *sock )
803 int oobinline;
804 socklen_t len = sizeof(oobinline);
805 return !getsockopt( get_unix_fd( sock->fd ), SOL_SOCKET, SO_OOBINLINE, (char *)&oobinline, &len ) && oobinline;
808 static int get_poll_flags( struct sock *sock, int event )
810 int flags = 0;
812 /* A connection-mode socket which has never been connected does not return
813 * write or hangup events, but Linux reports POLLOUT | POLLHUP. */
814 if (sock->state == SOCK_UNCONNECTED)
815 event &= ~(POLLOUT | POLLHUP);
817 if (event & POLLIN)
819 if (sock->state == SOCK_LISTENING)
820 flags |= AFD_POLL_ACCEPT;
821 else
822 flags |= AFD_POLL_READ;
824 if (event & POLLPRI)
825 flags |= is_oobinline( sock ) ? AFD_POLL_READ : AFD_POLL_OOB;
826 if (event & POLLOUT)
827 flags |= AFD_POLL_WRITE;
828 if (sock->state == SOCK_CONNECTED)
829 flags |= AFD_POLL_CONNECT;
830 if (event & POLLHUP)
831 flags |= AFD_POLL_HUP;
832 if (event & POLLERR)
833 flags |= AFD_POLL_CONNECT_ERR;
835 return flags;
838 static void complete_async_poll( struct poll_req *req, unsigned int status )
840 unsigned int i, signaled_count = 0;
842 for (i = 0; i < req->count; ++i)
844 struct sock *sock = req->sockets[i].sock;
846 if (sock->main_poll == req)
847 sock->main_poll = NULL;
850 if (!status)
852 for (i = 0; i < req->count; ++i)
854 if (req->sockets[i].flags)
855 ++signaled_count;
859 if (is_machine_64bit( async_get_thread( req->async )->process->machine ))
861 size_t output_size = offsetof( struct afd_poll_params_64, sockets[signaled_count] );
862 struct afd_poll_params_64 *output;
864 if (!(output = mem_alloc( output_size )))
866 async_terminate( req->async, get_error() );
867 return;
869 memset( output, 0, output_size );
870 output->timeout = req->orig_timeout;
871 output->exclusive = req->exclusive;
872 for (i = 0; i < req->count; ++i)
874 if (!req->sockets[i].flags) continue;
875 output->sockets[output->count].socket = req->sockets[i].handle;
876 output->sockets[output->count].flags = req->sockets[i].flags;
877 output->sockets[output->count].status = req->sockets[i].status;
878 ++output->count;
880 assert( output->count == signaled_count );
882 async_request_complete( req->async, status, output_size, output_size, output );
884 else
886 size_t output_size = offsetof( struct afd_poll_params_32, sockets[signaled_count] );
887 struct afd_poll_params_32 *output;
889 if (!(output = mem_alloc( output_size )))
891 async_terminate( req->async, get_error() );
892 return;
894 memset( output, 0, output_size );
895 output->timeout = req->orig_timeout;
896 output->exclusive = req->exclusive;
897 for (i = 0; i < req->count; ++i)
899 if (!req->sockets[i].flags) continue;
900 output->sockets[output->count].socket = req->sockets[i].handle;
901 output->sockets[output->count].flags = req->sockets[i].flags;
902 output->sockets[output->count].status = req->sockets[i].status;
903 ++output->count;
905 assert( output->count == signaled_count );
907 async_request_complete( req->async, status, output_size, output_size, output );
911 static void complete_async_polls( struct sock *sock, int event, int error )
913 int flags = get_poll_flags( sock, event );
914 struct poll_req *req, *next;
916 LIST_FOR_EACH_ENTRY_SAFE( req, next, &poll_list, struct poll_req, entry )
918 unsigned int i;
920 if (req->iosb->status != STATUS_PENDING) continue;
922 for (i = 0; i < req->count; ++i)
924 if (req->sockets[i].sock != sock) continue;
925 if (!(req->sockets[i].mask & flags)) continue;
927 if (debug_level)
928 fprintf( stderr, "completing poll for socket %p, wanted %#x got %#x\n",
929 sock, req->sockets[i].mask, flags );
931 req->sockets[i].flags = req->sockets[i].mask & flags;
932 req->sockets[i].status = sock_get_ntstatus( error );
934 complete_async_poll( req, STATUS_SUCCESS );
935 break;
940 static void async_poll_timeout( void *private )
942 struct poll_req *req = private;
944 req->timeout = NULL;
946 if (req->iosb->status != STATUS_PENDING) return;
948 complete_async_poll( req, STATUS_TIMEOUT );
951 static int sock_dispatch_asyncs( struct sock *sock, int event, int error )
953 if (event & (POLLIN | POLLPRI))
955 struct accept_req *req;
957 LIST_FOR_EACH_ENTRY( req, &sock->accept_list, struct accept_req, entry )
959 if (req->iosb->status == STATUS_PENDING && !req->accepted)
961 complete_async_accept( sock, req );
962 break;
966 if (sock->accept_recv_req && sock->accept_recv_req->iosb->status == STATUS_PENDING)
967 complete_async_accept_recv( sock->accept_recv_req );
970 if ((event & POLLOUT) && sock->connect_req && sock->connect_req->iosb->status == STATUS_PENDING)
971 complete_async_connect( sock );
973 if (event & (POLLIN | POLLPRI) && async_waiting( &sock->read_q ))
975 if (debug_level) fprintf( stderr, "activating read queue for socket %p\n", sock );
976 async_wake_up( &sock->read_q, STATUS_ALERTED );
977 event &= ~(POLLIN | POLLPRI);
980 if (event & POLLOUT && async_waiting( &sock->write_q ))
982 if (debug_level) fprintf( stderr, "activating write queue for socket %p\n", sock );
983 async_wake_up( &sock->write_q, STATUS_ALERTED );
984 event &= ~POLLOUT;
987 if (event & (POLLERR | POLLHUP))
989 int status = sock_get_ntstatus( error );
990 struct accept_req *req, *next;
992 if (sock->rd_shutdown || sock->hangup)
993 async_wake_up( &sock->read_q, status );
994 if (sock->wr_shutdown)
995 async_wake_up( &sock->write_q, status );
997 LIST_FOR_EACH_ENTRY_SAFE( req, next, &sock->accept_list, struct accept_req, entry )
999 if (req->iosb->status == STATUS_PENDING)
1000 async_terminate( req->async, status );
1003 if (sock->accept_recv_req && sock->accept_recv_req->iosb->status == STATUS_PENDING)
1004 async_terminate( sock->accept_recv_req->async, status );
1006 if (sock->connect_req)
1007 async_terminate( sock->connect_req->async, status );
1010 return event;
1013 static void post_socket_event( struct sock *sock, enum afd_poll_bit event_bit, int error )
1015 unsigned int event = (1 << event_bit);
1017 if (!(sock->reported_events & event))
1019 sock->pending_events |= event;
1020 sock->reported_events |= event;
1021 sock->errors[event_bit] = error;
1025 static void sock_dispatch_events( struct sock *sock, enum connection_state prevstate, int event, int error )
1027 switch (prevstate)
1029 case SOCK_UNCONNECTED:
1030 break;
1032 case SOCK_CONNECTING:
1033 if (event & POLLOUT)
1035 post_socket_event( sock, AFD_POLL_BIT_CONNECT, 0 );
1036 sock->errors[AFD_POLL_BIT_CONNECT_ERR] = 0;
1038 if (event & (POLLERR | POLLHUP))
1039 post_socket_event( sock, AFD_POLL_BIT_CONNECT_ERR, error );
1040 break;
1042 case SOCK_LISTENING:
1043 if (event & (POLLIN | POLLERR | POLLHUP))
1044 post_socket_event( sock, AFD_POLL_BIT_ACCEPT, error );
1045 break;
1047 case SOCK_CONNECTED:
1048 case SOCK_CONNECTIONLESS:
1049 if (event & POLLIN)
1050 post_socket_event( sock, AFD_POLL_BIT_READ, 0 );
1052 if (event & POLLOUT)
1053 post_socket_event( sock, AFD_POLL_BIT_WRITE, 0 );
1055 if (event & POLLPRI)
1056 post_socket_event( sock, AFD_POLL_BIT_OOB, 0 );
1058 if (event & (POLLERR | POLLHUP))
1059 post_socket_event( sock, AFD_POLL_BIT_HUP, error );
1060 break;
1063 sock_wake_up( sock );
1066 static void sock_poll_event( struct fd *fd, int event )
1068 struct sock *sock = get_fd_user( fd );
1069 int hangup_seen = 0;
1070 enum connection_state prevstate = sock->state;
1071 int error = 0;
1073 assert( sock->obj.ops == &sock_ops );
1074 if (debug_level)
1075 fprintf(stderr, "socket %p select event: %x\n", sock, event);
1077 /* we may change event later, remove from loop here */
1078 if (event & (POLLERR|POLLHUP)) set_fd_events( sock->fd, -1 );
1080 switch (sock->state)
1082 case SOCK_UNCONNECTED:
1083 break;
1085 case SOCK_CONNECTING:
1086 if (event & (POLLERR|POLLHUP))
1088 sock->state = SOCK_UNCONNECTED;
1089 event &= ~POLLOUT;
1090 error = sock_error( fd );
1092 else if (event & POLLOUT)
1094 sock->state = SOCK_CONNECTED;
1095 sock->connect_time = current_time;
1097 break;
1099 case SOCK_LISTENING:
1100 if (event & (POLLERR|POLLHUP))
1101 error = sock_error( fd );
1102 break;
1104 case SOCK_CONNECTED:
1105 case SOCK_CONNECTIONLESS:
1106 if (sock->type == WS_SOCK_STREAM && (event & POLLIN))
1108 char dummy;
1109 int nr;
1111 /* Linux 2.4 doesn't report POLLHUP if only one side of the socket
1112 * has been closed, so we need to check for it explicitly here */
1113 nr = recv( get_unix_fd( fd ), &dummy, 1, MSG_PEEK );
1114 if ( nr == 0 )
1116 hangup_seen = 1;
1117 event &= ~POLLIN;
1119 else if ( nr < 0 )
1121 event &= ~POLLIN;
1122 /* EAGAIN can happen if an async recv() falls between the server's poll()
1123 call and the invocation of this routine */
1124 if ( errno != EAGAIN )
1126 error = errno;
1127 event |= POLLERR;
1128 if ( debug_level )
1129 fprintf( stderr, "recv error on socket %p: %d\n", sock, errno );
1134 if (hangup_seen || (sock_shutdown_type == SOCK_SHUTDOWN_POLLHUP && (event & POLLHUP)))
1136 sock->hangup = 1;
1138 else if (event & (POLLHUP | POLLERR))
1140 sock->aborted = 1;
1142 if (debug_level)
1143 fprintf( stderr, "socket %p aborted by error %d, event %#x\n", sock, error, event );
1146 if (hangup_seen)
1147 event |= POLLHUP;
1148 break;
1151 complete_async_polls( sock, event, error );
1153 event = sock_dispatch_asyncs( sock, event, error );
1154 sock_dispatch_events( sock, prevstate, event, error );
1156 sock_reselect( sock );
1159 static void sock_dump( struct object *obj, int verbose )
1161 struct sock *sock = (struct sock *)obj;
1162 assert( obj->ops == &sock_ops );
1163 fprintf( stderr, "Socket fd=%p, state=%x, mask=%x, pending=%x, reported=%x\n",
1164 sock->fd, sock->state,
1165 sock->mask, sock->pending_events, sock->reported_events );
1168 static int poll_flags_from_afd( struct sock *sock, int flags )
1170 int ev = 0;
1172 /* A connection-mode socket which has never been connected does
1173 * not return write or hangup events, but Linux returns
1174 * POLLOUT | POLLHUP. */
1175 if (sock->state == SOCK_UNCONNECTED)
1176 return -1;
1178 if (flags & (AFD_POLL_READ | AFD_POLL_ACCEPT))
1179 ev |= POLLIN;
1180 if ((flags & AFD_POLL_HUP) && sock->type == WS_SOCK_STREAM)
1181 ev |= POLLIN;
1182 if (flags & AFD_POLL_OOB)
1183 ev |= is_oobinline( sock ) ? POLLIN : POLLPRI;
1184 if (flags & AFD_POLL_WRITE)
1185 ev |= POLLOUT;
1187 return ev;
1190 static int sock_get_poll_events( struct fd *fd )
1192 struct sock *sock = get_fd_user( fd );
1193 unsigned int mask = sock->mask & ~sock->reported_events;
1194 struct poll_req *req;
1195 int ev = 0;
1197 assert( sock->obj.ops == &sock_ops );
1199 if (!sock->type) /* not initialized yet */
1200 return -1;
1202 switch (sock->state)
1204 case SOCK_UNCONNECTED:
1205 /* A connection-mode Windows socket which has never been connected does
1206 * not return any events, but Linux returns POLLOUT | POLLHUP. Hence we
1207 * need to return -1 here, to prevent the socket from being polled on at
1208 * all. */
1209 return -1;
1211 case SOCK_CONNECTING:
1212 return POLLOUT;
1214 case SOCK_LISTENING:
1215 if (!list_empty( &sock->accept_list ) || (mask & AFD_POLL_ACCEPT))
1216 ev |= POLLIN;
1217 break;
1219 case SOCK_CONNECTED:
1220 case SOCK_CONNECTIONLESS:
1221 if (sock->hangup && sock->wr_shutdown && !sock->wr_shutdown_pending)
1223 /* Linux returns POLLHUP if a socket is both SHUT_RD and SHUT_WR, or
1224 * if both the socket and its peer are SHUT_WR.
1226 * We don't use SHUT_RD, so we can only encounter this in the latter
1227 * case. In that case there can't be any pending read requests (they
1228 * would have already been completed with a length of zero), the
1229 * above condition ensures that we don't have any pending write
1230 * requests, and nothing that can change about the socket state that
1231 * would complete a pending poll request. */
1232 return -1;
1235 if (sock->aborted)
1236 return -1;
1238 if (sock->accept_recv_req)
1240 ev |= POLLIN;
1242 else if (async_queued( &sock->read_q ))
1244 if (async_waiting( &sock->read_q )) ev |= POLLIN | POLLPRI;
1246 else
1248 /* Don't ask for POLLIN if we got a hangup. We won't receive more
1249 * data anyway, but we will get POLLIN if SOCK_SHUTDOWN_EOF. */
1250 if (!sock->hangup)
1252 if (mask & AFD_POLL_READ)
1253 ev |= POLLIN;
1254 if (mask & AFD_POLL_OOB)
1255 ev |= POLLPRI;
1258 /* We use POLLIN with 0 bytes recv() as hangup indication for stream sockets. */
1259 if (sock->state == SOCK_CONNECTED && (mask & AFD_POLL_HUP) && !(sock->reported_events & AFD_POLL_READ))
1260 ev |= POLLIN;
1263 if (async_queued( &sock->write_q ))
1265 if (async_waiting( &sock->write_q )) ev |= POLLOUT;
1267 else if (!sock->wr_shutdown && (mask & AFD_POLL_WRITE))
1269 ev |= POLLOUT;
1272 break;
1275 LIST_FOR_EACH_ENTRY( req, &poll_list, struct poll_req, entry )
1277 unsigned int i;
1279 for (i = 0; i < req->count; ++i)
1281 if (req->sockets[i].sock != sock) continue;
1283 ev |= poll_flags_from_afd( sock, req->sockets[i].mask );
1287 return ev;
1290 static enum server_fd_type sock_get_fd_type( struct fd *fd )
1292 return FD_TYPE_SOCKET;
1295 static void sock_cancel_async( struct fd *fd, struct async *async )
1297 struct poll_req *req;
1299 LIST_FOR_EACH_ENTRY( req, &poll_list, struct poll_req, entry )
1301 unsigned int i;
1303 if (req->async != async)
1304 continue;
1306 for (i = 0; i < req->count; i++)
1308 struct sock *sock = req->sockets[i].sock;
1310 if (sock->main_poll == req)
1311 sock->main_poll = NULL;
1315 async_terminate( async, STATUS_CANCELLED );
1318 static void sock_queue_async( struct fd *fd, struct async *async, int type, int count )
1320 struct sock *sock = get_fd_user( fd );
1321 struct async_queue *queue;
1323 assert( sock->obj.ops == &sock_ops );
1325 switch (type)
1327 case ASYNC_TYPE_READ:
1328 if (sock->rd_shutdown)
1330 set_error( STATUS_PIPE_DISCONNECTED );
1331 return;
1333 queue = &sock->read_q;
1334 break;
1336 case ASYNC_TYPE_WRITE:
1337 if (sock->wr_shutdown)
1339 set_error( STATUS_PIPE_DISCONNECTED );
1340 return;
1342 queue = &sock->write_q;
1343 break;
1345 default:
1346 set_error( STATUS_INVALID_PARAMETER );
1347 return;
1350 if (sock->state != SOCK_CONNECTED)
1352 set_error( STATUS_PIPE_DISCONNECTED );
1353 return;
1356 queue_async( queue, async );
1357 sock_reselect( sock );
1359 set_error( STATUS_PENDING );
1362 static void sock_reselect_async( struct fd *fd, struct async_queue *queue )
1364 struct sock *sock = get_fd_user( fd );
1366 if (sock->wr_shutdown_pending && list_empty( &sock->write_q.queue ))
1368 shutdown( get_unix_fd( sock->fd ), SHUT_WR );
1369 sock->wr_shutdown_pending = 0;
1372 /* Don't reselect the ifchange queue; we always ask for POLLIN.
1373 * Don't reselect an uninitialized socket; we can't call set_fd_events() on
1374 * a pseudo-fd. */
1375 if (queue != &sock->ifchange_q && sock->type)
1376 sock_reselect( sock );
1379 static struct fd *sock_get_fd( struct object *obj )
1381 struct sock *sock = (struct sock *)obj;
1382 return (struct fd *)grab_object( sock->fd );
1385 static int sock_close_handle( struct object *obj, struct process *process, obj_handle_t handle )
1387 struct sock *sock = (struct sock *)obj;
1389 if (sock->obj.handle_count == 1) /* last handle */
1391 struct accept_req *accept_req, *accept_next;
1392 struct poll_req *poll_req, *poll_next;
1394 if (sock->accept_recv_req)
1395 async_terminate( sock->accept_recv_req->async, STATUS_CANCELLED );
1397 LIST_FOR_EACH_ENTRY_SAFE( accept_req, accept_next, &sock->accept_list, struct accept_req, entry )
1398 async_terminate( accept_req->async, STATUS_CANCELLED );
1400 if (sock->connect_req)
1401 async_terminate( sock->connect_req->async, STATUS_CANCELLED );
1403 LIST_FOR_EACH_ENTRY_SAFE( poll_req, poll_next, &poll_list, struct poll_req, entry )
1405 struct iosb *iosb = poll_req->iosb;
1406 BOOL signaled = FALSE;
1407 unsigned int i;
1409 if (iosb->status != STATUS_PENDING) continue;
1411 for (i = 0; i < poll_req->count; ++i)
1413 if (poll_req->sockets[i].sock == sock)
1415 signaled = TRUE;
1416 poll_req->sockets[i].flags = AFD_POLL_CLOSE;
1417 poll_req->sockets[i].status = 0;
1421 if (signaled) complete_async_poll( poll_req, STATUS_SUCCESS );
1425 return 1;
1428 static void sock_destroy( struct object *obj )
1430 struct sock *sock = (struct sock *)obj;
1432 assert( obj->ops == &sock_ops );
1434 /* FIXME: special socket shutdown stuff? */
1436 if ( sock->deferred )
1437 release_object( sock->deferred );
1439 async_wake_up( &sock->ifchange_q, STATUS_CANCELLED );
1440 sock_release_ifchange( sock );
1441 free_async_queue( &sock->read_q );
1442 free_async_queue( &sock->write_q );
1443 free_async_queue( &sock->ifchange_q );
1444 free_async_queue( &sock->accept_q );
1445 free_async_queue( &sock->connect_q );
1446 free_async_queue( &sock->poll_q );
1447 if (sock->event) release_object( sock->event );
1448 if (sock->fd)
1450 /* shut the socket down to force pending poll() calls in the client to return */
1451 shutdown( get_unix_fd(sock->fd), SHUT_RDWR );
1452 release_object( sock->fd );
1456 static struct sock *create_socket(void)
1458 struct sock *sock;
1460 if (!(sock = alloc_object( &sock_ops ))) return NULL;
1461 sock->fd = NULL;
1462 sock->state = SOCK_UNCONNECTED;
1463 sock->mask = 0;
1464 sock->pending_events = 0;
1465 sock->reported_events = 0;
1466 sock->flags = 0;
1467 sock->proto = 0;
1468 sock->type = 0;
1469 sock->family = 0;
1470 sock->event = NULL;
1471 sock->window = 0;
1472 sock->message = 0;
1473 sock->wparam = 0;
1474 sock->connect_time = 0;
1475 sock->deferred = NULL;
1476 sock->ifchange_obj = NULL;
1477 sock->accept_recv_req = NULL;
1478 sock->connect_req = NULL;
1479 sock->main_poll = NULL;
1480 memset( &sock->addr, 0, sizeof(sock->addr) );
1481 sock->addr_len = 0;
1482 sock->rd_shutdown = 0;
1483 sock->wr_shutdown = 0;
1484 sock->wr_shutdown_pending = 0;
1485 sock->hangup = 0;
1486 sock->aborted = 0;
1487 sock->nonblocking = 0;
1488 sock->bound = 0;
1489 sock->rcvbuf = 0;
1490 sock->sndbuf = 0;
1491 sock->rcvtimeo = 0;
1492 sock->sndtimeo = 0;
1493 init_async_queue( &sock->read_q );
1494 init_async_queue( &sock->write_q );
1495 init_async_queue( &sock->ifchange_q );
1496 init_async_queue( &sock->accept_q );
1497 init_async_queue( &sock->connect_q );
1498 init_async_queue( &sock->poll_q );
1499 memset( sock->errors, 0, sizeof(sock->errors) );
1500 list_init( &sock->accept_list );
1501 return sock;
1504 static int get_unix_family( int family )
1506 switch (family)
1508 case WS_AF_INET: return AF_INET;
1509 case WS_AF_INET6: return AF_INET6;
1510 #ifdef HAS_IPX
1511 case WS_AF_IPX: return AF_IPX;
1512 #endif
1513 #ifdef AF_IRDA
1514 case WS_AF_IRDA: return AF_IRDA;
1515 #endif
1516 case WS_AF_UNSPEC: return AF_UNSPEC;
1517 default: return -1;
1521 static int get_unix_type( int type )
1523 switch (type)
1525 case WS_SOCK_DGRAM: return SOCK_DGRAM;
1526 case WS_SOCK_RAW: return SOCK_RAW;
1527 case WS_SOCK_STREAM: return SOCK_STREAM;
1528 default: return -1;
1532 static int get_unix_protocol( int protocol )
1534 if (protocol >= WS_NSPROTO_IPX && protocol <= WS_NSPROTO_IPX + 255)
1535 return protocol;
1537 switch (protocol)
1539 case WS_IPPROTO_ICMP: return IPPROTO_ICMP;
1540 case WS_IPPROTO_IGMP: return IPPROTO_IGMP;
1541 case WS_IPPROTO_IP: return IPPROTO_IP;
1542 case WS_IPPROTO_IPV4: return IPPROTO_IPIP;
1543 case WS_IPPROTO_IPV6: return IPPROTO_IPV6;
1544 case WS_IPPROTO_RAW: return IPPROTO_RAW;
1545 case WS_IPPROTO_TCP: return IPPROTO_TCP;
1546 case WS_IPPROTO_UDP: return IPPROTO_UDP;
1547 default: return -1;
1551 static void set_dont_fragment( int fd, int level, int value )
1553 int optname;
1555 if (level == IPPROTO_IP)
1557 #ifdef IP_DONTFRAG
1558 optname = IP_DONTFRAG;
1559 #elif defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO) && defined(IP_PMTUDISC_DONT)
1560 optname = IP_MTU_DISCOVER;
1561 value = value ? IP_PMTUDISC_DO : IP_PMTUDISC_DONT;
1562 #else
1563 return;
1564 #endif
1566 else
1568 #ifdef IPV6_DONTFRAG
1569 optname = IPV6_DONTFRAG;
1570 #elif defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO) && defined(IPV6_PMTUDISC_DONT)
1571 optname = IPV6_MTU_DISCOVER;
1572 value = value ? IPV6_PMTUDISC_DO : IPV6_PMTUDISC_DONT;
1573 #else
1574 return;
1575 #endif
1578 setsockopt( fd, level, optname, &value, sizeof(value) );
1581 static int init_socket( struct sock *sock, int family, int type, int protocol, unsigned int flags )
1583 unsigned int options = 0;
1584 int sockfd, unix_type, unix_family, unix_protocol, value;
1585 socklen_t len;
1587 unix_family = get_unix_family( family );
1588 unix_type = get_unix_type( type );
1589 unix_protocol = get_unix_protocol( protocol );
1591 if (unix_protocol < 0)
1593 if (type && unix_type < 0)
1594 set_win32_error( WSAESOCKTNOSUPPORT );
1595 else
1596 set_win32_error( WSAEPROTONOSUPPORT );
1597 return -1;
1599 if (unix_family < 0)
1601 if (family >= 0 && unix_type < 0)
1602 set_win32_error( WSAESOCKTNOSUPPORT );
1603 else
1604 set_win32_error( WSAEAFNOSUPPORT );
1605 return -1;
1608 sockfd = socket( unix_family, unix_type, unix_protocol );
1609 if (sockfd == -1)
1611 if (errno == EINVAL) set_win32_error( WSAESOCKTNOSUPPORT );
1612 else set_win32_error( sock_get_error( errno ));
1613 return -1;
1615 fcntl(sockfd, F_SETFL, O_NONBLOCK); /* make socket nonblocking */
1617 if (family == WS_AF_IPX && protocol >= WS_NSPROTO_IPX && protocol <= WS_NSPROTO_IPX + 255)
1619 #ifdef HAS_IPX
1620 int ipx_type = protocol - WS_NSPROTO_IPX;
1622 #ifdef SOL_IPX
1623 setsockopt( sockfd, SOL_IPX, IPX_TYPE, &ipx_type, sizeof(ipx_type) );
1624 #else
1625 struct ipx val;
1626 /* Should we retrieve val using a getsockopt call and then
1627 * set the modified one? */
1628 val.ipx_pt = ipx_type;
1629 setsockopt( sockfd, 0, SO_DEFAULT_HEADERS, &val, sizeof(val) );
1630 #endif
1631 #endif
1634 if (unix_family == AF_INET || unix_family == AF_INET6)
1636 /* ensure IP_DONTFRAGMENT is disabled for SOCK_DGRAM and SOCK_RAW, enabled for SOCK_STREAM */
1637 if (unix_type == SOCK_DGRAM || unix_type == SOCK_RAW) /* in Linux the global default can be enabled */
1638 set_dont_fragment( sockfd, unix_family == AF_INET6 ? IPPROTO_IPV6 : IPPROTO_IP, FALSE );
1639 else if (unix_type == SOCK_STREAM)
1640 set_dont_fragment( sockfd, unix_family == AF_INET6 ? IPPROTO_IPV6 : IPPROTO_IP, TRUE );
1643 #ifdef IPV6_V6ONLY
1644 if (unix_family == AF_INET6)
1646 static const int enable = 1;
1647 setsockopt( sockfd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable) );
1649 #endif
1651 len = sizeof(value);
1652 if (!getsockopt( sockfd, SOL_SOCKET, SO_RCVBUF, &value, &len ))
1653 sock->rcvbuf = value;
1655 len = sizeof(value);
1656 if (!getsockopt( sockfd, SOL_SOCKET, SO_SNDBUF, &value, &len ))
1657 sock->sndbuf = value;
1659 sock->state = (type == WS_SOCK_STREAM ? SOCK_UNCONNECTED : SOCK_CONNECTIONLESS);
1660 sock->flags = flags;
1661 sock->proto = protocol;
1662 sock->type = type;
1663 sock->family = family;
1665 if (sock->fd)
1667 options = get_fd_options( sock->fd );
1668 release_object( sock->fd );
1671 if (!(sock->fd = create_anonymous_fd( &sock_fd_ops, sockfd, &sock->obj, options )))
1673 return -1;
1676 /* We can't immediately allow caching for a connection-mode socket, since it
1677 * might be accepted into (changing the underlying fd object.) */
1678 if (sock->type != WS_SOCK_STREAM) allow_fd_caching( sock->fd );
1680 return 0;
1683 /* accepts a socket and inits it */
1684 static int accept_new_fd( struct sock *sock )
1687 /* Try to accept(2). We can't be safe that this an already connected socket
1688 * or that accept() is allowed on it. In those cases we will get -1/errno
1689 * return.
1691 struct sockaddr saddr;
1692 socklen_t slen = sizeof(saddr);
1693 int acceptfd = accept( get_unix_fd(sock->fd), &saddr, &slen );
1694 if (acceptfd != -1)
1695 fcntl( acceptfd, F_SETFL, O_NONBLOCK );
1696 else
1697 set_error( sock_get_ntstatus( errno ));
1698 return acceptfd;
1701 /* accept a socket (creates a new fd) */
1702 static struct sock *accept_socket( struct sock *sock )
1704 struct sock *acceptsock;
1705 int acceptfd;
1707 if (get_unix_fd( sock->fd ) == -1) return NULL;
1709 if ( sock->deferred )
1711 acceptsock = sock->deferred;
1712 sock->deferred = NULL;
1714 else
1716 union unix_sockaddr unix_addr;
1717 socklen_t unix_len;
1719 if ((acceptfd = accept_new_fd( sock )) == -1) return NULL;
1720 if (!(acceptsock = create_socket()))
1722 close( acceptfd );
1723 return NULL;
1726 /* newly created socket gets the same properties of the listening socket */
1727 acceptsock->state = SOCK_CONNECTED;
1728 acceptsock->bound = 1;
1729 acceptsock->nonblocking = sock->nonblocking;
1730 acceptsock->mask = sock->mask;
1731 acceptsock->proto = sock->proto;
1732 acceptsock->type = sock->type;
1733 acceptsock->family = sock->family;
1734 acceptsock->window = sock->window;
1735 acceptsock->message = sock->message;
1736 acceptsock->connect_time = current_time;
1737 if (sock->event) acceptsock->event = (struct event *)grab_object( sock->event );
1738 acceptsock->flags = sock->flags;
1739 if (!(acceptsock->fd = create_anonymous_fd( &sock_fd_ops, acceptfd, &acceptsock->obj,
1740 get_fd_options( sock->fd ) )))
1742 release_object( acceptsock );
1743 return NULL;
1745 unix_len = sizeof(unix_addr);
1746 if (!getsockname( acceptfd, &unix_addr.addr, &unix_len ))
1747 acceptsock->addr_len = sockaddr_from_unix( &unix_addr, &acceptsock->addr.addr, sizeof(acceptsock->addr) );
1749 clear_error();
1750 sock->pending_events &= ~AFD_POLL_ACCEPT;
1751 sock->reported_events &= ~AFD_POLL_ACCEPT;
1752 sock_reselect( sock );
1753 return acceptsock;
1756 static int accept_into_socket( struct sock *sock, struct sock *acceptsock )
1758 union unix_sockaddr unix_addr;
1759 socklen_t unix_len;
1760 int acceptfd;
1761 struct fd *newfd;
1763 if (get_unix_fd( sock->fd ) == -1) return FALSE;
1765 if ( sock->deferred )
1767 newfd = dup_fd_object( sock->deferred->fd, 0, 0,
1768 get_fd_options( acceptsock->fd ) );
1769 if ( !newfd )
1770 return FALSE;
1772 set_fd_user( newfd, &sock_fd_ops, &acceptsock->obj );
1774 release_object( sock->deferred );
1775 sock->deferred = NULL;
1777 else
1779 if ((acceptfd = accept_new_fd( sock )) == -1)
1780 return FALSE;
1782 if (!(newfd = create_anonymous_fd( &sock_fd_ops, acceptfd, &acceptsock->obj,
1783 get_fd_options( acceptsock->fd ) )))
1784 return FALSE;
1787 acceptsock->state = SOCK_CONNECTED;
1788 acceptsock->pending_events = 0;
1789 acceptsock->reported_events = 0;
1790 acceptsock->proto = sock->proto;
1791 acceptsock->type = sock->type;
1792 acceptsock->family = sock->family;
1793 acceptsock->wparam = 0;
1794 acceptsock->deferred = NULL;
1795 acceptsock->connect_time = current_time;
1796 fd_copy_completion( acceptsock->fd, newfd );
1797 release_object( acceptsock->fd );
1798 acceptsock->fd = newfd;
1800 unix_len = sizeof(unix_addr);
1801 if (!getsockname( get_unix_fd( newfd ), &unix_addr.addr, &unix_len ))
1802 acceptsock->addr_len = sockaddr_from_unix( &unix_addr, &acceptsock->addr.addr, sizeof(acceptsock->addr) );
1804 clear_error();
1805 sock->pending_events &= ~AFD_POLL_ACCEPT;
1806 sock->reported_events &= ~AFD_POLL_ACCEPT;
1807 sock_reselect( sock );
1809 return TRUE;
1812 #ifdef IP_BOUND_IF
1814 static int bind_to_iface_name( int fd, in_addr_t bind_addr, const char *name )
1816 static const int enable = 1;
1817 unsigned int index;
1819 if (!(index = if_nametoindex( name )))
1820 return -1;
1822 if (setsockopt( fd, IPPROTO_IP, IP_BOUND_IF, &index, sizeof(index) ))
1823 return -1;
1825 return setsockopt( fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable) );
1828 #elif defined(IP_UNICAST_IF) && defined(SO_ATTACH_FILTER) && defined(SO_BINDTODEVICE)
1830 struct interface_filter
1832 struct sock_filter iface_memaddr;
1833 struct sock_filter iface_rule;
1834 struct sock_filter ip_memaddr;
1835 struct sock_filter ip_rule;
1836 struct sock_filter return_keep;
1837 struct sock_filter return_dump;
1839 # define FILTER_JUMP_DUMP(here) (u_char)(offsetof(struct interface_filter, return_dump) \
1840 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
1841 /sizeof(struct sock_filter)
1842 # define FILTER_JUMP_KEEP(here) (u_char)(offsetof(struct interface_filter, return_keep) \
1843 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
1844 /sizeof(struct sock_filter)
1845 # define FILTER_JUMP_NEXT() (u_char)(0)
1846 # define SKF_NET_DESTIP 16 /* offset in the network header to the destination IP */
1847 static struct interface_filter generic_interface_filter =
1849 /* This filter rule allows incoming packets on the specified interface, which works for all
1850 * remotely generated packets and for locally generated broadcast packets. */
1851 BPF_STMT(BPF_LD+BPF_W+BPF_ABS, SKF_AD_OFF+SKF_AD_IFINDEX),
1852 BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0xdeadbeef, FILTER_JUMP_KEEP(iface_rule), FILTER_JUMP_NEXT()),
1853 /* This rule allows locally generated packets targeted at the specific IP address of the chosen
1854 * adapter (local packets not destined for the broadcast address do not have IFINDEX set) */
1855 BPF_STMT(BPF_LD+BPF_W+BPF_ABS, SKF_NET_OFF+SKF_NET_DESTIP),
1856 BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0xdeadbeef, FILTER_JUMP_KEEP(ip_rule), FILTER_JUMP_DUMP(ip_rule)),
1857 BPF_STMT(BPF_RET+BPF_K, (u_int)-1), /* keep packet */
1858 BPF_STMT(BPF_RET+BPF_K, 0) /* dump packet */
1861 static int bind_to_iface_name( int fd, in_addr_t bind_addr, const char *name )
1863 struct interface_filter specific_interface_filter;
1864 struct sock_fprog filter_prog;
1865 static const int enable = 1;
1866 unsigned int index;
1867 in_addr_t ifindex;
1869 if (!setsockopt( fd, SOL_SOCKET, SO_BINDTODEVICE, name, strlen( name ) + 1 ))
1870 return 0;
1872 /* SO_BINDTODEVICE requires NET_CAP_RAW until Linux 5.7. */
1873 if (debug_level)
1874 fprintf( stderr, "setsockopt SO_BINDTODEVICE fd %d, name %s failed: %s, falling back to SO_REUSE_ADDR\n",
1875 fd, name, strerror( errno ));
1877 if (!(index = if_nametoindex( name )))
1878 return -1;
1880 ifindex = htonl( index );
1881 if (setsockopt( fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, sizeof(ifindex) ) < 0)
1882 return -1;
1884 specific_interface_filter = generic_interface_filter;
1885 specific_interface_filter.iface_rule.k = index;
1886 specific_interface_filter.ip_rule.k = htonl( bind_addr );
1887 filter_prog.len = sizeof(generic_interface_filter) / sizeof(struct sock_filter);
1888 filter_prog.filter = (struct sock_filter *)&specific_interface_filter;
1889 if (setsockopt( fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog, sizeof(filter_prog) ))
1890 return -1;
1892 return setsockopt( fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable) );
1895 #else
1897 static int bind_to_iface_name( int fd, in_addr_t bind_addr, const char *name )
1899 errno = EOPNOTSUPP;
1900 return -1;
1903 #endif /* LINUX_BOUND_IF */
1905 /* Take bind() calls on any name corresponding to a local network adapter and
1906 * restrict the given socket to operating only on the specified interface. This
1907 * restriction consists of two components:
1908 * 1) An outgoing packet restriction suggesting the egress interface for all
1909 * packets.
1910 * 2) An incoming packet restriction dropping packets not meant for the
1911 * interface.
1912 * If the function succeeds in placing these restrictions, then the name for the
1913 * bind() may safely be changed to INADDR_ANY, permitting the transmission and
1914 * receipt of broadcast packets on the socket. This behavior is only relevant to
1915 * UDP sockets and is needed for applications that expect to be able to receive
1916 * broadcast packets on a socket that is bound to a specific network interface.
1918 static int bind_to_interface( struct sock *sock, const struct sockaddr_in *addr )
1920 in_addr_t bind_addr = addr->sin_addr.s_addr;
1921 struct ifaddrs *ifaddrs, *ifaddr;
1922 int fd = get_unix_fd( sock->fd );
1923 int err = 0;
1925 if (bind_addr == htonl( INADDR_ANY ) || bind_addr == htonl( INADDR_LOOPBACK ))
1926 return 0;
1927 if (sock->type != WS_SOCK_DGRAM)
1928 return 0;
1930 if (getifaddrs( &ifaddrs ) < 0) return 0;
1932 for (ifaddr = ifaddrs; ifaddr != NULL; ifaddr = ifaddr->ifa_next)
1934 if (ifaddr->ifa_addr && ifaddr->ifa_addr->sa_family == AF_INET
1935 && ((struct sockaddr_in *)ifaddr->ifa_addr)->sin_addr.s_addr == bind_addr)
1937 if ((err = bind_to_iface_name( fd, bind_addr, ifaddr->ifa_name )) < 0)
1939 if (debug_level)
1940 fprintf( stderr, "failed to bind to interface: %s\n", strerror( errno ) );
1942 break;
1945 freeifaddrs( ifaddrs );
1946 return !err;
1949 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1950 static unsigned int get_ipv6_interface_index( const struct in6_addr *addr )
1952 struct ifaddrs *ifaddrs, *ifaddr;
1954 if (getifaddrs( &ifaddrs ) < 0) return 0;
1956 for (ifaddr = ifaddrs; ifaddr != NULL; ifaddr = ifaddr->ifa_next)
1958 if (ifaddr->ifa_addr && ifaddr->ifa_addr->sa_family == AF_INET6
1959 && !memcmp( &((struct sockaddr_in6 *)ifaddr->ifa_addr)->sin6_addr, addr, sizeof(*addr) ))
1961 unsigned int index = if_nametoindex( ifaddr->ifa_name );
1963 if (!index)
1965 if (debug_level)
1966 fprintf( stderr, "Unable to look up interface index for %s: %s\n",
1967 ifaddr->ifa_name, strerror( errno ) );
1968 continue;
1971 freeifaddrs( ifaddrs );
1972 return index;
1976 freeifaddrs( ifaddrs );
1977 return 0;
1979 #endif
1981 /* return an errno value mapped to a WSA error */
1982 static unsigned int sock_get_error( int err )
1984 switch (err)
1986 case EINTR: return WSAEINTR;
1987 case EBADF: return WSAEBADF;
1988 case EPERM:
1989 case EACCES: return WSAEACCES;
1990 case EFAULT: return WSAEFAULT;
1991 case EINVAL: return WSAEINVAL;
1992 case EMFILE: return WSAEMFILE;
1993 case EINPROGRESS:
1994 case EWOULDBLOCK: return WSAEWOULDBLOCK;
1995 case EALREADY: return WSAEALREADY;
1996 case ENOTSOCK: return WSAENOTSOCK;
1997 case EDESTADDRREQ: return WSAEDESTADDRREQ;
1998 case EMSGSIZE: return WSAEMSGSIZE;
1999 case EPROTOTYPE: return WSAEPROTOTYPE;
2000 case ENOPROTOOPT: return WSAENOPROTOOPT;
2001 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
2002 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
2003 case EOPNOTSUPP: return WSAEOPNOTSUPP;
2004 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
2005 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
2006 case EADDRINUSE: return WSAEADDRINUSE;
2007 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
2008 case ENETDOWN: return WSAENETDOWN;
2009 case ENETUNREACH: return WSAENETUNREACH;
2010 case ENETRESET: return WSAENETRESET;
2011 case ECONNABORTED: return WSAECONNABORTED;
2012 case EPIPE:
2013 case ECONNRESET: return WSAECONNRESET;
2014 case ENOBUFS: return WSAENOBUFS;
2015 case EISCONN: return WSAEISCONN;
2016 case ENOTCONN: return WSAENOTCONN;
2017 case ESHUTDOWN: return WSAESHUTDOWN;
2018 case ETOOMANYREFS: return WSAETOOMANYREFS;
2019 case ETIMEDOUT: return WSAETIMEDOUT;
2020 case ECONNREFUSED: return WSAECONNREFUSED;
2021 case ELOOP: return WSAELOOP;
2022 case ENAMETOOLONG: return WSAENAMETOOLONG;
2023 case EHOSTDOWN: return WSAEHOSTDOWN;
2024 case EHOSTUNREACH: return WSAEHOSTUNREACH;
2025 case ENOTEMPTY: return WSAENOTEMPTY;
2026 #ifdef EPROCLIM
2027 case EPROCLIM: return WSAEPROCLIM;
2028 #endif
2029 #ifdef EUSERS
2030 case EUSERS: return WSAEUSERS;
2031 #endif
2032 #ifdef EDQUOT
2033 case EDQUOT: return WSAEDQUOT;
2034 #endif
2035 #ifdef ESTALE
2036 case ESTALE: return WSAESTALE;
2037 #endif
2038 #ifdef EREMOTE
2039 case EREMOTE: return WSAEREMOTE;
2040 #endif
2042 case 0: return 0;
2043 default:
2044 errno = err;
2045 perror("wineserver: sock_get_error() can't map error");
2046 return WSAEFAULT;
2050 static int sock_get_ntstatus( int err )
2052 switch ( err )
2054 case EBADF: return STATUS_INVALID_HANDLE;
2055 case EBUSY: return STATUS_DEVICE_BUSY;
2056 case EPERM:
2057 case EACCES: return STATUS_ACCESS_DENIED;
2058 case EFAULT: return STATUS_ACCESS_VIOLATION;
2059 case EINVAL: return STATUS_INVALID_PARAMETER;
2060 case ENFILE:
2061 case EMFILE: return STATUS_TOO_MANY_OPENED_FILES;
2062 case EINPROGRESS:
2063 case EWOULDBLOCK: return STATUS_DEVICE_NOT_READY;
2064 case EALREADY: return STATUS_NETWORK_BUSY;
2065 case ENOTSOCK: return STATUS_OBJECT_TYPE_MISMATCH;
2066 case EDESTADDRREQ: return STATUS_INVALID_PARAMETER;
2067 case EMSGSIZE: return STATUS_BUFFER_OVERFLOW;
2068 case EPROTONOSUPPORT:
2069 case ESOCKTNOSUPPORT:
2070 case EPFNOSUPPORT:
2071 case EAFNOSUPPORT:
2072 case EPROTOTYPE: return STATUS_NOT_SUPPORTED;
2073 case ENOPROTOOPT: return STATUS_INVALID_PARAMETER;
2074 case EOPNOTSUPP: return STATUS_NOT_SUPPORTED;
2075 case EADDRINUSE: return STATUS_SHARING_VIOLATION;
2076 /* Linux returns ENODEV when specifying an invalid sin6_scope_id;
2077 * Windows returns STATUS_INVALID_ADDRESS_COMPONENT */
2078 case ENODEV:
2079 case EADDRNOTAVAIL: return STATUS_INVALID_ADDRESS_COMPONENT;
2080 case ECONNREFUSED: return STATUS_CONNECTION_REFUSED;
2081 case ESHUTDOWN: return STATUS_PIPE_DISCONNECTED;
2082 case ENOTCONN: return STATUS_INVALID_CONNECTION;
2083 case ETIMEDOUT: return STATUS_IO_TIMEOUT;
2084 case ENETUNREACH: return STATUS_NETWORK_UNREACHABLE;
2085 case EHOSTUNREACH: return STATUS_HOST_UNREACHABLE;
2086 case ENETDOWN: return STATUS_NETWORK_BUSY;
2087 case EPIPE:
2088 case ECONNRESET: return STATUS_CONNECTION_RESET;
2089 case ECONNABORTED: return STATUS_CONNECTION_ABORTED;
2090 case EISCONN: return STATUS_CONNECTION_ACTIVE;
2092 case 0: return STATUS_SUCCESS;
2093 default:
2094 errno = err;
2095 perror("wineserver: sock_get_ntstatus() can't map error");
2096 return STATUS_UNSUCCESSFUL;
2100 static struct accept_req *alloc_accept_req( struct sock *sock, struct sock *acceptsock, struct async *async,
2101 const struct afd_accept_into_params *params )
2103 struct accept_req *req = mem_alloc( sizeof(*req) );
2105 if (req)
2107 req->async = (struct async *)grab_object( async );
2108 req->iosb = async_get_iosb( async );
2109 req->sock = (struct sock *)grab_object( sock );
2110 req->acceptsock = acceptsock;
2111 if (acceptsock) grab_object( acceptsock );
2112 req->accepted = 0;
2113 req->recv_len = 0;
2114 req->local_len = 0;
2115 if (params)
2117 req->recv_len = params->recv_len;
2118 req->local_len = params->local_len;
2121 return req;
2124 static void sock_ioctl( struct fd *fd, ioctl_code_t code, struct async *async )
2126 struct sock *sock = get_fd_user( fd );
2127 int unix_fd;
2129 assert( sock->obj.ops == &sock_ops );
2131 if (code != IOCTL_AFD_WINE_CREATE && (unix_fd = get_unix_fd( fd )) < 0) return;
2133 switch(code)
2135 case IOCTL_AFD_WINE_CREATE:
2137 const struct afd_create_params *params = get_req_data();
2139 if (get_req_data_size() != sizeof(*params))
2141 set_error( STATUS_INVALID_PARAMETER );
2142 return;
2144 init_socket( sock, params->family, params->type, params->protocol, params->flags );
2145 return;
2148 case IOCTL_AFD_WINE_ACCEPT:
2150 struct sock *acceptsock;
2151 obj_handle_t handle;
2153 if (get_reply_max_size() != sizeof(handle))
2155 set_error( STATUS_BUFFER_TOO_SMALL );
2156 return;
2159 if (!(acceptsock = accept_socket( sock )))
2161 struct accept_req *req;
2163 if (sock->nonblocking) return;
2164 if (get_error() != STATUS_DEVICE_NOT_READY) return;
2166 if (!(req = alloc_accept_req( sock, NULL, async, NULL ))) return;
2167 list_add_tail( &sock->accept_list, &req->entry );
2169 async_set_completion_callback( async, free_accept_req, req );
2170 queue_async( &sock->accept_q, async );
2171 sock_reselect( sock );
2172 set_error( STATUS_PENDING );
2173 return;
2175 handle = alloc_handle( current->process, &acceptsock->obj,
2176 GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE, OBJ_INHERIT );
2177 acceptsock->wparam = handle;
2178 sock_reselect( acceptsock );
2179 release_object( acceptsock );
2180 set_reply_data( &handle, sizeof(handle) );
2181 return;
2184 case IOCTL_AFD_WINE_ACCEPT_INTO:
2186 static const int access = FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES | FILE_READ_DATA;
2187 const struct afd_accept_into_params *params = get_req_data();
2188 struct sock *acceptsock;
2189 unsigned int remote_len;
2190 struct accept_req *req;
2192 if (get_req_data_size() != sizeof(*params) ||
2193 get_reply_max_size() < params->recv_len ||
2194 get_reply_max_size() - params->recv_len < params->local_len)
2196 set_error( STATUS_BUFFER_TOO_SMALL );
2197 return;
2200 remote_len = get_reply_max_size() - params->recv_len - params->local_len;
2201 if (remote_len < sizeof(int))
2203 set_error( STATUS_INVALID_PARAMETER );
2204 return;
2207 if (!(acceptsock = (struct sock *)get_handle_obj( current->process, params->accept_handle, access, &sock_ops )))
2208 return;
2210 if (acceptsock->accept_recv_req)
2212 release_object( acceptsock );
2213 set_error( STATUS_INVALID_PARAMETER );
2214 return;
2217 if (!(req = alloc_accept_req( sock, acceptsock, async, params )))
2219 release_object( acceptsock );
2220 return;
2222 list_add_tail( &sock->accept_list, &req->entry );
2223 acceptsock->accept_recv_req = req;
2224 release_object( acceptsock );
2226 acceptsock->wparam = params->accept_handle;
2227 async_set_completion_callback( async, free_accept_req, req );
2228 queue_async( &sock->accept_q, async );
2229 sock_reselect( sock );
2230 set_error( STATUS_PENDING );
2231 return;
2234 case IOCTL_AFD_LISTEN:
2236 const struct afd_listen_params *params = get_req_data();
2238 if (get_req_data_size() < sizeof(*params))
2240 set_error( STATUS_INVALID_PARAMETER );
2241 return;
2244 if (!sock->bound)
2246 set_error( STATUS_INVALID_PARAMETER );
2247 return;
2250 if (listen( unix_fd, params->backlog ) < 0)
2252 set_error( sock_get_ntstatus( errno ) );
2253 return;
2256 sock->state = SOCK_LISTENING;
2258 /* a listening socket can no longer be accepted into */
2259 allow_fd_caching( sock->fd );
2261 /* we may already be selecting for AFD_POLL_ACCEPT */
2262 sock_reselect( sock );
2263 return;
2266 case IOCTL_AFD_WINE_CONNECT:
2268 const struct afd_connect_params *params = get_req_data();
2269 const struct WS_sockaddr *addr;
2270 union unix_sockaddr unix_addr;
2271 struct connect_req *req;
2272 socklen_t unix_len;
2273 int send_len, ret;
2275 if (get_req_data_size() < sizeof(*params) ||
2276 get_req_data_size() - sizeof(*params) < params->addr_len)
2278 set_error( STATUS_BUFFER_TOO_SMALL );
2279 return;
2281 send_len = get_req_data_size() - sizeof(*params) - params->addr_len;
2282 addr = (const struct WS_sockaddr *)(params + 1);
2284 if (!params->synchronous && !sock->bound)
2286 set_error( STATUS_INVALID_PARAMETER );
2287 return;
2290 if (sock->accept_recv_req)
2292 set_error( STATUS_INVALID_PARAMETER );
2293 return;
2296 if (sock->connect_req)
2298 set_error( STATUS_INVALID_PARAMETER );
2299 return;
2302 switch (sock->state)
2304 case SOCK_LISTENING:
2305 set_error( STATUS_INVALID_PARAMETER );
2306 return;
2308 case SOCK_CONNECTING:
2309 /* FIXME: STATUS_ADDRESS_ALREADY_ASSOCIATED probably isn't right,
2310 * but there's no status code that maps to WSAEALREADY... */
2311 set_error( params->synchronous ? STATUS_ADDRESS_ALREADY_ASSOCIATED : STATUS_INVALID_PARAMETER );
2312 return;
2314 case SOCK_CONNECTED:
2315 set_error( STATUS_CONNECTION_ACTIVE );
2316 return;
2318 case SOCK_UNCONNECTED:
2319 case SOCK_CONNECTIONLESS:
2320 break;
2323 unix_len = sockaddr_to_unix( addr, params->addr_len, &unix_addr );
2324 if (!unix_len)
2326 set_error( STATUS_INVALID_ADDRESS );
2327 return;
2329 if (unix_addr.addr.sa_family == AF_INET && !memcmp( &unix_addr.in.sin_addr, magic_loopback_addr, 4 ))
2330 unix_addr.in.sin_addr.s_addr = htonl( INADDR_LOOPBACK );
2332 ret = connect( unix_fd, &unix_addr.addr, unix_len );
2333 if (ret < 0 && errno != EINPROGRESS)
2335 set_error( sock_get_ntstatus( errno ) );
2336 return;
2339 /* a connected or connecting socket can no longer be accepted into */
2340 allow_fd_caching( sock->fd );
2342 unix_len = sizeof(unix_addr);
2343 if (!sock->bound && !getsockname( unix_fd, &unix_addr.addr, &unix_len ))
2344 sock->addr_len = sockaddr_from_unix( &unix_addr, &sock->addr.addr, sizeof(sock->addr) );
2345 sock->bound = 1;
2347 if (!ret)
2349 sock->state = SOCK_CONNECTED;
2351 if (!send_len) return;
2354 sock->state = SOCK_CONNECTING;
2356 if (params->synchronous && sock->nonblocking)
2358 sock_reselect( sock );
2359 set_error( STATUS_DEVICE_NOT_READY );
2360 return;
2363 if (!(req = mem_alloc( sizeof(*req) )))
2364 return;
2366 req->async = (struct async *)grab_object( async );
2367 req->iosb = async_get_iosb( async );
2368 req->sock = (struct sock *)grab_object( sock );
2369 req->addr_len = params->addr_len;
2370 req->send_len = send_len;
2371 req->send_cursor = 0;
2373 async_set_completion_callback( async, free_connect_req, req );
2374 sock->connect_req = req;
2375 queue_async( &sock->connect_q, async );
2376 sock_reselect( sock );
2377 set_error( STATUS_PENDING );
2378 return;
2381 case IOCTL_AFD_WINE_SHUTDOWN:
2383 unsigned int how;
2385 if (get_req_data_size() < sizeof(int))
2387 set_error( STATUS_BUFFER_TOO_SMALL );
2388 return;
2390 how = *(int *)get_req_data();
2392 if (how > SD_BOTH)
2394 set_error( STATUS_INVALID_PARAMETER );
2395 return;
2398 if (sock->state != SOCK_CONNECTED && sock->state != SOCK_CONNECTIONLESS)
2400 set_error( STATUS_INVALID_CONNECTION );
2401 return;
2404 if (how != SD_SEND)
2406 sock->rd_shutdown = 1;
2408 if (how != SD_RECEIVE)
2410 sock->wr_shutdown = 1;
2411 if (list_empty( &sock->write_q.queue ))
2412 shutdown( unix_fd, SHUT_WR );
2413 else
2414 sock->wr_shutdown_pending = 1;
2417 if (how == SD_BOTH)
2419 if (sock->event) release_object( sock->event );
2420 sock->event = NULL;
2421 sock->window = 0;
2422 sock->mask = 0;
2423 sock->nonblocking = 1;
2426 sock_reselect( sock );
2427 return;
2430 case IOCTL_AFD_WINE_ADDRESS_LIST_CHANGE:
2432 int force_async;
2434 if (get_req_data_size() < sizeof(int))
2436 set_error( STATUS_BUFFER_TOO_SMALL );
2437 return;
2439 force_async = *(int *)get_req_data();
2441 if (sock->nonblocking && !force_async)
2443 set_error( STATUS_DEVICE_NOT_READY );
2444 return;
2446 if (!sock_get_ifchange( sock )) return;
2447 queue_async( &sock->ifchange_q, async );
2448 set_error( STATUS_PENDING );
2449 return;
2452 case IOCTL_AFD_WINE_FIONBIO:
2453 if (get_req_data_size() < sizeof(int))
2455 set_error( STATUS_BUFFER_TOO_SMALL );
2456 return;
2458 if (*(int *)get_req_data())
2460 sock->nonblocking = 1;
2462 else
2464 if (sock->mask)
2466 set_error( STATUS_INVALID_PARAMETER );
2467 return;
2469 sock->nonblocking = 0;
2471 return;
2473 case IOCTL_AFD_GET_EVENTS:
2475 struct afd_get_events_params params = {0};
2476 unsigned int i;
2478 if (get_reply_max_size() < sizeof(params))
2480 set_error( STATUS_INVALID_PARAMETER );
2481 return;
2484 params.flags = sock->pending_events & sock->mask;
2485 for (i = 0; i < ARRAY_SIZE( params.status ); ++i)
2486 params.status[i] = sock_get_ntstatus( sock->errors[i] );
2488 sock->pending_events = 0;
2489 sock_reselect( sock );
2491 set_reply_data( &params, sizeof(params) );
2492 return;
2495 case IOCTL_AFD_EVENT_SELECT:
2497 struct event *event = NULL;
2498 obj_handle_t event_handle;
2499 int mask;
2501 set_async_pending( async );
2503 if (is_machine_64bit( current->process->machine ))
2505 const struct afd_event_select_params_64 *params = get_req_data();
2507 if (get_req_data_size() < sizeof(*params))
2509 set_error( STATUS_INVALID_PARAMETER );
2510 return;
2513 event_handle = params->event;
2514 mask = params->mask;
2516 else
2518 const struct afd_event_select_params_32 *params = get_req_data();
2520 if (get_req_data_size() < sizeof(*params))
2522 set_error( STATUS_INVALID_PARAMETER );
2523 return;
2526 event_handle = params->event;
2527 mask = params->mask;
2530 if ((event_handle || mask) &&
2531 !(event = get_event_obj( current->process, event_handle, EVENT_MODIFY_STATE )))
2533 set_error( STATUS_INVALID_PARAMETER );
2534 return;
2537 if (sock->event) release_object( sock->event );
2538 sock->event = event;
2539 sock->mask = mask;
2540 sock->window = 0;
2541 sock->message = 0;
2542 sock->wparam = 0;
2543 sock->nonblocking = 1;
2545 sock_reselect( sock );
2546 /* Explicitly wake the socket up if the mask causes it to become
2547 * signaled. Note that reselecting isn't enough, since we might already
2548 * have had events recorded in sock->reported_events and we don't want
2549 * to select for them again. */
2550 sock_wake_up( sock );
2552 return;
2555 case IOCTL_AFD_WINE_MESSAGE_SELECT:
2557 const struct afd_message_select_params *params = get_req_data();
2559 if (get_req_data_size() < sizeof(params))
2561 set_error( STATUS_BUFFER_TOO_SMALL );
2562 return;
2565 if (sock->event) release_object( sock->event );
2567 if (params->window)
2569 sock->pending_events = 0;
2570 sock->reported_events = 0;
2572 sock->event = NULL;
2573 sock->mask = params->mask;
2574 sock->window = params->window;
2575 sock->message = params->message;
2576 sock->wparam = params->handle;
2577 sock->nonblocking = 1;
2579 sock_reselect( sock );
2581 return;
2584 case IOCTL_AFD_BIND:
2586 const struct afd_bind_params *params = get_req_data();
2587 union unix_sockaddr unix_addr, bind_addr;
2588 data_size_t in_size;
2589 socklen_t unix_len;
2591 /* the ioctl is METHOD_NEITHER, so ntdll gives us the output buffer as
2592 * input */
2593 if (get_req_data_size() < get_reply_max_size())
2595 set_error( STATUS_BUFFER_TOO_SMALL );
2596 return;
2598 in_size = get_req_data_size() - get_reply_max_size();
2599 if (in_size < offsetof(struct afd_bind_params, addr.sa_data)
2600 || get_reply_max_size() < in_size - sizeof(int))
2602 set_error( STATUS_INVALID_PARAMETER );
2603 return;
2606 if (sock->bound)
2608 set_error( STATUS_ADDRESS_ALREADY_ASSOCIATED );
2609 return;
2612 unix_len = sockaddr_to_unix( &params->addr, in_size - sizeof(int), &unix_addr );
2613 if (!unix_len)
2615 set_error( STATUS_INVALID_ADDRESS );
2616 return;
2618 bind_addr = unix_addr;
2620 if (unix_addr.addr.sa_family == AF_INET)
2622 if (!memcmp( &unix_addr.in.sin_addr, magic_loopback_addr, 4 )
2623 || bind_to_interface( sock, &unix_addr.in ))
2624 bind_addr.in.sin_addr.s_addr = htonl( INADDR_ANY );
2626 else if (unix_addr.addr.sa_family == AF_INET6)
2628 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
2629 /* Windows allows specifying zero to use the default scope. Linux
2630 * interprets it as an interface index and requires that it be
2631 * nonzero. */
2632 if (!unix_addr.in6.sin6_scope_id)
2633 bind_addr.in6.sin6_scope_id = get_ipv6_interface_index( &unix_addr.in6.sin6_addr );
2634 #endif
2637 set_async_pending( async );
2639 if (bind( unix_fd, &bind_addr.addr, unix_len ) < 0)
2641 if (errno == EADDRINUSE)
2643 int reuse;
2644 socklen_t len = sizeof(reuse);
2646 if (!getsockopt( unix_fd, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, &len ) && reuse)
2647 errno = EACCES;
2650 set_error( sock_get_ntstatus( errno ) );
2651 return;
2654 sock->bound = 1;
2656 unix_len = sizeof(bind_addr);
2657 if (!getsockname( unix_fd, &bind_addr.addr, &unix_len ))
2659 /* store the interface or magic loopback address instead of the
2660 * actual unix address */
2661 if (bind_addr.addr.sa_family == AF_INET)
2662 bind_addr.in.sin_addr = unix_addr.in.sin_addr;
2663 sock->addr_len = sockaddr_from_unix( &bind_addr, &sock->addr.addr, sizeof(sock->addr) );
2666 if (get_reply_max_size() >= sock->addr_len)
2667 set_reply_data( &sock->addr, sock->addr_len );
2668 return;
2671 case IOCTL_AFD_GETSOCKNAME:
2672 if (!sock->bound)
2674 set_error( STATUS_INVALID_PARAMETER );
2675 return;
2678 if (get_reply_max_size() < sock->addr_len)
2680 set_error( STATUS_BUFFER_TOO_SMALL );
2681 return;
2684 set_reply_data( &sock->addr, sock->addr_len );
2685 return;
2687 case IOCTL_AFD_WINE_DEFER:
2689 const obj_handle_t *handle = get_req_data();
2690 struct sock *acceptsock;
2692 if (get_req_data_size() < sizeof(*handle))
2694 set_error( STATUS_BUFFER_TOO_SMALL );
2695 return;
2698 acceptsock = (struct sock *)get_handle_obj( current->process, *handle, 0, &sock_ops );
2699 if (!acceptsock) return;
2701 sock->deferred = acceptsock;
2702 return;
2705 case IOCTL_AFD_WINE_GET_INFO:
2707 struct afd_get_info_params params;
2709 if (get_reply_max_size() < sizeof(params))
2711 set_error( STATUS_BUFFER_TOO_SMALL );
2712 return;
2715 params.family = sock->family;
2716 params.type = sock->type;
2717 params.protocol = sock->proto;
2718 set_reply_data( &params, sizeof(params) );
2719 return;
2722 case IOCTL_AFD_WINE_GET_SO_ACCEPTCONN:
2724 int listening = (sock->state == SOCK_LISTENING);
2726 if (get_reply_max_size() < sizeof(listening))
2728 set_error( STATUS_BUFFER_TOO_SMALL );
2729 return;
2732 set_reply_data( &listening, sizeof(listening) );
2733 return;
2736 case IOCTL_AFD_WINE_GET_SO_ERROR:
2738 int error;
2739 socklen_t len = sizeof(error);
2740 unsigned int i;
2742 if (get_reply_max_size() < sizeof(error))
2744 set_error( STATUS_BUFFER_TOO_SMALL );
2745 return;
2748 if (getsockopt( unix_fd, SOL_SOCKET, SO_ERROR, (char *)&error, &len ) < 0)
2750 set_error( sock_get_ntstatus( errno ) );
2751 return;
2754 if (!error)
2756 for (i = 0; i < ARRAY_SIZE( sock->errors ); ++i)
2758 if (sock->errors[i])
2760 error = sock_get_error( sock->errors[i] );
2761 break;
2766 set_reply_data( &error, sizeof(error) );
2767 return;
2770 case IOCTL_AFD_WINE_GET_SO_RCVBUF:
2772 int rcvbuf = sock->rcvbuf;
2774 if (get_reply_max_size() < sizeof(rcvbuf))
2776 set_error( STATUS_BUFFER_TOO_SMALL );
2777 return;
2780 set_reply_data( &rcvbuf, sizeof(rcvbuf) );
2781 return;
2784 case IOCTL_AFD_WINE_SET_SO_RCVBUF:
2786 DWORD rcvbuf;
2788 if (get_req_data_size() < sizeof(rcvbuf))
2790 set_error( STATUS_BUFFER_TOO_SMALL );
2791 return;
2793 rcvbuf = *(DWORD *)get_req_data();
2795 if (!setsockopt( unix_fd, SOL_SOCKET, SO_RCVBUF, (char *)&rcvbuf, sizeof(rcvbuf) ))
2796 sock->rcvbuf = rcvbuf;
2797 else
2798 set_error( sock_get_ntstatus( errno ) );
2799 return;
2802 case IOCTL_AFD_WINE_GET_SO_RCVTIMEO:
2804 DWORD rcvtimeo = sock->rcvtimeo;
2806 if (get_reply_max_size() < sizeof(rcvtimeo))
2808 set_error( STATUS_BUFFER_TOO_SMALL );
2809 return;
2812 set_reply_data( &rcvtimeo, sizeof(rcvtimeo) );
2813 return;
2816 case IOCTL_AFD_WINE_SET_SO_RCVTIMEO:
2818 DWORD rcvtimeo;
2820 if (get_req_data_size() < sizeof(rcvtimeo))
2822 set_error( STATUS_BUFFER_TOO_SMALL );
2823 return;
2825 rcvtimeo = *(DWORD *)get_req_data();
2827 sock->rcvtimeo = rcvtimeo;
2828 return;
2831 case IOCTL_AFD_WINE_GET_SO_SNDBUF:
2833 int sndbuf = sock->sndbuf;
2835 if (get_reply_max_size() < sizeof(sndbuf))
2837 set_error( STATUS_BUFFER_TOO_SMALL );
2838 return;
2841 set_reply_data( &sndbuf, sizeof(sndbuf) );
2842 return;
2845 case IOCTL_AFD_WINE_SET_SO_SNDBUF:
2847 DWORD sndbuf;
2849 if (get_req_data_size() < sizeof(sndbuf))
2851 set_error( STATUS_BUFFER_TOO_SMALL );
2852 return;
2854 sndbuf = *(DWORD *)get_req_data();
2856 #ifdef __APPLE__
2857 if (!sndbuf)
2859 /* setsockopt fails if a zero value is passed */
2860 sock->sndbuf = sndbuf;
2861 return;
2863 #endif
2865 if (!setsockopt( unix_fd, SOL_SOCKET, SO_SNDBUF, (char *)&sndbuf, sizeof(sndbuf) ))
2866 sock->sndbuf = sndbuf;
2867 else
2868 set_error( sock_get_ntstatus( errno ) );
2869 return;
2872 case IOCTL_AFD_WINE_GET_SO_SNDTIMEO:
2874 DWORD sndtimeo = sock->sndtimeo;
2876 if (get_reply_max_size() < sizeof(sndtimeo))
2878 set_error( STATUS_BUFFER_TOO_SMALL );
2879 return;
2882 set_reply_data( &sndtimeo, sizeof(sndtimeo) );
2883 return;
2886 case IOCTL_AFD_WINE_SET_SO_SNDTIMEO:
2888 DWORD sndtimeo;
2890 if (get_req_data_size() < sizeof(sndtimeo))
2892 set_error( STATUS_BUFFER_TOO_SMALL );
2893 return;
2895 sndtimeo = *(DWORD *)get_req_data();
2897 sock->sndtimeo = sndtimeo;
2898 return;
2901 case IOCTL_AFD_WINE_GET_SO_CONNECT_TIME:
2903 DWORD time = ~0u;
2905 if (get_reply_max_size() < sizeof(time))
2907 set_error( STATUS_BUFFER_TOO_SMALL );
2908 return;
2911 if (sock->state == SOCK_CONNECTED)
2912 time = (current_time - sock->connect_time) / 10000000;
2914 set_reply_data( &time, sizeof(time) );
2915 return;
2918 case IOCTL_AFD_POLL:
2920 if (get_reply_max_size() < get_req_data_size())
2922 set_error( STATUS_INVALID_PARAMETER );
2923 return;
2926 if (is_machine_64bit( current->process->machine ))
2928 const struct afd_poll_params_64 *params = get_req_data();
2930 if (get_req_data_size() < sizeof(struct afd_poll_params_64) ||
2931 get_req_data_size() < offsetof( struct afd_poll_params_64, sockets[params->count] ))
2933 set_error( STATUS_INVALID_PARAMETER );
2934 return;
2937 poll_socket( sock, async, params->exclusive, params->timeout, params->count, params->sockets );
2939 else
2941 const struct afd_poll_params_32 *params = get_req_data();
2942 struct afd_poll_socket_64 *sockets;
2943 unsigned int i;
2945 if (get_req_data_size() < sizeof(struct afd_poll_params_32) ||
2946 get_req_data_size() < offsetof( struct afd_poll_params_32, sockets[params->count] ))
2948 set_error( STATUS_INVALID_PARAMETER );
2949 return;
2952 if (!(sockets = mem_alloc( params->count * sizeof(*sockets) ))) return;
2953 for (i = 0; i < params->count; ++i)
2955 sockets[i].socket = params->sockets[i].socket;
2956 sockets[i].flags = params->sockets[i].flags;
2957 sockets[i].status = params->sockets[i].status;
2960 poll_socket( sock, async, params->exclusive, params->timeout, params->count, sockets );
2961 free( sockets );
2964 return;
2967 default:
2968 set_error( STATUS_NOT_SUPPORTED );
2969 return;
2973 static int poll_single_socket( struct sock *sock, int mask )
2975 struct pollfd pollfd;
2977 pollfd.fd = get_unix_fd( sock->fd );
2978 pollfd.events = poll_flags_from_afd( sock, mask );
2979 if (pollfd.events < 0 || poll( &pollfd, 1, 0 ) < 0)
2980 return 0;
2982 if (sock->state == SOCK_CONNECTING && (pollfd.revents & (POLLERR | POLLHUP)))
2983 pollfd.revents &= ~POLLOUT;
2985 if ((mask & AFD_POLL_HUP) && (pollfd.revents & POLLIN) && sock->type == WS_SOCK_STREAM)
2987 char dummy;
2989 if (!recv( get_unix_fd( sock->fd ), &dummy, 1, MSG_PEEK ))
2991 pollfd.revents &= ~POLLIN;
2992 pollfd.revents |= POLLHUP;
2996 return get_poll_flags( sock, pollfd.revents ) & mask;
2999 static void handle_exclusive_poll(struct poll_req *req)
3001 unsigned int i;
3003 for (i = 0; i < req->count; ++i)
3005 struct sock *sock = req->sockets[i].sock;
3006 struct poll_req *main_poll = sock->main_poll;
3008 if (main_poll && main_poll->exclusive && req->exclusive)
3010 complete_async_poll( main_poll, STATUS_SUCCESS );
3011 main_poll = NULL;
3014 if (!main_poll)
3015 sock->main_poll = req;
3019 static void poll_socket( struct sock *poll_sock, struct async *async, int exclusive, timeout_t timeout,
3020 unsigned int count, const struct afd_poll_socket_64 *sockets )
3022 BOOL signaled = FALSE;
3023 struct poll_req *req;
3024 unsigned int i, j;
3026 if (!count)
3028 set_error( STATUS_INVALID_PARAMETER );
3029 return;
3032 if (!(req = mem_alloc( offsetof( struct poll_req, sockets[count] ) )))
3033 return;
3035 req->timeout = NULL;
3036 if (timeout && timeout != TIMEOUT_INFINITE &&
3037 !(req->timeout = add_timeout_user( timeout, async_poll_timeout, req )))
3039 free( req );
3040 return;
3042 req->orig_timeout = timeout;
3044 for (i = 0; i < count; ++i)
3046 req->sockets[i].sock = (struct sock *)get_handle_obj( current->process, sockets[i].socket, 0, &sock_ops );
3047 if (!req->sockets[i].sock)
3049 for (j = 0; j < i; ++j) release_object( req->sockets[j].sock );
3050 if (req->timeout) remove_timeout_user( req->timeout );
3051 free( req );
3052 return;
3054 req->sockets[i].handle = sockets[i].socket;
3055 req->sockets[i].mask = sockets[i].flags;
3056 req->sockets[i].flags = 0;
3059 req->exclusive = exclusive;
3060 req->count = count;
3061 req->async = (struct async *)grab_object( async );
3062 req->iosb = async_get_iosb( async );
3064 handle_exclusive_poll(req);
3066 list_add_tail( &poll_list, &req->entry );
3067 async_set_completion_callback( async, free_poll_req, req );
3068 queue_async( &poll_sock->poll_q, async );
3070 for (i = 0; i < count; ++i)
3072 struct sock *sock = req->sockets[i].sock;
3073 int mask = req->sockets[i].mask;
3074 int flags = poll_single_socket( sock, mask );
3076 if (flags)
3078 signaled = TRUE;
3079 req->sockets[i].flags = flags;
3080 req->sockets[i].status = sock_get_ntstatus( sock_error( sock->fd ) );
3083 /* FIXME: do other error conditions deserve a similar treatment? */
3084 if (sock->state != SOCK_CONNECTING && sock->errors[AFD_POLL_BIT_CONNECT_ERR] && (mask & AFD_POLL_CONNECT_ERR))
3086 signaled = TRUE;
3087 req->sockets[i].flags |= AFD_POLL_CONNECT_ERR;
3088 req->sockets[i].status = sock_get_ntstatus( sock->errors[AFD_POLL_BIT_CONNECT_ERR] );
3092 if (!timeout || signaled)
3093 complete_async_poll( req, STATUS_SUCCESS );
3095 for (i = 0; i < req->count; ++i)
3096 sock_reselect( req->sockets[i].sock );
3097 set_error( STATUS_PENDING );
3100 #ifdef HAVE_LINUX_RTNETLINK_H
3102 /* only keep one ifchange object around, all sockets waiting for wakeups will look to it */
3103 static struct object *ifchange_object;
3105 static void ifchange_dump( struct object *obj, int verbose );
3106 static struct fd *ifchange_get_fd( struct object *obj );
3107 static void ifchange_destroy( struct object *obj );
3109 static int ifchange_get_poll_events( struct fd *fd );
3110 static void ifchange_poll_event( struct fd *fd, int event );
3112 struct ifchange
3114 struct object obj; /* object header */
3115 struct fd *fd; /* interface change file descriptor */
3116 struct list sockets; /* list of sockets to send interface change notifications */
3119 static const struct object_ops ifchange_ops =
3121 sizeof(struct ifchange), /* size */
3122 &no_type, /* type */
3123 ifchange_dump, /* dump */
3124 no_add_queue, /* add_queue */
3125 NULL, /* remove_queue */
3126 NULL, /* signaled */
3127 no_satisfied, /* satisfied */
3128 no_signal, /* signal */
3129 ifchange_get_fd, /* get_fd */
3130 default_map_access, /* map_access */
3131 default_get_sd, /* get_sd */
3132 default_set_sd, /* set_sd */
3133 no_get_full_name, /* get_full_name */
3134 no_lookup_name, /* lookup_name */
3135 no_link_name, /* link_name */
3136 NULL, /* unlink_name */
3137 no_open_file, /* open_file */
3138 no_kernel_obj_list, /* get_kernel_obj_list */
3139 no_close_handle, /* close_handle */
3140 ifchange_destroy /* destroy */
3143 static const struct fd_ops ifchange_fd_ops =
3145 ifchange_get_poll_events, /* get_poll_events */
3146 ifchange_poll_event, /* poll_event */
3147 NULL, /* get_fd_type */
3148 no_fd_read, /* read */
3149 no_fd_write, /* write */
3150 no_fd_flush, /* flush */
3151 no_fd_get_file_info, /* get_file_info */
3152 no_fd_get_volume_info, /* get_volume_info */
3153 no_fd_ioctl, /* ioctl */
3154 NULL, /* cancel_async */
3155 NULL, /* queue_async */
3156 NULL /* reselect_async */
3159 static void ifchange_dump( struct object *obj, int verbose )
3161 assert( obj->ops == &ifchange_ops );
3162 fprintf( stderr, "Interface change\n" );
3165 static struct fd *ifchange_get_fd( struct object *obj )
3167 struct ifchange *ifchange = (struct ifchange *)obj;
3168 return (struct fd *)grab_object( ifchange->fd );
3171 static void ifchange_destroy( struct object *obj )
3173 struct ifchange *ifchange = (struct ifchange *)obj;
3174 assert( obj->ops == &ifchange_ops );
3176 release_object( ifchange->fd );
3178 /* reset the global ifchange object so that it will be recreated if it is needed again */
3179 assert( obj == ifchange_object );
3180 ifchange_object = NULL;
3183 static int ifchange_get_poll_events( struct fd *fd )
3185 return POLLIN;
3188 /* wake up all the sockets waiting for a change notification event */
3189 static void ifchange_wake_up( struct object *obj, unsigned int status )
3191 struct ifchange *ifchange = (struct ifchange *)obj;
3192 struct list *ptr, *next;
3193 assert( obj->ops == &ifchange_ops );
3194 assert( obj == ifchange_object );
3196 LIST_FOR_EACH_SAFE( ptr, next, &ifchange->sockets )
3198 struct sock *sock = LIST_ENTRY( ptr, struct sock, ifchange_entry );
3200 assert( sock->ifchange_obj );
3201 async_wake_up( &sock->ifchange_q, status ); /* issue ifchange notification for the socket */
3202 sock_release_ifchange( sock ); /* remove socket from list and decrement ifchange refcount */
3206 static void ifchange_poll_event( struct fd *fd, int event )
3208 struct object *ifchange = get_fd_user( fd );
3209 unsigned int status = STATUS_PENDING;
3210 char buffer[PIPE_BUF];
3211 int r;
3213 r = recv( get_unix_fd(fd), buffer, sizeof(buffer), MSG_DONTWAIT );
3214 if (r < 0)
3216 if (errno == EWOULDBLOCK || (EWOULDBLOCK != EAGAIN && errno == EAGAIN))
3217 return; /* retry when poll() says the socket is ready */
3218 status = sock_get_ntstatus( errno );
3220 else if (r > 0)
3222 struct nlmsghdr *nlh;
3224 for (nlh = (struct nlmsghdr *)buffer; NLMSG_OK(nlh, r); nlh = NLMSG_NEXT(nlh, r))
3226 if (nlh->nlmsg_type == NLMSG_DONE)
3227 break;
3228 if (nlh->nlmsg_type == RTM_NEWADDR || nlh->nlmsg_type == RTM_DELADDR)
3229 status = STATUS_SUCCESS;
3232 else status = STATUS_CANCELLED;
3234 if (status != STATUS_PENDING) ifchange_wake_up( ifchange, status );
3237 #endif
3239 /* we only need one of these interface notification objects, all of the sockets dependent upon
3240 * it will wake up when a notification event occurs */
3241 static struct object *get_ifchange( void )
3243 #ifdef HAVE_LINUX_RTNETLINK_H
3244 struct ifchange *ifchange;
3245 struct sockaddr_nl addr;
3246 int unix_fd;
3248 if (ifchange_object)
3250 /* increment the refcount for each socket that uses the ifchange object */
3251 return grab_object( ifchange_object );
3254 /* create the socket we need for processing interface change notifications */
3255 unix_fd = socket( PF_NETLINK, SOCK_RAW, NETLINK_ROUTE );
3256 if (unix_fd == -1)
3258 set_error( sock_get_ntstatus( errno ));
3259 return NULL;
3261 fcntl( unix_fd, F_SETFL, O_NONBLOCK ); /* make socket nonblocking */
3262 memset( &addr, 0, sizeof(addr) );
3263 addr.nl_family = AF_NETLINK;
3264 addr.nl_groups = RTMGRP_IPV4_IFADDR;
3265 /* bind the socket to the special netlink kernel interface */
3266 if (bind( unix_fd, (struct sockaddr *)&addr, sizeof(addr) ) == -1)
3268 close( unix_fd );
3269 set_error( sock_get_ntstatus( errno ));
3270 return NULL;
3272 if (!(ifchange = alloc_object( &ifchange_ops )))
3274 close( unix_fd );
3275 set_error( STATUS_NO_MEMORY );
3276 return NULL;
3278 list_init( &ifchange->sockets );
3279 if (!(ifchange->fd = create_anonymous_fd( &ifchange_fd_ops, unix_fd, &ifchange->obj, 0 )))
3281 release_object( ifchange );
3282 set_error( STATUS_NO_MEMORY );
3283 return NULL;
3285 set_fd_events( ifchange->fd, POLLIN ); /* enable read wakeup on the file descriptor */
3287 /* the ifchange object is now successfully configured */
3288 ifchange_object = &ifchange->obj;
3289 return &ifchange->obj;
3290 #else
3291 set_error( STATUS_NOT_SUPPORTED );
3292 return NULL;
3293 #endif
3296 /* add the socket to the interface change notification list */
3297 static void ifchange_add_sock( struct object *obj, struct sock *sock )
3299 #ifdef HAVE_LINUX_RTNETLINK_H
3300 struct ifchange *ifchange = (struct ifchange *)obj;
3302 list_add_tail( &ifchange->sockets, &sock->ifchange_entry );
3303 #endif
3306 /* create a new ifchange queue for a specific socket or, if one already exists, reuse the existing one */
3307 static struct object *sock_get_ifchange( struct sock *sock )
3309 struct object *ifchange;
3311 if (sock->ifchange_obj) /* reuse existing ifchange_obj for this socket */
3312 return sock->ifchange_obj;
3314 if (!(ifchange = get_ifchange()))
3315 return NULL;
3317 /* add the socket to the ifchange notification list */
3318 ifchange_add_sock( ifchange, sock );
3319 sock->ifchange_obj = ifchange;
3320 return ifchange;
3323 /* destroy an existing ifchange queue for a specific socket */
3324 static void sock_release_ifchange( struct sock *sock )
3326 if (sock->ifchange_obj)
3328 list_remove( &sock->ifchange_entry );
3329 release_object( sock->ifchange_obj );
3330 sock->ifchange_obj = NULL;
3334 static void socket_device_dump( struct object *obj, int verbose );
3335 static struct object *socket_device_lookup_name( struct object *obj, struct unicode_str *name,
3336 unsigned int attr, struct object *root );
3337 static struct object *socket_device_open_file( struct object *obj, unsigned int access,
3338 unsigned int sharing, unsigned int options );
3340 static const struct object_ops socket_device_ops =
3342 sizeof(struct object), /* size */
3343 &device_type, /* type */
3344 socket_device_dump, /* dump */
3345 no_add_queue, /* add_queue */
3346 NULL, /* remove_queue */
3347 NULL, /* signaled */
3348 no_satisfied, /* satisfied */
3349 no_signal, /* signal */
3350 no_get_fd, /* get_fd */
3351 default_map_access, /* map_access */
3352 default_get_sd, /* get_sd */
3353 default_set_sd, /* set_sd */
3354 default_get_full_name, /* get_full_name */
3355 socket_device_lookup_name, /* lookup_name */
3356 directory_link_name, /* link_name */
3357 default_unlink_name, /* unlink_name */
3358 socket_device_open_file, /* open_file */
3359 no_kernel_obj_list, /* get_kernel_obj_list */
3360 no_close_handle, /* close_handle */
3361 no_destroy /* destroy */
3364 static void socket_device_dump( struct object *obj, int verbose )
3366 fputs( "Socket device\n", stderr );
3369 static struct object *socket_device_lookup_name( struct object *obj, struct unicode_str *name,
3370 unsigned int attr, struct object *root )
3372 if (name) name->len = 0;
3373 return NULL;
3376 static struct object *socket_device_open_file( struct object *obj, unsigned int access,
3377 unsigned int sharing, unsigned int options )
3379 struct sock *sock;
3381 if (!(sock = create_socket())) return NULL;
3382 if (!(sock->fd = alloc_pseudo_fd( &sock_fd_ops, &sock->obj, options )))
3384 release_object( sock );
3385 return NULL;
3387 return &sock->obj;
3390 struct object *create_socket_device( struct object *root, const struct unicode_str *name,
3391 unsigned int attr, const struct security_descriptor *sd )
3393 return create_named_object( root, &socket_device_ops, name, attr, sd );
3396 DECL_HANDLER(recv_socket)
3398 struct sock *sock = (struct sock *)get_handle_obj( current->process, req->async.handle, 0, &sock_ops );
3399 unsigned int status = req->status;
3400 timeout_t timeout = 0;
3401 struct async *async;
3402 struct fd *fd;
3404 if (!sock) return;
3405 fd = sock->fd;
3407 /* recv() returned EWOULDBLOCK, i.e. no data available yet */
3408 if (status == STATUS_DEVICE_NOT_READY && !sock->nonblocking)
3410 /* Set a timeout on the async if necessary.
3412 * We want to do this *only* if the client gave us STATUS_DEVICE_NOT_READY.
3413 * If the client gave us STATUS_PENDING, it expects the async to always
3414 * block (it was triggered by WSARecv*() with a valid OVERLAPPED
3415 * structure) and for the timeout not to be respected. */
3416 if (is_fd_overlapped( fd ))
3417 timeout = (timeout_t)sock->rcvtimeo * -10000;
3419 status = STATUS_PENDING;
3422 if ((status == STATUS_PENDING || status == STATUS_DEVICE_NOT_READY) && sock->rd_shutdown)
3423 status = STATUS_PIPE_DISCONNECTED;
3425 sock->pending_events &= ~(req->oob ? AFD_POLL_OOB : AFD_POLL_READ);
3426 sock->reported_events &= ~(req->oob ? AFD_POLL_OOB : AFD_POLL_READ);
3428 if ((async = create_request_async( fd, get_fd_comp_flags( fd ), &req->async )))
3430 if (status == STATUS_SUCCESS)
3432 struct iosb *iosb = async_get_iosb( async );
3433 iosb->result = req->total;
3434 release_object( iosb );
3436 set_error( status );
3438 if (timeout)
3439 async_set_timeout( async, timeout, STATUS_IO_TIMEOUT );
3441 if (status == STATUS_PENDING)
3442 queue_async( &sock->read_q, async );
3444 /* always reselect; we changed reported_events above */
3445 sock_reselect( sock );
3447 reply->wait = async_handoff( async, NULL, 0 );
3448 reply->options = get_fd_options( fd );
3449 release_object( async );
3451 release_object( sock );
3454 DECL_HANDLER(send_socket)
3456 struct sock *sock = (struct sock *)get_handle_obj( current->process, req->async.handle, 0, &sock_ops );
3457 unsigned int status = req->status;
3458 timeout_t timeout = 0;
3459 struct async *async;
3460 struct fd *fd;
3462 if (!sock) return;
3463 fd = sock->fd;
3465 if (sock->type == WS_SOCK_DGRAM)
3467 /* sendto() and sendmsg() implicitly binds a socket */
3468 union unix_sockaddr unix_addr;
3469 socklen_t unix_len = sizeof(unix_addr);
3471 if (!sock->bound && !getsockname( get_unix_fd( fd ), &unix_addr.addr, &unix_len ))
3472 sock->addr_len = sockaddr_from_unix( &unix_addr, &sock->addr.addr, sizeof(sock->addr) );
3473 sock->bound = 1;
3476 if (status != STATUS_SUCCESS)
3478 /* send() calls only clear and reselect events if unsuccessful. */
3479 sock->pending_events &= ~AFD_POLL_WRITE;
3480 sock->reported_events &= ~AFD_POLL_WRITE;
3483 /* If we had a short write and the socket is nonblocking (and the client is
3484 * not trying to force the operation to be asynchronous), return success.
3485 * Windows actually refuses to send any data in this case, and returns
3486 * EWOULDBLOCK, but we have no way of doing that. */
3487 if (status == STATUS_DEVICE_NOT_READY && req->total && sock->nonblocking)
3488 status = STATUS_SUCCESS;
3490 /* send() returned EWOULDBLOCK or a short write, i.e. cannot send all data yet */
3491 if (status == STATUS_DEVICE_NOT_READY && !sock->nonblocking)
3493 /* Set a timeout on the async if necessary.
3495 * We want to do this *only* if the client gave us STATUS_DEVICE_NOT_READY.
3496 * If the client gave us STATUS_PENDING, it expects the async to always
3497 * block (it was triggered by WSASend*() with a valid OVERLAPPED
3498 * structure) and for the timeout not to be respected. */
3499 if (is_fd_overlapped( fd ))
3500 timeout = (timeout_t)sock->sndtimeo * -10000;
3502 status = STATUS_PENDING;
3505 if ((status == STATUS_PENDING || status == STATUS_DEVICE_NOT_READY) && sock->wr_shutdown)
3506 status = STATUS_PIPE_DISCONNECTED;
3508 if ((async = create_request_async( fd, get_fd_comp_flags( fd ), &req->async )))
3510 if (status == STATUS_SUCCESS)
3512 struct iosb *iosb = async_get_iosb( async );
3513 iosb->result = req->total;
3514 release_object( iosb );
3516 set_error( status );
3518 if (timeout)
3519 async_set_timeout( async, timeout, STATUS_IO_TIMEOUT );
3521 if (status == STATUS_PENDING)
3522 queue_async( &sock->write_q, async );
3524 /* always reselect; we changed reported_events above */
3525 sock_reselect( sock );
3527 reply->wait = async_handoff( async, NULL, 0 );
3528 reply->options = get_fd_options( fd );
3529 release_object( async );
3531 release_object( sock );