1 /* fhandler_socket.cc. See fhandler.h for a description of the fhandler classes.
3 Copyright 2000, 2001, 2002, 2003, 2004, 2005 Red Hat, Inc.
5 This file is part of Cygwin.
7 This software is a copyrighted work licensed under the terms of the
8 Cygwin license. Please consult the file "CYGWIN_LICENSE" for
11 /* #define DEBUG_NEST_ON 1 */
13 #define __INSIDE_CYGWIN_NET__
16 #include <sys/socket.h>
19 #include <asm/byteorder.h>
22 #define USE_SYS_TYPES_FD_SET
26 #include "cygwin/version.h"
27 #include "perprocess.h"
34 #include "cygthread.h"
41 #define ASYNC_MASK (FD_READ|FD_WRITE|FD_OOB|FD_ACCEPT|FD_CONNECT)
43 extern bool fdsock (cygheap_fdmanip& fd, const device *, SOCKET soc);
45 int sscanf (const char *, const char *, ...);
46 } /* End of "C" section */
48 fhandler_dev_random* entropy_source;
50 /* cygwin internal: map sockaddr into internet domain address */
52 get_inet_addr (const struct sockaddr *in, int inlen,
53 struct sockaddr_in *out, int *outlen,
54 int *type = NULL, int *secret = NULL)
57 int* secret_ptr = (secret ? : secret_buf);
59 if (in->sa_family == AF_INET)
61 *out = * (struct sockaddr_in *)in;
65 else if (in->sa_family == AF_LOCAL)
67 path_conv pc (in->sa_data, PC_SYM_FOLLOW);
83 HANDLE fh = CreateFile (pc, GENERIC_READ, wincap.shared (), &sec_none,
84 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
85 if (fh == INVALID_HANDLE_VALUE)
93 memset (buf, 0, sizeof buf);
94 if (ReadFile (fh, buf, 128, &len, 0))
96 struct sockaddr_in sin;
98 sin.sin_family = AF_INET;
99 sscanf (buf + strlen (SOCKET_COOKIE), "%hu %c %08x-%08x-%08x-%08x",
102 secret_ptr, secret_ptr + 1, secret_ptr + 2, secret_ptr + 3);
103 sin.sin_port = htons (sin.sin_port);
104 sin.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
106 *outlen = sizeof sin;
108 *type = (ctype == 's' ? SOCK_STREAM :
109 ctype == 'd' ? SOCK_DGRAM
120 set_errno (EAFNOSUPPORT);
125 /**********************************************************************/
126 /* fhandler_socket */
128 fhandler_socket::fhandler_socket () :
133 need_fork_fixup (true);
134 prot_info_ptr = (LPWSAPROTOCOL_INFOA) cmalloc (HEAP_BUF,
135 sizeof (WSAPROTOCOL_INFOA));
137 if (pc.is_fs_special ())
139 fhandler_socket * fhs = (fhandler_socket *) fh;
140 fhs->set_addr_family (AF_LOCAL);
141 fhs->set_sun_path (posix_path);
146 fhandler_socket::~fhandler_socket ()
149 cfree (prot_info_ptr);
155 fhandler_socket::get_proc_fd_name (char *buf)
157 __small_sprintf (buf, "socket:[%d]", get_socket ());
162 fhandler_socket::open (int flags, mode_t mode)
169 fhandler_socket::af_local_set_sockpair_cred ()
171 sec_pid = sec_peer_pid = getpid ();
172 sec_uid = sec_peer_uid = geteuid32 ();
173 sec_gid = sec_peer_gid = getegid32 ();
177 fhandler_socket::af_local_setblocking (bool &async, bool &nonblocking)
180 nonblocking = is_nonblocking ();
181 if (async || nonblocking)
182 WSAAsyncSelect (get_socket (), winmsg, 0, 0);
184 ioctlsocket (get_socket (), FIONBIO, &p);
185 set_nonblocking (false);
190 fhandler_socket::af_local_unsetblocking (bool async, bool nonblocking)
195 ioctlsocket (get_socket (), FIONBIO, &p);
196 set_nonblocking (true);
200 WSAAsyncSelect (get_socket (), winmsg, WM_ASYNCIO, ASYNC_MASK);
206 fhandler_socket::af_local_recv_secret ()
208 int out[4] = { 0, 0, 0, 0 };
209 int rest = sizeof out;
210 char *ptr = (char *) out;
213 int ret = recvfrom (ptr, rest, 0, NULL, NULL);
221 debug_printf ("Received af_local secret: %08x-%08x-%08x-%08x",
222 out[0], out[1], out[2], out[3]);
223 if (out[0] != connect_secret[0] || out[1] != connect_secret[1]
224 || out[2] != connect_secret[2] || out[3] != connect_secret[3])
226 debug_printf ("Receiving af_local secret mismatch");
231 debug_printf ("Receiving af_local secret failed");
236 fhandler_socket::af_local_send_secret ()
238 int rest = sizeof connect_secret;
239 char *ptr = (char *) connect_secret;
242 int ret = sendto (ptr, rest, 0, NULL, 0);
248 debug_printf ("Sending af_local secret %s", rest == 0 ? "succeeded"
254 fhandler_socket::af_local_recv_cred ()
256 struct ucred out = { (pid_t) 0, (__uid32_t) -1, (__gid32_t) -1 };
257 int rest = sizeof out;
258 char *ptr = (char *) &out;
261 int ret = recvfrom (ptr, rest, 0, NULL, NULL);
269 debug_printf ("Received eid credentials: pid: %d, uid: %d, gid: %d",
270 out.pid, out.uid, out.gid);
271 sec_peer_pid = out.pid;
272 sec_peer_uid = out.uid;
273 sec_peer_gid = out.gid;
276 debug_printf ("Receiving eid credentials failed");
281 fhandler_socket::af_local_send_cred ()
283 struct ucred in = { sec_pid, sec_uid, sec_gid };
284 int rest = sizeof in;
285 char *ptr = (char *) ∈
288 int ret = sendto (ptr, rest, 0, NULL, 0);
295 debug_printf ("Sending eid credentials succeeded");
297 debug_printf ("Sending eid credentials failed");
302 fhandler_socket::af_local_connect ()
304 /* This keeps the test out of select. */
305 if (get_addr_family () != AF_LOCAL || get_socket_type () != SOCK_STREAM)
308 debug_printf ("af_local_connect called");
309 bool orig_async_io, orig_is_nonblocking;
310 af_local_setblocking (orig_async_io, orig_is_nonblocking);
311 if (!af_local_send_secret () || !af_local_recv_secret ()
312 || !af_local_send_cred () || !af_local_recv_cred ())
314 debug_printf ("accept from unauthorized server");
315 ::shutdown (get_socket (), SD_BOTH);
316 WSASetLastError (WSAECONNREFUSED);
319 af_local_unsetblocking (orig_async_io, orig_is_nonblocking);
324 fhandler_socket::af_local_accept ()
326 debug_printf ("af_local_accept called");
327 bool orig_async_io, orig_is_nonblocking;
328 af_local_setblocking (orig_async_io, orig_is_nonblocking);
329 if (!af_local_recv_secret () || !af_local_send_secret ()
330 || !af_local_recv_cred () || !af_local_send_cred ())
332 debug_printf ("connect from unauthorized client");
333 ::shutdown (get_socket (), SD_BOTH);
334 ::closesocket (get_socket ());
335 WSASetLastError (WSAECONNABORTED);
338 af_local_unsetblocking (orig_async_io, orig_is_nonblocking);
343 fhandler_socket::af_local_set_cred ()
346 sec_uid = geteuid32 ();
347 sec_gid = getegid32 ();
348 sec_peer_pid = (pid_t) 0;
349 sec_peer_uid = (__uid32_t) -1;
350 sec_peer_gid = (__gid32_t) -1;
354 fhandler_socket::af_local_copy (fhandler_socket *sock)
356 sock->connect_secret[0] = connect_secret[0];
357 sock->connect_secret[1] = connect_secret[1];
358 sock->connect_secret[2] = connect_secret[2];
359 sock->connect_secret[3] = connect_secret[3];
360 sock->sec_pid = sec_pid;
361 sock->sec_uid = sec_uid;
362 sock->sec_gid = sec_gid;
363 sock->sec_peer_pid = sec_peer_pid;
364 sock->sec_peer_uid = sec_peer_uid;
365 sock->sec_peer_gid = sec_peer_gid;
369 fhandler_socket::af_local_set_secret (char *buf)
373 void *buf = malloc (sizeof (fhandler_dev_random));
374 entropy_source = new (buf) fhandler_dev_random ();
375 entropy_source->dev () = *urandom_dev;
377 if (entropy_source &&
378 !entropy_source->open (O_RDONLY))
380 delete entropy_source;
381 entropy_source = NULL;
385 size_t len = sizeof (connect_secret);
386 entropy_source->read (connect_secret, len);
387 if (len != sizeof (connect_secret))
388 bzero ((char*) connect_secret, sizeof (connect_secret));
390 __small_sprintf (buf, "%08x-%08x-%08x-%08x",
391 connect_secret [0], connect_secret [1],
392 connect_secret [2], connect_secret [3]);
396 fhandler_socket::fixup_before_fork_exec (DWORD win_proc_id)
398 if (!winsock2_active)
400 fhandler_base::fixup_before_fork_exec (win_proc_id);
401 debug_printf ("Without Winsock 2.0");
403 else if (!WSADuplicateSocketA (get_socket (), win_proc_id, prot_info_ptr))
404 debug_printf ("WSADuplicateSocket went fine, sock %p, win_proc_id %d, prot_info_ptr %p",
405 get_socket (), win_proc_id, prot_info_ptr);
408 debug_printf ("WSADuplicateSocket error, sock %p, win_proc_id %d, prot_info_ptr %p",
409 get_socket (), win_proc_id, prot_info_ptr);
410 set_winsock_errno ();
414 extern "C" void __stdcall load_wsock32 ();
416 fhandler_socket::fixup_after_fork (HANDLE parent)
420 debug_printf ("WSASocket begin, dwServiceFlags1=%d",
421 prot_info_ptr->dwServiceFlags1);
423 if ((new_sock = WSASocketA (FROM_PROTOCOL_INFO,
426 prot_info_ptr, 0, 0)) == INVALID_SOCKET)
428 debug_printf ("WSASocket error");
429 set_io_handle ((HANDLE)INVALID_SOCKET);
430 set_winsock_errno ();
432 else if (!new_sock && !winsock2_active)
435 fhandler_base::fixup_after_fork (parent);
436 debug_printf ("Without Winsock 2.0");
440 debug_printf ("WSASocket went fine new_sock %p, old_sock %p", new_sock, get_io_handle ());
441 set_io_handle ((HANDLE) new_sock);
446 fhandler_socket::fixup_after_exec ()
448 debug_printf ("here");
449 if (!close_on_exec ())
450 fixup_after_fork (NULL);
452 else if (!winsock2_active)
453 closesocket (get_socket ());
458 fhandler_socket::dup (fhandler_base *child, HANDLE from_proc)
462 debug_printf ("here");
463 fhandler_socket *fhs = (fhandler_socket *) child;
464 fhs->addr_family = addr_family;
465 fhs->set_socket_type (get_socket_type ());
466 if (get_addr_family () == AF_LOCAL)
468 fhs->set_sun_path (get_sun_path ());
469 if (get_socket_type () == SOCK_STREAM)
471 fhs->sec_pid = sec_pid;
472 fhs->sec_uid = sec_uid;
473 fhs->sec_gid = sec_gid;
474 fhs->sec_peer_pid = sec_peer_pid;
475 fhs->sec_peer_uid = sec_peer_uid;
476 fhs->sec_peer_gid = sec_peer_gid;
479 fhs->connect_state (connect_state ());
481 if (winsock2_active && from_proc == hMainProc)
483 /* Since WSADuplicateSocket() fails on NT systems when the process
484 is currently impersonating a non-privileged account, we revert
485 to the original account before calling WSADuplicateSocket() and
486 switch back afterwards as it's also in fork().
487 If WSADuplicateSocket() still fails for some reason, we fall back
488 to DuplicateHandle(). */
490 cygheap->user.deimpersonate ();
491 fhs->set_io_handle (get_io_handle ());
492 fhs->fixup_before_fork_exec (GetCurrentProcessId ());
493 cygheap->user.reimpersonate ();
494 if (!WSAGetLastError ())
496 fhs->fixup_after_fork (hMainProc);
497 if (fhs->get_io_handle() != (HANDLE) INVALID_SOCKET)
499 cygheap->fdtab.inc_need_fixup_before ();
503 debug_printf ("WSADuplicateSocket failed, trying DuplicateHandle");
506 /* We don't call fhandler_base::dup here since that requires
507 having winsock called from fhandler_base and it creates only
508 inheritable sockets which is wrong for winsock2. */
510 if (!DuplicateHandle (from_proc, get_io_handle (), hMainProc, &nh, 0,
511 !winsock2_active, DUPLICATE_SAME_ACCESS))
513 system_printf ("!DuplicateHandle(%x) failed, %E", get_io_handle ());
518 fhs->set_io_handle (nh);
519 cygheap->fdtab.inc_need_fixup_before ();
524 fhandler_socket::fstat (struct __stat64 *buf)
527 if (get_device () == FH_UNIX)
529 res = fhandler_base::fstat_fs (buf);
532 buf->st_mode = (buf->st_mode & ~S_IFMT) | S_IFSOCK;
537 res = fhandler_base::fstat (buf);
541 buf->st_ino = (__ino64_t) ((DWORD) get_handle ());
542 buf->st_mode = S_IFSOCK | S_IRWXU | S_IRWXG | S_IRWXO;
549 fhandler_socket::fchmod (mode_t mode)
551 if (get_device () == FH_UNIX)
553 fhandler_disk_file fh (pc);
554 fh.get_device () = FH_FS;
555 int ret = fh.fchmod (mode);
556 SetFileAttributes (pc, GetFileAttributes (pc) | FILE_ATTRIBUTE_SYSTEM);
563 fhandler_socket::fchown (__uid32_t uid, __gid32_t gid)
565 if (get_device () == FH_UNIX)
567 fhandler_disk_file fh (pc);
568 return fh.fchown (uid, gid);
574 fhandler_socket::facl (int cmd, int nentries, __aclent32_t *aclbufp)
576 if (get_device () == FH_UNIX)
578 fhandler_disk_file fh (pc);
579 return fh.facl (cmd, nentries, aclbufp);
581 return fhandler_base::facl (cmd, nentries, aclbufp);
585 fhandler_socket::link (const char *newpath)
587 if (get_device () == FH_UNIX)
589 fhandler_disk_file fh (pc);
590 return fh.link (newpath);
592 return fhandler_base::link (newpath);
596 fhandler_socket::bind (const struct sockaddr *name, int namelen)
600 if (name->sa_family == AF_LOCAL)
602 #define un_addr ((struct sockaddr_un *) name)
603 struct sockaddr_in sin;
604 int len = sizeof sin;
606 if (strlen (un_addr->sun_path) >= UNIX_PATH_LEN)
608 set_errno (ENAMETOOLONG);
611 sin.sin_family = AF_INET;
613 sin.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
614 if (::bind (get_socket (), (sockaddr *) &sin, len))
616 syscall_printf ("AF_LOCAL: bind failed %d", get_errno ());
617 set_winsock_errno ();
620 if (::getsockname (get_socket (), (sockaddr *) &sin, &len))
622 syscall_printf ("AF_LOCAL: getsockname failed %d", get_errno ());
623 set_winsock_errno ();
627 sin.sin_port = ntohs (sin.sin_port);
628 debug_printf ("AF_LOCAL: socket bound to port %u", sin.sin_port);
630 path_conv pc (un_addr->sun_path, PC_SYM_FOLLOW);
633 set_errno (pc.error);
638 set_errno (EADDRINUSE);
641 mode_t mode = (S_IRWXU | S_IRWXG | S_IRWXO) & ~cygheap->umask;
642 DWORD attr = FILE_ATTRIBUTE_SYSTEM;
643 if (!(mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
644 attr |= FILE_ATTRIBUTE_READONLY;
645 SECURITY_ATTRIBUTES sa = sec_none;
646 security_descriptor sd;
647 if (allow_ntsec && pc.has_acls ())
648 set_security_attribute (mode, &sa, sd);
649 HANDLE fh = CreateFile (pc, GENERIC_WRITE, 0, &sa, CREATE_NEW, attr, 0);
650 if (fh == INVALID_HANDLE_VALUE)
652 if (GetLastError () == ERROR_ALREADY_EXISTS)
653 set_errno (EADDRINUSE);
658 char buf[sizeof (SOCKET_COOKIE) + 80];
659 __small_sprintf (buf, "%s%u %c ", SOCKET_COOKIE, sin.sin_port, get_socket_type () == SOCK_STREAM ? 's' : get_socket_type () == SOCK_DGRAM ? 'd' : '-');
660 af_local_set_secret (strchr (buf, '\0'));
661 DWORD blen = strlen (buf) + 1;
662 if (!WriteFile (fh, buf, blen, &blen, 0))
671 set_sun_path (un_addr->sun_path);
676 else if (::bind (get_socket (), name, namelen))
677 set_winsock_errno ();
686 fhandler_socket::connect (const struct sockaddr *name, int namelen)
689 bool in_progress = false;
690 struct sockaddr_in sin;
694 if (!get_inet_addr (name, namelen, &sin, &namelen, &type, connect_secret))
697 if (get_addr_family () == AF_LOCAL && get_socket_type () != type)
699 WSASetLastError (WSAEPROTOTYPE);
700 set_winsock_errno ();
704 res = ::connect (get_socket (), (struct sockaddr *) &sin, namelen);
710 err = WSAGetLastError ();
711 /* Special handling for connect to return the correct error code
712 when called on a non-blocking socket. */
713 if (is_nonblocking ())
715 if (err == WSAEWOULDBLOCK || err == WSAEALREADY)
718 if (err == WSAEWOULDBLOCK)
719 WSASetLastError (err = WSAEINPROGRESS);
720 else if (err == WSAEINVAL)
721 WSASetLastError (err = WSAEISCONN);
723 set_winsock_errno ();
726 if (get_addr_family () == AF_LOCAL && (!res || in_progress))
727 set_sun_path (name->sa_data);
729 if (get_addr_family () == AF_LOCAL && get_socket_type () == SOCK_STREAM)
731 af_local_set_cred (); /* Don't move into af_local_connect since
732 af_local_connect is called from select,
733 possibly running under another identity. */
734 if (!res && af_local_connect ())
736 set_winsock_errno ();
741 if (err == WSAEINPROGRESS || err == WSAEALREADY)
742 connect_state (connect_pending);
744 connect_state (connect_failed);
746 connect_state (connected);
752 fhandler_socket::listen (int backlog)
754 int res = ::listen (get_socket (), backlog);
756 set_winsock_errno ();
759 if (get_addr_family () == AF_LOCAL && get_socket_type () == SOCK_STREAM)
760 af_local_set_cred ();
761 connect_state (connected);
767 fhandler_socket::accept (struct sockaddr *peer, int *len)
771 /* Allows NULL peer and len parameters. */
772 struct sockaddr_in peer_dummy;
775 peer = (struct sockaddr *) &peer_dummy;
778 len_dummy = sizeof (struct sockaddr_in);
782 /* accept on NT fails if len < sizeof (sockaddr_in)
783 * some programs set len to
784 * sizeof (name.sun_family) + strlen (name.sun_path) for UNIX domain
786 if (len && ((unsigned) *len < sizeof (struct sockaddr_in)))
787 *len = sizeof (struct sockaddr_in);
789 res = ::accept (get_socket (), peer, len);
791 if (res == (int) INVALID_SOCKET)
792 set_winsock_errno ();
795 cygheap_fdnew res_fd;
796 if (res_fd >= 0 && fdsock (res_fd, &dev (), res))
798 fhandler_socket *sock = (fhandler_socket *) res_fd;
799 sock->set_addr_family (get_addr_family ());
800 sock->set_socket_type (get_socket_type ());
801 sock->async_io (async_io ());
802 sock->set_nonblocking (is_nonblocking ());
803 if (get_addr_family () == AF_LOCAL)
805 sock->set_sun_path (get_sun_path ());
806 if (get_socket_type () == SOCK_STREAM)
808 /* Don't forget to copy credentials from accepting
809 socket to accepted socket and start transaction
810 on accepted socket! */
811 af_local_copy (sock);
812 res = sock->af_local_accept ();
816 set_winsock_errno ();
821 sock->connect_state (connected);
832 debug_printf ("res %d", res);
837 fhandler_socket::getsockname (struct sockaddr *name, int *namelen)
841 if (get_addr_family () == AF_LOCAL)
843 struct sockaddr_un *sun = (struct sockaddr_un *) name;
844 memset (sun, 0, *namelen);
845 sun->sun_family = AF_LOCAL;
847 if (!get_sun_path ())
848 sun->sun_path[0] = '\0';
850 /* According to SUSv2 "If the actual length of the address is
851 greater than the length of the supplied sockaddr structure, the
852 stored address will be truncated." We play it save here so
853 that the path always has a trailing 0 even if it's truncated. */
854 strncpy (sun->sun_path, get_sun_path (),
855 *namelen - sizeof *sun + sizeof sun->sun_path - 1);
857 *namelen = sizeof *sun - sizeof sun->sun_path
858 + strlen (sun->sun_path) + 1;
863 res = ::getsockname (get_socket (), name, namelen);
865 set_winsock_errno ();
872 fhandler_socket::getpeername (struct sockaddr *name, int *namelen)
874 int res = ::getpeername (get_socket (), name, namelen);
876 set_winsock_errno ();
882 fhandler_socket::prepare (HANDLE &event, long event_mask)
886 if ((event = WSACreateEvent ()) == WSA_INVALID_EVENT)
888 debug_printf ("WSACreateEvent, %E");
891 if (WSAEventSelect (get_socket (), event, event_mask) == SOCKET_ERROR)
893 debug_printf ("WSAEventSelect, %E");
900 fhandler_socket::wait (HANDLE event, int flags)
902 int ret = SOCKET_ERROR;
904 WSAEVENT ev[2] = { event, signal_arrived };
905 WSANETWORKEVENTS evts;
907 switch (WSAWaitForMultipleEvents (2, ev, FALSE, 10, FALSE))
909 case WSA_WAIT_TIMEOUT:
912 case WSA_WAIT_EVENT_0:
913 if (!WSAEnumNetworkEvents (get_socket (), event, &evts))
915 if (!evts.lNetworkEvents)
920 if (evts.lNetworkEvents & FD_OOB)
922 if (evts.iErrorCode[FD_OOB_BIT])
923 wsa_err = evts.iErrorCode[FD_OOB_BIT];
924 else if (flags & MSG_OOB)
929 WSASetLastError (WSAEINTR);
933 if (evts.lNetworkEvents & FD_READ)
935 if (evts.iErrorCode[FD_READ_BIT])
936 wsa_err = evts.iErrorCode[FD_READ_BIT];
940 else if (evts.lNetworkEvents & FD_WRITE)
942 if (evts.iErrorCode[FD_WRITE_BIT])
943 wsa_err = evts.iErrorCode[FD_WRITE_BIT];
947 if (evts.lNetworkEvents & FD_CLOSE)
952 if (evts.iErrorCode[FD_CLOSE_BIT])
953 wsa_err = evts.iErrorCode[FD_CLOSE_BIT];
959 WSASetLastError (wsa_err);
962 case WSA_WAIT_EVENT_0 + 1:
963 WSASetLastError (WSAEINTR);
966 WSASetLastError (WSAEFAULT);
973 fhandler_socket::release (HANDLE event)
975 int last_err = WSAGetLastError ();
976 /* KB 168349: NT4 fails if the event parameter is not NULL. */
977 WSAEventSelect (get_socket (), NULL, 0);
978 WSACloseEvent (event);
979 unsigned long non_block = 0;
980 if (ioctlsocket (get_socket (), FIONBIO, &non_block))
981 debug_printf ("return to blocking failed: %d", WSAGetLastError ());
983 WSASetLastError (last_err);
987 fhandler_socket::readv (const struct iovec *const iov, const int iovcnt,
994 msg_iov: (struct iovec *) iov, // const_cast
1001 return recvmsg (&msg, 0, tot);
1005 fhandler_socket::recvfrom (void *ptr, size_t len, int flags,
1006 struct sockaddr *from, int *fromlen)
1008 int res = SOCKET_ERROR;
1011 flags &= MSG_WINMASK;
1012 if (!winsock2_active)
1013 ret = res = ::recvfrom (get_socket (),
1014 (char *) ptr, len, flags,
1018 WSABUF wsabuf = { len, (char *) ptr };
1020 if (is_nonblocking () || closed () || async_io ())
1021 res = WSARecvFrom (get_socket (), &wsabuf, 1, &ret,
1022 (DWORD *) &flags, from, fromlen, NULL, NULL);
1026 if (prepare (evt, FD_CLOSE | FD_READ | (owner () ? FD_OOB : 0)))
1030 DWORD lflags = (DWORD) flags;
1031 res = WSARecvFrom (get_socket (), &wsabuf, 1, &ret, &lflags,
1032 from, fromlen, NULL, NULL);
1034 while (res == SOCKET_ERROR
1035 && WSAGetLastError () == WSAEWOULDBLOCK
1037 && !(res = wait (evt, flags)));
1043 if (res == SOCKET_ERROR)
1045 /* According to SUSv3, errno isn't set in that case and no error
1046 condition is returned. */
1047 if (WSAGetLastError () == WSAEMSGSIZE)
1050 set_winsock_errno ();
1059 fhandler_socket::recvmsg (struct msghdr *msg, int flags, ssize_t tot)
1061 if (get_addr_family () == AF_LOCAL)
1063 /* On AF_LOCAL sockets the (fixed-size) name of the shared memory
1064 area used for descriptor passing is transmitted first.
1065 If this string is empty, no descriptors are passed and we can
1066 go ahead recv'ing the normal data blocks. Otherwise start
1067 special handling for descriptor passing. */
1069 if (CYGWIN_VERSION_CHECK_FOR_USING_ANCIENT_MSGHDR)
1070 ((struct OLD_msghdr *) msg)->msg_accrightslen = 0;
1072 msg->msg_controllen = 0;
1075 struct iovec *const iov = msg->msg_iov;
1076 const int iovcnt = msg->msg_iovlen;
1078 struct sockaddr *from = (struct sockaddr *) msg->msg_name;
1079 int *fromlen = from ? &msg->msg_namelen : NULL;
1081 int res = SOCKET_ERROR;
1083 if (!winsock2_active)
1086 res = recvfrom (iov->iov_base, iov->iov_len, flags, from, fromlen);
1089 if (tot == -1) // i.e. if not pre-calculated by the caller.
1092 const struct iovec *iovptr = iov + iovcnt;
1096 tot += iovptr->iov_len;
1098 while (iovptr != iov);
1101 char *buf = (char *) alloca (tot);
1110 res = recvfrom (buf, tot, flags, from, fromlen);
1112 const struct iovec *iovptr = iov;
1117 const int frag = min (nbytes, (ssize_t) iovptr->iov_len);
1118 memcpy (iovptr->iov_base, buf, frag);
1128 WSABUF wsabuf[iovcnt];
1129 unsigned long len = 0L;
1132 const struct iovec *iovptr = iov + iovcnt;
1133 WSABUF *wsaptr = wsabuf + iovcnt;
1138 len += wsaptr->len = iovptr->iov_len;
1139 wsaptr->buf = (char *) iovptr->iov_base;
1141 while (wsaptr != wsabuf);
1146 if (is_nonblocking () || closed () || async_io ())
1147 res = WSARecvFrom (get_socket (), wsabuf, iovcnt, &ret,
1148 (DWORD *) &flags, from, fromlen, NULL, NULL);
1152 if (prepare (evt, FD_CLOSE | FD_READ | (owner () ? FD_OOB : 0)))
1156 DWORD lflags = (DWORD) flags;
1157 res = WSARecvFrom (get_socket (), wsabuf, iovcnt, &ret,
1158 &lflags, from, fromlen, NULL, NULL);
1160 while (res == SOCKET_ERROR
1161 && WSAGetLastError () == WSAEWOULDBLOCK
1163 && !(res = wait (evt, flags)));
1168 if (res == SOCKET_ERROR)
1170 /* According to SUSv3, errno isn't set in that case and no error
1171 condition is returned. */
1172 if (WSAGetLastError () == WSAEMSGSIZE)
1175 set_winsock_errno ();
1185 fhandler_socket::writev (const struct iovec *const iov, const int iovcnt,
1192 msg_iov: (struct iovec *) iov, // const_cast
1199 return sendmsg (&msg, 0, tot);
1203 fhandler_socket::sendto (const void *ptr, size_t len, int flags,
1204 const struct sockaddr *to, int tolen)
1206 struct sockaddr_in sin;
1208 if (to && !get_inet_addr (to, tolen, &sin, &tolen))
1209 return SOCKET_ERROR;
1211 int res = SOCKET_ERROR;
1214 if (!winsock2_active)
1215 ret = res = ::sendto (get_socket (), (const char *) ptr, len,
1216 flags & MSG_WINMASK,
1217 (to ? (const struct sockaddr *) &sin : NULL), tolen);
1220 WSABUF wsabuf = { len, (char *) ptr };
1222 if (is_nonblocking () || closed () || async_io ())
1223 res = WSASendTo (get_socket (), &wsabuf, 1, &ret,
1224 flags & MSG_WINMASK,
1225 (to ? (const struct sockaddr *) &sin : NULL), tolen,
1230 if (prepare (evt, FD_CLOSE | FD_WRITE | (owner () ? FD_OOB : 0)))
1234 res = WSASendTo (get_socket (), &wsabuf, 1, &ret,
1235 flags & MSG_WINMASK,
1236 (to ? (const struct sockaddr *) &sin : NULL),
1239 while (res == SOCKET_ERROR
1240 && WSAGetLastError () == WSAEWOULDBLOCK
1241 && !(res = wait (evt, 0))
1248 if (res == SOCKET_ERROR)
1249 set_winsock_errno ();
1253 /* Special handling for EPIPE and SIGPIPE.
1255 EPIPE is generated if the local end has been shut down on a connection
1256 oriented socket. In this case the process will also receive a SIGPIPE
1257 unless MSG_NOSIGNAL is set. */
1258 if (res == SOCKET_ERROR && get_errno () == ESHUTDOWN
1259 && get_socket_type () == SOCK_STREAM)
1262 if (! (flags & MSG_NOSIGNAL))
1270 fhandler_socket::sendmsg (const struct msghdr *msg, int flags, ssize_t tot)
1272 struct cmsghdr *cmsg;
1273 bool descriptors_inflight = false;
1275 if (get_addr_family () == AF_LOCAL
1276 && get_socket_type () == SOCK_STREAM
1277 && msg->msg_controllen > 0) /* Works for ancient msghdr, too. */
1279 /* For AF_LOCAL/SOCK_STREAM sockets, if descriptors are given, start
1280 the special handling for descriptor passing. Otherwise just
1281 transmit an empty string to tell the receiver that no
1282 descriptor passing is done. */
1284 /* NOTE: SOCK_DGRAMs are usually allowed, but we can't support them
1285 unless credential passing works for SOCK_DGRAM sockets as well.
1286 OTOH, since DGRAMs can be easily discarded, they are not reliable
1287 and seldomly used anyway. */
1293 char control[CMSG_SPACE (sizeof (int))];
1295 if (CYGWIN_VERSION_CHECK_FOR_USING_ANCIENT_MSGHDR)
1297 memcpy (&lmsg, msg, sizeof *msg);
1298 lmsg.msg_control = (void *) control_un.control;
1299 lmsg.msg_controllen = sizeof control_un.control;
1301 cmsg = CMSG_FIRSTHDR (&lmsg);
1302 cmsg->cmsg_len = CMSG_LEN (sizeof (int));
1303 cmsg->cmsg_level = SOL_SOCKET;
1304 cmsg->cmsg_type = SCM_RIGHTS;
1305 *((int *) CMSG_DATA (cmsg)) =
1306 *(int *) ((OLD_msghdr *) msg)->msg_accrights;
1310 pinfo p (sec_peer_pid);
1313 set_errno (ENOTCONN);
1314 return SOCKET_ERROR;
1316 for (cmsg = CMSG_FIRSTHDR (msg); cmsg; cmsg = CMSG_NXTHDR (msg, cmsg))
1318 if (cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS)
1320 set_errno (ENOTSUP);
1321 return SOCKET_ERROR;
1323 int *fds = (int *) CMSG_DATA (cmsg);
1324 int cnt = (cmsg->cmsg_len - CMSG_ALIGN (sizeof (struct cmsghdr)))
1326 if (!p->send_descriptors (cnt, fds))
1327 return SOCKET_ERROR;
1328 descriptors_inflight = true;
1332 struct iovec *const iov = msg->msg_iov;
1333 const int iovcnt = msg->msg_iovlen;
1335 int res = SOCKET_ERROR;
1337 if (!winsock2_active)
1340 res = sendto (iov->iov_base, iov->iov_len, flags,
1341 (struct sockaddr *) msg->msg_name,
1345 if (tot == -1) // i.e. if not pre-calculated by the caller.
1348 const struct iovec *iovptr = iov + iovcnt;
1352 tot += iovptr->iov_len;
1354 while (iovptr != iov);
1357 char *const buf = (char *) alloca (tot);
1367 const struct iovec *iovptr = iov;
1372 const int frag = min (nbytes, (ssize_t) iovptr->iov_len);
1373 memcpy (bufptr, iovptr->iov_base, frag);
1379 res = sendto (buf, tot, flags,
1380 (struct sockaddr *) msg->msg_name,
1387 WSABUF wsabuf[iovcnt];
1390 const struct iovec *iovptr = iov + iovcnt;
1391 WSABUF *wsaptr = wsabuf + iovcnt;
1396 wsaptr->len = iovptr->iov_len;
1397 wsaptr->buf = (char *) iovptr->iov_base;
1399 while (wsaptr != wsabuf);
1404 if (is_nonblocking () || closed () || async_io ())
1405 res = WSASendTo (get_socket (), wsabuf, iovcnt, &ret,
1406 flags, (struct sockaddr *) msg->msg_name,
1407 msg->msg_namelen, NULL, NULL);
1411 if (prepare (evt, FD_CLOSE | FD_WRITE | (owner () ? FD_OOB : 0)))
1415 res = WSASendTo (get_socket (), wsabuf, iovcnt,
1417 (struct sockaddr *) msg->msg_name,
1418 msg->msg_namelen, NULL, NULL);
1420 while (res == SOCKET_ERROR
1421 && WSAGetLastError () == WSAEWOULDBLOCK
1422 && !(res = wait (evt, 0))
1428 if (res == SOCKET_ERROR)
1430 set_winsock_errno ();
1436 if (res == SOCKET_ERROR)
1438 /* If sendmsg fails, destroy all inflight descriptors. */
1439 if (descriptors_inflight && WSAGetLastError () != WSAEWOULDBLOCK)
1441 pinfo p (sec_peer_pid);
1443 p->destroy_inflight_descriptors ();
1446 /* Special handling for EPIPE and SIGPIPE.
1448 EPIPE is generated if the local end has been shut down on a connection
1449 oriented socket. In this case the process will also receive a SIGPIPE
1450 unless MSG_NOSIGNAL is set. */
1451 if (get_errno () == ESHUTDOWN && get_socket_type () == SOCK_STREAM)
1454 if (! (flags & MSG_NOSIGNAL))
1463 fhandler_socket::shutdown (int how)
1465 int res = ::shutdown (get_socket (), how);
1468 set_winsock_errno ();
1473 saw_shutdown_read (true);
1476 saw_shutdown_write (true);
1479 saw_shutdown_read (true);
1480 saw_shutdown_write (true);
1487 fhandler_socket::close ()
1491 /* HACK to allow a graceful shutdown even if shutdown() hasn't been
1492 called by the application. Note that this isn't the ultimate
1493 solution but it helps in many cases. */
1494 struct linger linger;
1496 linger.l_linger = 240; /* secs. default 2MSL value according to MSDN. */
1497 setsockopt (get_socket (), SOL_SOCKET, SO_LINGER,
1498 (const char *)&linger, sizeof linger);
1500 while ((res = closesocket (get_socket ())) != 0)
1502 if (WSAGetLastError () != WSAEWOULDBLOCK)
1504 set_winsock_errno ();
1508 if (WaitForSingleObject (signal_arrived, 10) == WAIT_OBJECT_0)
1514 WSASetLastError (0);
1517 debug_printf ("%d = fhandler_socket::close()", res);
1522 fhandler_socket::ioctl (unsigned int cmd, void *p)
1524 extern int get_ifconf (struct ifconf *ifc, int what); /* net.cc */
1526 struct ifconf ifc, *ifcp;
1527 struct ifreq *ifr, *ifrp;
1532 ifcp = (struct ifconf *) p;
1538 res = get_ifconf (ifcp, cmd);
1540 debug_printf ("error in get_ifconf");
1543 ifr = (struct ifreq *) p;
1549 ifr->ifr_flags = IFF_NOTRAILERS | IFF_UP | IFF_RUNNING;
1550 if (!strncmp(ifr->ifr_name, "lo", 2)
1551 || ntohl (((struct sockaddr_in *) &ifr->ifr_addr)->sin_addr.s_addr)
1553 ifr->ifr_flags |= IFF_LOOPBACK;
1555 ifr->ifr_flags |= IFF_BROADCAST;
1558 case SIOCGIFBRDADDR:
1559 case SIOCGIFNETMASK:
1566 ifc.ifc_buf = (char *) alloca (2048);
1568 ifr = (struct ifreq *) p;
1571 debug_printf ("ifr == NULL");
1576 res = get_ifconf (&ifc, cmd);
1579 debug_printf ("error in get_ifconf");
1583 debug_printf (" name: %s", ifr->ifr_name);
1584 for (ifrp = ifc.ifc_req;
1585 (caddr_t) ifrp < ifc.ifc_buf + ifc.ifc_len;
1588 debug_printf ("testname: %s", ifrp->ifr_name);
1589 if (! strcmp (ifrp->ifr_name, ifr->ifr_name))
1594 ifr->ifr_addr = ifrp->ifr_addr;
1596 case SIOCGIFBRDADDR:
1597 ifr->ifr_broadaddr = ifrp->ifr_broadaddr;
1599 case SIOCGIFNETMASK:
1600 ifr->ifr_netmask = ifrp->ifr_netmask;
1603 ifr->ifr_hwaddr = ifrp->ifr_hwaddr;
1606 ifr->ifr_metric = ifrp->ifr_metric;
1609 ifr->ifr_mtu = ifrp->ifr_mtu;
1615 if ((caddr_t) ifrp >= ifc.ifc_buf + ifc.ifc_len)
1623 res = WSAAsyncSelect (get_socket (), winmsg, WM_ASYNCIO,
1624 *(int *) p ? ASYNC_MASK : 0);
1625 syscall_printf ("Async I/O on socket %s",
1626 *(int *) p ? "started" : "cancelled");
1627 async_io (*(int *) p != 0);
1630 res = ioctlsocket (get_socket (), FIONREAD, (unsigned long *) p);
1631 if (res == SOCKET_ERROR)
1632 set_winsock_errno ();
1635 /* We must cancel WSAAsyncSelect (if any) before setting socket to
1638 if (cmd == FIONBIO && async_io () && *(int *) p == 0)
1639 WSAAsyncSelect (get_socket (), winmsg, 0, 0);
1640 res = ioctlsocket (get_socket (), cmd, (unsigned long *) p);
1641 if (res == SOCKET_ERROR)
1642 set_winsock_errno ();
1645 syscall_printf ("socket is now %sblocking",
1646 *(int *) p ? "non" : "");
1647 /* Start AsyncSelect if async socket unblocked */
1648 if (*(int *) p && async_io ())
1649 WSAAsyncSelect (get_socket (), winmsg, WM_ASYNCIO, ASYNC_MASK);
1651 set_nonblocking (*(int *) p);
1655 syscall_printf ("%d = ioctl_socket (%x, %x)", res, cmd, p);
1660 fhandler_socket::fcntl (int cmd, void *arg)
1663 int request, current;
1669 /* Urgh! Bad hack! */
1670 pid_t pid = (pid_t) arg;
1671 owner (pid == getpid ());
1672 debug_printf ("owner set to %d", owner ());
1677 /* Carefully test for the O_NONBLOCK or deprecated OLD_O_NDELAY flag.
1678 Set only the flag that has been passed in. If both are set, just
1679 record O_NONBLOCK. */
1680 int new_flags = (int) arg & O_NONBLOCK_MASK;
1681 if ((new_flags & OLD_O_NDELAY) && (new_flags & O_NONBLOCK))
1682 new_flags = O_NONBLOCK;
1683 current = get_flags () & O_NONBLOCK_MASK;
1684 request = new_flags ? 1 : 0;
1685 if (!!current != !!new_flags && (res = ioctl (FIONBIO, &request)))
1687 set_flags ((get_flags () & ~O_NONBLOCK_MASK) | new_flags);
1691 res = fhandler_base::fcntl (cmd, arg);
1698 fhandler_socket::set_close_on_exec (bool val)
1700 if (!winsock2_active) /* < Winsock 2.0 */
1701 set_no_inheritance (get_handle (), val);
1702 close_on_exec (val);
1703 debug_printf ("set close_on_exec for %s to %d", get_name (), val);
1707 fhandler_socket::set_sun_path (const char *path)
1709 sun_path = path ? cstrdup (path) : NULL;
1713 fhandler_socket::getpeereid (pid_t *pid, __uid32_t *euid, __gid32_t *egid)
1715 if (get_addr_family () != AF_LOCAL || get_socket_type () != SOCK_STREAM)
1720 if (connect_state () != connected)
1722 set_errno (ENOTCONN);
1725 if (sec_peer_pid == (pid_t) 0)
1727 set_errno (ENOTCONN); /* Usually when calling getpeereid on
1728 accepting (instead of accepted) socket. */
1733 if (efault.faulted (EFAULT))
1736 *pid = sec_peer_pid;
1738 *euid = sec_peer_uid;
1740 *egid = sec_peer_gid;