diff mbox series

[for-4.19,2/3] tools/libxs: Fix CLOEXEC handling in get_socket()

Message ID 20240628143116.1044976-3-andrew.cooper3@citrix.com (mailing list archive)
State New, archived
Headers show
Series tools/libxs: More CLOEXEC fixes | expand

Commit Message

Andrew Cooper June 28, 2024, 2:31 p.m. UTC
get_socket() opens a socket, then uses fcntl() to set CLOEXEC.  This is racy
with exec().

Open the socket with SOCK_CLOEXEC.  Use the same compatibility strategy as
O_CLOEXEC on ancient versions of Linux.

Reported-by: Frediano Ziglio <frediano.ziglio@cloud.com>
Signed-off-by: Andrew Cooper <andrew.cooper3@citrix.com>
---
CC: Anthony PERARD <anthony@xenproject.org>
CC: Juergen Gross <jgross@suse.com>
CC: Roger Pau Monné <roger.pau@citrix.com>
CC: Frediano Ziglio <frediano.ziglio@cloud.com>
CC: Oleksii Kurochko <oleksii.kurochko@gmail.com>
---
 tools/libs/store/xs.c | 14 ++++++++------
 1 file changed, 8 insertions(+), 6 deletions(-)
diff mbox series

Patch

diff --git a/tools/libs/store/xs.c b/tools/libs/store/xs.c
index 037e79d98b58..11a766c50887 100644
--- a/tools/libs/store/xs.c
+++ b/tools/libs/store/xs.c
@@ -44,6 +44,10 @@ 
 #define O_CLOEXEC 0
 #endif
 
+#ifndef SOCK_CLOEXEC
+#define SOCK_CLOEXEC 0
+#endif
+
 struct xs_stored_msg {
 	XEN_TAILQ_ENTRY(struct xs_stored_msg) list;
 	struct xsd_sockmsg hdr;
@@ -207,16 +211,14 @@  int xs_fileno(struct xs_handle *h)
 static int get_socket(const char *connect_to)
 {
 	struct sockaddr_un addr;
-	int sock, saved_errno, flags;
+	int sock, saved_errno;
 
-	sock = socket(PF_UNIX, SOCK_STREAM, 0);
+	sock = socket(PF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
 	if (sock < 0)
 		return -1;
 
-	if ((flags = fcntl(sock, F_GETFD)) < 0)
-		goto error;
-	flags |= FD_CLOEXEC;
-	if (fcntl(sock, F_SETFD, flags) < 0)
+	/* Compat for non-SOCK_CLOEXEC environments.  Racy. */
+	if (!SOCK_CLOEXEC && !set_cloexec(sock))
 		goto error;
 
 	addr.sun_family = AF_UNIX;