From c2faa3bd8f94373182f31af55789e965cc64dc07 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Aleix=20Conchillo=20Flaqu=C3=A9?= <aconchillo@gmail.com>
Date: Wed, 29 Jul 2020 16:59:27 -0700
Subject: [PATCH] accept4: add support for SOCK_NONBLOCK when using accept()

* lib/accept4.c (accept4): if accept4 is not available we default to
accept(). We add support for SOCK_NONBLOCK in this case.
---
 lib/accept4.c | 37 +++++++++++++++++++++++++++++++++++--
 1 file changed, 35 insertions(+), 2 deletions(-)

diff --git a/lib/accept4.c b/lib/accept4.c
index 9fab9c645..4d8c7995e 100644
--- a/lib/accept4.c
+++ b/lib/accept4.c
@@ -25,7 +25,19 @@
 #include "msvc-nothrow.h"
 
 #ifndef SOCK_CLOEXEC
-# define SOCK_CLOEXEC 0
+# if defined __MACH__ && defined __APPLE__
+#  define SOCK_CLOEXEC O_CLOEXEC
+# else
+#  define SOCK_CLOEXEC 0
+# endif
+#endif
+
+#ifndef SOCK_NONBLOCK
+# if defined __MACH__ && defined __APPLE__
+#  define SOCK_NONBLOCK O_NONBLOCK
+# else
+#  define SOCK_NONBLOCK 0
+# endif
 #endif
 
 int
@@ -54,7 +66,7 @@ accept4 (int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
 #endif
 
   /* Check the supported flags.  */
-  if ((flags & ~(SOCK_CLOEXEC | O_TEXT | O_BINARY)) != 0)
+  if ((flags & ~(SOCK_NONBLOCK | SOCK_CLOEXEC | O_TEXT | O_BINARY)) != 0)
     {
       errno = EINVAL;
       return -1;
@@ -117,6 +129,27 @@ accept4 (int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
 # endif
 #endif
 
+#if SOCK_NONBLOCK
+# if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
+# warning SOCK_NONBLOCK not currently supported on WIN32
+# else
+/* Unix API.  */
+  if (flags & SOCK_NONBLOCK)
+    {
+      int fcntl_flags;
+
+      if ((fcntl_flags = fcntl (fd, F_GETFL, 0)) < 0
+          || fcntl (fd, F_SETFL, fcntl_flags | O_NONBLOCK) == -1)
+        {
+          int saved_errno = errno;
+          close (fd);
+          errno = saved_errno;
+          return -1;
+        }
+    }
+# endif
+#endif
+
 #if O_BINARY
   if (flags & O_BINARY)
     set_binary_mode (fd, O_BINARY);
-- 
2.27.0

