All of lore.kernel.org
 help / color / mirror / Atom feed
* [PULL v2 00/25] Win socket patches
@ 2023-03-13 11:46 marcandre.lureau
  2023-03-13 11:46 ` [PULL v2 01/25] util: drop qemu_fork() marcandre.lureau
                   ` (25 more replies)
  0 siblings, 26 replies; 35+ messages in thread
From: marcandre.lureau @ 2023-03-13 11:46 UTC (permalink / raw)
  To: qemu-devel
  Cc: qemu-block, Dr. David Alan Gilbert, Daniel P. Berrangé,
	Philippe Mathieu-Daudé,
	Eric Blake, Samuel Thibault, Hanna Reitz, Stefan Weil,
	Thomas Huth, Fam Zheng, Beraldo Leal, Paolo Bonzini, Jason Wang,
	Michael Roth, Stefan Berger, qemu-arm, Joel Stanley,
	Alex Bennée, Peter Maydell, Stefan Hajnoczi,
	Markus Armbruster, Marc-André Lureau, Kevin Wolf,
	Laurent Vivier, Wainer dos Santos Moschetta

From: Marc-André Lureau <marcandre.lureau@redhat.com>

The following changes since commit 29c8a9e31a982874ce4e2c15f2bf82d5f8dc3517:

  Merge tag 'linux-user-for-8.0-pull-request' of https://gitlab.com/laurent_vivier/qemu into staging (2023-03-12 10:57:00 +0000)

are available in the Git repository at:

  https://gitlab.com/marcandre.lureau/qemu.git tags/win-socket-pull-request

for you to fetch changes up to 4bf21c7f748bee42b6f4692f8c37a11d1033b2d1:

  monitor: restrict command getfd to POSIX hosts (2023-03-13 15:46:09 +0400)

----------------------------------------------------------------
QMP command to import win32 sockets

----------------------------------------------------------------

Marc-André Lureau (25):
  util: drop qemu_fork()
  tests: use closesocket()
  io: use closesocket()
  tests: add test-error-report
  error: add global &error_warn destination
  win32/socket: introduce qemu_socket_select() helper
  win32/socket: introduce qemu_socket_unselect() helper
  aio: make aio_set_fd_poll() static to aio-posix.c
  aio/win32: aio_set_fd_handler() only supports SOCKET
  main-loop: remove qemu_fd_register(), win32/slirp/socket specific
  slirp: unregister the win32 SOCKET
  slirp: open-code qemu_socket_(un)select()
  win32: avoid mixing SOCKET and file descriptor space
  os-posix: remove useless ioctlsocket() define
  win32: replace closesocket() with close() wrapper
  tests: fix path separator, use g_build_filename()
  char: do not double-close fd when failing to add client
  tests/docker: fix a win32 error due to portability
  osdep: implement qemu_socketpair() for win32
  qmp: 'add_client' actually expects sockets
  monitor: release the lock before calling close()
  qmp: add 'get-win32-socket'
  libqtest: make qtest_qmp_add_client work on win32
  qtest: enable vnc-display test on win32
  monitor: restrict command getfd to POSIX hosts

 qapi/misc.json                       |  36 ++-
 include/block/aio.h                  |   8 -
 include/qapi/error.h                 |   6 +
 include/qemu/main-loop.h             |   2 -
 include/qemu/osdep.h                 |  14 --
 include/qemu/sockets.h               |   2 -
 include/sysemu/os-posix.h            |   3 -
 include/sysemu/os-win32.h            |  15 +-
 tests/qtest/libqtest.h               |   5 +-
 backends/tpm/tpm_emulator.c          |   6 +-
 chardev/char.c                       |   2 -
 crypto/afalg.c                       |   6 +-
 hw/hyperv/syndbg.c                   |   4 +-
 io/channel-socket.c                  |   8 +-
 io/channel-watch.c                   |  10 +-
 monitor/fds.c                        |  77 ++++--
 monitor/hmp-cmds.c                   |   2 +
 monitor/qmp-cmds.c                   |   7 +
 net/dgram.c                          |  14 +-
 net/slirp.c                          |  16 +-
 net/socket.c                         |  22 +-
 tests/qtest/libqtest.c               |  26 +-
 tests/qtest/microbit-test.c          |   2 +-
 tests/qtest/netdev-socket.c          |  10 +-
 tests/qtest/vnc-display-test.c       |  12 +-
 tests/unit/socket-helpers.c          |   2 +-
 tests/unit/test-error-report.c       | 139 +++++++++++
 tests/unit/test-io-channel-command.c |   2 +-
 util/aio-posix.c                     |   6 +-
 util/aio-win32.c                     |  23 +-
 util/error.c                         |  10 +-
 util/main-loop.c                     |  11 -
 util/oslib-posix.c                   |  70 ------
 util/oslib-win32.c                   | 350 ++++++++++++++++++++++++---
 util/qemu-sockets.c                  |  22 +-
 hmp-commands.hx                      |   2 +
 tests/docker/docker.py               |   6 +-
 tests/unit/meson.build               |   1 +
 38 files changed, 701 insertions(+), 258 deletions(-)
 create mode 100644 tests/unit/test-error-report.c

-- 
2.39.2



^ permalink raw reply	[flat|nested] 35+ messages in thread

* [PULL v2 01/25] util: drop qemu_fork()
  2023-03-13 11:46 [PULL v2 00/25] Win socket patches marcandre.lureau
@ 2023-03-13 11:46 ` marcandre.lureau
  2023-03-13 11:46 ` [PULL v2 02/25] tests: use closesocket() marcandre.lureau
                   ` (24 subsequent siblings)
  25 siblings, 0 replies; 35+ messages in thread
From: marcandre.lureau @ 2023-03-13 11:46 UTC (permalink / raw)
  To: qemu-devel
  Cc: qemu-block, Dr. David Alan Gilbert, Daniel P. Berrangé,
	Philippe Mathieu-Daudé,
	Eric Blake, Samuel Thibault, Hanna Reitz, Stefan Weil,
	Thomas Huth, Fam Zheng, Beraldo Leal, Paolo Bonzini, Jason Wang,
	Michael Roth, Stefan Berger, qemu-arm, Joel Stanley,
	Alex Bennée, Peter Maydell, Stefan Hajnoczi,
	Markus Armbruster, Marc-André Lureau, Kevin Wolf,
	Laurent Vivier, Wainer dos Santos Moschetta

From: Marc-André Lureau <marcandre.lureau@redhat.com>

Fortunately, qemu_fork() is no longer used since commit
a95570e3e4d6 ("io/command: use glib GSpawn, instead of open-coding
fork/exec"). (GSpawn uses posix_spawn() whenever possible instead)

Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
Reviewed-by: Daniel P. Berrangé <berrange@redhat.com>
Message-Id: <20230221124802.4103554-2-marcandre.lureau@redhat.com>
---
 include/qemu/osdep.h | 14 ---------
 util/oslib-posix.c   | 70 --------------------------------------------
 util/oslib-win32.c   |  9 ------
 3 files changed, 93 deletions(-)

diff --git a/include/qemu/osdep.h b/include/qemu/osdep.h
index 88c9facbf2..f68b5d8708 100644
--- a/include/qemu/osdep.h
+++ b/include/qemu/osdep.h
@@ -665,20 +665,6 @@ void qemu_prealloc_mem(int fd, char *area, size_t sz, int max_threads,
  */
 char *qemu_get_pid_name(pid_t pid);
 
-/**
- * qemu_fork:
- *
- * A version of fork that avoids signal handler race
- * conditions that can lead to child process getting
- * signals that are otherwise only expected by the
- * parent. It also resets all signal handlers to the
- * default settings.
- *
- * Returns 0 to child process, pid number to parent
- * or -1 on failure.
- */
-pid_t qemu_fork(Error **errp);
-
 /* Using intptr_t ensures that qemu_*_page_mask is sign-extended even
  * when intptr_t is 32-bit and we are aligning a long long.
  */
diff --git a/util/oslib-posix.c b/util/oslib-posix.c
index 77d882e681..760390b31e 100644
--- a/util/oslib-posix.c
+++ b/util/oslib-posix.c
@@ -583,76 +583,6 @@ char *qemu_get_pid_name(pid_t pid)
 }
 
 
-pid_t qemu_fork(Error **errp)
-{
-    sigset_t oldmask, newmask;
-    struct sigaction sig_action;
-    int saved_errno;
-    pid_t pid;
-
-    /*
-     * Need to block signals now, so that child process can safely
-     * kill off caller's signal handlers without a race.
-     */
-    sigfillset(&newmask);
-    if (pthread_sigmask(SIG_SETMASK, &newmask, &oldmask) != 0) {
-        error_setg_errno(errp, errno,
-                         "cannot block signals");
-        return -1;
-    }
-
-    pid = fork();
-    saved_errno = errno;
-
-    if (pid < 0) {
-        /* attempt to restore signal mask, but ignore failure, to
-         * avoid obscuring the fork failure */
-        (void)pthread_sigmask(SIG_SETMASK, &oldmask, NULL);
-        error_setg_errno(errp, saved_errno,
-                         "cannot fork child process");
-        errno = saved_errno;
-        return -1;
-    } else if (pid) {
-        /* parent process */
-
-        /* Restore our original signal mask now that the child is
-         * safely running. Only documented failures are EFAULT (not
-         * possible, since we are using just-grabbed mask) or EINVAL
-         * (not possible, since we are using correct arguments).  */
-        (void)pthread_sigmask(SIG_SETMASK, &oldmask, NULL);
-    } else {
-        /* child process */
-        size_t i;
-
-        /* Clear out all signal handlers from parent so nothing
-         * unexpected can happen in our child once we unblock
-         * signals */
-        sig_action.sa_handler = SIG_DFL;
-        sig_action.sa_flags = 0;
-        sigemptyset(&sig_action.sa_mask);
-
-        for (i = 1; i < NSIG; i++) {
-            /* Only possible errors are EFAULT or EINVAL The former
-             * won't happen, the latter we expect, so no need to check
-             * return value */
-            (void)sigaction(i, &sig_action, NULL);
-        }
-
-        /* Unmask all signals in child, since we've no idea what the
-         * caller's done with their signal mask and don't want to
-         * propagate that to children */
-        sigemptyset(&newmask);
-        if (pthread_sigmask(SIG_SETMASK, &newmask, NULL) != 0) {
-            Error *local_err = NULL;
-            error_setg_errno(&local_err, errno,
-                             "cannot unblock signals");
-            error_report_err(local_err);
-            _exit(1);
-        }
-    }
-    return pid;
-}
-
 void *qemu_alloc_stack(size_t *sz)
 {
     void *ptr, *guardpage;
diff --git a/util/oslib-win32.c b/util/oslib-win32.c
index 07ade41800..528c9ee156 100644
--- a/util/oslib-win32.c
+++ b/util/oslib-win32.c
@@ -283,15 +283,6 @@ char *qemu_get_pid_name(pid_t pid)
 }
 
 
-pid_t qemu_fork(Error **errp)
-{
-    errno = ENOSYS;
-    error_setg_errno(errp, errno,
-                     "cannot fork child process");
-    return -1;
-}
-
-
 #undef connect
 int qemu_connect_wrap(int sockfd, const struct sockaddr *addr,
                       socklen_t addrlen)
-- 
2.39.2



^ permalink raw reply related	[flat|nested] 35+ messages in thread

* [PULL v2 02/25] tests: use closesocket()
  2023-03-13 11:46 [PULL v2 00/25] Win socket patches marcandre.lureau
  2023-03-13 11:46 ` [PULL v2 01/25] util: drop qemu_fork() marcandre.lureau
@ 2023-03-13 11:46 ` marcandre.lureau
  2023-03-13 11:46 ` [PULL v2 03/25] io: " marcandre.lureau
                   ` (23 subsequent siblings)
  25 siblings, 0 replies; 35+ messages in thread
From: marcandre.lureau @ 2023-03-13 11:46 UTC (permalink / raw)
  To: qemu-devel
  Cc: qemu-block, Dr. David Alan Gilbert, Daniel P. Berrangé,
	Philippe Mathieu-Daudé,
	Eric Blake, Samuel Thibault, Hanna Reitz, Stefan Weil,
	Thomas Huth, Fam Zheng, Beraldo Leal, Paolo Bonzini, Jason Wang,
	Michael Roth, Stefan Berger, qemu-arm, Joel Stanley,
	Alex Bennée, Peter Maydell, Stefan Hajnoczi,
	Markus Armbruster, Marc-André Lureau, Kevin Wolf,
	Laurent Vivier, Wainer dos Santos Moschetta

From: Marc-André Lureau <marcandre.lureau@redhat.com>

Because they are actually sockets...

Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
Reviewed-by: Thomas Huth <thuth@redhat.com>
Message-Id: <20230221124802.4103554-3-marcandre.lureau@redhat.com>
---
 tests/unit/socket-helpers.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/tests/unit/socket-helpers.c b/tests/unit/socket-helpers.c
index eecadf3a3c..914b3aa0cf 100644
--- a/tests/unit/socket-helpers.c
+++ b/tests/unit/socket-helpers.c
@@ -117,13 +117,13 @@ static int socket_can_bind_connect(const char *hostname, int family)
 
  cleanup:
     if (afd != -1) {
-        close(afd);
+        closesocket(afd);
     }
     if (cfd != -1) {
-        close(cfd);
+        closesocket(cfd);
     }
     if (lfd != -1) {
-        close(lfd);
+        closesocket(lfd);
     }
     if (res) {
         freeaddrinfo(res);
-- 
2.39.2



^ permalink raw reply related	[flat|nested] 35+ messages in thread

* [PULL v2 03/25] io: use closesocket()
  2023-03-13 11:46 [PULL v2 00/25] Win socket patches marcandre.lureau
  2023-03-13 11:46 ` [PULL v2 01/25] util: drop qemu_fork() marcandre.lureau
  2023-03-13 11:46 ` [PULL v2 02/25] tests: use closesocket() marcandre.lureau
@ 2023-03-13 11:46 ` marcandre.lureau
  2023-03-13 11:46 ` [PULL v2 04/25] tests: add test-error-report marcandre.lureau
                   ` (22 subsequent siblings)
  25 siblings, 0 replies; 35+ messages in thread
From: marcandre.lureau @ 2023-03-13 11:46 UTC (permalink / raw)
  To: qemu-devel
  Cc: qemu-block, Dr. David Alan Gilbert, Daniel P. Berrangé,
	Philippe Mathieu-Daudé,
	Eric Blake, Samuel Thibault, Hanna Reitz, Stefan Weil,
	Thomas Huth, Fam Zheng, Beraldo Leal, Paolo Bonzini, Jason Wang,
	Michael Roth, Stefan Berger, qemu-arm, Joel Stanley,
	Alex Bennée, Peter Maydell, Stefan Hajnoczi,
	Markus Armbruster, Marc-André Lureau, Kevin Wolf,
	Laurent Vivier, Wainer dos Santos Moschetta

From: Marc-André Lureau <marcandre.lureau@redhat.com>

Because they are actually sockets...

Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
Reviewed-by: Thomas Huth <thuth@redhat.com>
Message-Id: <20230221124802.4103554-4-marcandre.lureau@redhat.com>
---
 io/channel-socket.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/io/channel-socket.c b/io/channel-socket.c
index 7aca84f61a..2040297d2b 100644
--- a/io/channel-socket.c
+++ b/io/channel-socket.c
@@ -159,7 +159,7 @@ int qio_channel_socket_connect_sync(QIOChannelSocket *ioc,
 
     trace_qio_channel_socket_connect_complete(ioc, fd);
     if (qio_channel_socket_set_fd(ioc, fd, errp) < 0) {
-        close(fd);
+        closesocket(fd);
         return -1;
     }
 
@@ -233,7 +233,7 @@ int qio_channel_socket_listen_sync(QIOChannelSocket *ioc,
 
     trace_qio_channel_socket_listen_complete(ioc, fd);
     if (qio_channel_socket_set_fd(ioc, fd, errp) < 0) {
-        close(fd);
+        closesocket(fd);
         return -1;
     }
     qio_channel_set_feature(QIO_CHANNEL(ioc), QIO_CHANNEL_FEATURE_LISTEN);
@@ -310,7 +310,7 @@ int qio_channel_socket_dgram_sync(QIOChannelSocket *ioc,
 
     trace_qio_channel_socket_dgram_complete(ioc, fd);
     if (qio_channel_socket_set_fd(ioc, fd, errp) < 0) {
-        close(fd);
+        closesocket(fd);
         return -1;
     }
 
-- 
2.39.2



^ permalink raw reply related	[flat|nested] 35+ messages in thread

* [PULL v2 04/25] tests: add test-error-report
  2023-03-13 11:46 [PULL v2 00/25] Win socket patches marcandre.lureau
                   ` (2 preceding siblings ...)
  2023-03-13 11:46 ` [PULL v2 03/25] io: " marcandre.lureau
@ 2023-03-13 11:46 ` marcandre.lureau
  2023-03-13 11:46 ` [PULL v2 05/25] error: add global &error_warn destination marcandre.lureau
                   ` (21 subsequent siblings)
  25 siblings, 0 replies; 35+ messages in thread
From: marcandre.lureau @ 2023-03-13 11:46 UTC (permalink / raw)
  To: qemu-devel
  Cc: qemu-block, Dr. David Alan Gilbert, Daniel P. Berrangé,
	Philippe Mathieu-Daudé,
	Eric Blake, Samuel Thibault, Hanna Reitz, Stefan Weil,
	Thomas Huth, Fam Zheng, Beraldo Leal, Paolo Bonzini, Jason Wang,
	Michael Roth, Stefan Berger, qemu-arm, Joel Stanley,
	Alex Bennée, Peter Maydell, Stefan Hajnoczi,
	Markus Armbruster, Marc-André Lureau, Kevin Wolf,
	Laurent Vivier, Wainer dos Santos Moschetta

From: Marc-André Lureau <marcandre.lureau@redhat.com>

Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Message-Id: <20230221124802.4103554-5-marcandre.lureau@redhat.com>
---
 tests/unit/test-error-report.c | 121 +++++++++++++++++++++++++++++++++
 tests/unit/meson.build         |   1 +
 2 files changed, 122 insertions(+)
 create mode 100644 tests/unit/test-error-report.c

diff --git a/tests/unit/test-error-report.c b/tests/unit/test-error-report.c
new file mode 100644
index 0000000000..b09650687b
--- /dev/null
+++ b/tests/unit/test-error-report.c
@@ -0,0 +1,121 @@
+/*
+ * Error reporting test
+ *
+ * Copyright (C) 2022 Red Hat Inc.
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
+ * See the COPYING file in the top-level directory.
+ */
+
+#include "qemu/osdep.h"
+#include "glib-compat.h"
+#include <locale.h>
+
+#include "qemu/error-report.h"
+
+static void
+test_error_report_simple(void)
+{
+    if (g_test_subprocess()) {
+        error_report("%s", "test error");
+        warn_report("%s", "test warn");
+        info_report("%s", "test info");
+        return;
+    }
+
+    g_test_trap_subprocess(NULL, 0, 0);
+    g_test_trap_assert_passed();
+    g_test_trap_assert_stderr("\
+test-error-report: test error*\
+test-error-report: warning: test warn*\
+test-error-report: info: test info*\
+");
+}
+
+static void
+test_error_report_loc(void)
+{
+    if (g_test_subprocess()) {
+        loc_set_file("some-file.c", 7717);
+        error_report("%s", "test error1");
+        loc_set_none();
+        error_report("%s", "test error2");
+        return;
+    }
+
+    g_test_trap_subprocess(NULL, 0, 0);
+    g_test_trap_assert_passed();
+    g_test_trap_assert_stderr("\
+test-error-report:some-file.c:7717: test error1*\
+test-error-report: test error2*\
+");
+}
+
+static void
+test_error_report_glog(void)
+{
+    if (g_test_subprocess()) {
+        g_message("gmessage");
+        return;
+    }
+
+    g_test_trap_subprocess(NULL, 0, 0);
+    g_test_trap_assert_passed();
+    g_test_trap_assert_stderr("test-error-report: info: gmessage*");
+}
+
+static void
+test_error_report_once(void)
+{
+    int i;
+
+    if (g_test_subprocess()) {
+        for (i = 0; i < 3; i++) {
+            warn_report_once("warn");
+            error_report_once("err");
+        }
+        return;
+    }
+
+    g_test_trap_subprocess(NULL, 0, 0);
+    g_test_trap_assert_passed();
+    g_test_trap_assert_stderr("\
+test-error-report: warning: warn*\
+test-error-report: err*\
+");
+}
+
+static void
+test_error_report_timestamp(void)
+{
+    if (g_test_subprocess()) {
+        message_with_timestamp = true;
+        warn_report("warn");
+        error_report("err");
+        return;
+    }
+
+    g_test_trap_subprocess(NULL, 0, 0);
+    g_test_trap_assert_passed();
+    g_test_trap_assert_stderr("\
+*-*-*:*:* test-error-report: warning: warn*\
+*-*-*:*:* test-error-report: err*\
+");
+}
+
+int
+main(int argc, char *argv[])
+{
+    setlocale(LC_ALL, "");
+
+    g_test_init(&argc, &argv, NULL);
+    error_init("test-error-report");
+
+    g_test_add_func("/error-report/simple", test_error_report_simple);
+    g_test_add_func("/error-report/loc", test_error_report_loc);
+    g_test_add_func("/error-report/glog", test_error_report_glog);
+    g_test_add_func("/error-report/once", test_error_report_once);
+    g_test_add_func("/error-report/timestamp", test_error_report_timestamp);
+
+    return g_test_run();
+}
diff --git a/tests/unit/meson.build b/tests/unit/meson.build
index d9c0a7eae6..fa63cfe6ff 100644
--- a/tests/unit/meson.build
+++ b/tests/unit/meson.build
@@ -11,6 +11,7 @@ tests = {
   'check-qobject': [],
   'check-qjson': [],
   'check-qlit': [],
+  'test-error-report': [],
   'test-qobject-output-visitor': [testqapi],
   'test-clone-visitor': [testqapi],
   'test-qobject-input-visitor': [testqapi],
-- 
2.39.2



^ permalink raw reply related	[flat|nested] 35+ messages in thread

* [PULL v2 05/25] error: add global &error_warn destination
  2023-03-13 11:46 [PULL v2 00/25] Win socket patches marcandre.lureau
                   ` (3 preceding siblings ...)
  2023-03-13 11:46 ` [PULL v2 04/25] tests: add test-error-report marcandre.lureau
@ 2023-03-13 11:46 ` marcandre.lureau
  2023-04-06 13:16   ` Peter Maydell
  2023-03-13 11:46 ` [PULL v2 06/25] win32/socket: introduce qemu_socket_select() helper marcandre.lureau
                   ` (20 subsequent siblings)
  25 siblings, 1 reply; 35+ messages in thread
From: marcandre.lureau @ 2023-03-13 11:46 UTC (permalink / raw)
  To: qemu-devel
  Cc: qemu-block, Dr. David Alan Gilbert, Daniel P. Berrangé,
	Philippe Mathieu-Daudé,
	Eric Blake, Samuel Thibault, Hanna Reitz, Stefan Weil,
	Thomas Huth, Fam Zheng, Beraldo Leal, Paolo Bonzini, Jason Wang,
	Michael Roth, Stefan Berger, qemu-arm, Joel Stanley,
	Alex Bennée, Peter Maydell, Stefan Hajnoczi,
	Markus Armbruster, Marc-André Lureau, Kevin Wolf,
	Laurent Vivier, Wainer dos Santos Moschetta

From: Marc-André Lureau <marcandre.lureau@redhat.com>

This can help debugging issues or develop, when error handling is
introduced.

Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Message-Id: <20230221124802.4103554-6-marcandre.lureau@redhat.com>
---
 include/qapi/error.h           |  6 ++++++
 tests/unit/test-error-report.c | 18 ++++++++++++++++++
 util/error.c                   | 10 +++++++---
 3 files changed, 31 insertions(+), 3 deletions(-)

diff --git a/include/qapi/error.h b/include/qapi/error.h
index d798faeec3..f21a231bb1 100644
--- a/include/qapi/error.h
+++ b/include/qapi/error.h
@@ -519,6 +519,12 @@ static inline void error_propagator_cleanup(ErrorPropagator *prop)
 
 G_DEFINE_AUTO_CLEANUP_CLEAR_FUNC(ErrorPropagator, error_propagator_cleanup);
 
+/*
+ * Special error destination to warn on error.
+ * See error_setg() and error_propagate() for details.
+ */
+extern Error *error_warn;
+
 /*
  * Special error destination to abort on error.
  * See error_setg() and error_propagate() for details.
diff --git a/tests/unit/test-error-report.c b/tests/unit/test-error-report.c
index b09650687b..54319c86c9 100644
--- a/tests/unit/test-error-report.c
+++ b/tests/unit/test-error-report.c
@@ -12,6 +12,7 @@
 #include <locale.h>
 
 #include "qemu/error-report.h"
+#include "qapi/error.h"
 
 static void
 test_error_report_simple(void)
@@ -103,6 +104,22 @@ test_error_report_timestamp(void)
 ");
 }
 
+static void
+test_error_warn(void)
+{
+    if (g_test_subprocess()) {
+        error_setg(&error_warn, "Testing &error_warn");
+        return;
+    }
+
+    g_test_trap_subprocess(NULL, 0, 0);
+    g_test_trap_assert_passed();
+    g_test_trap_assert_stderr("\
+test-error-report: warning: Testing &error_warn*\
+");
+}
+
+
 int
 main(int argc, char *argv[])
 {
@@ -116,6 +133,7 @@ main(int argc, char *argv[])
     g_test_add_func("/error-report/glog", test_error_report_glog);
     g_test_add_func("/error-report/once", test_error_report_once);
     g_test_add_func("/error-report/timestamp", test_error_report_timestamp);
+    g_test_add_func("/error-report/warn", test_error_warn);
 
     return g_test_run();
 }
diff --git a/util/error.c b/util/error.c
index 1e7af665b8..5537245da6 100644
--- a/util/error.c
+++ b/util/error.c
@@ -27,8 +27,9 @@ struct Error
 
 Error *error_abort;
 Error *error_fatal;
+Error *error_warn;
 
-static void error_handle_fatal(Error **errp, Error *err)
+static void error_handle(Error **errp, Error *err)
 {
     if (errp == &error_abort) {
         fprintf(stderr, "Unexpected error in %s() at %s:%d:\n",
@@ -43,6 +44,9 @@ static void error_handle_fatal(Error **errp, Error *err)
         error_report_err(err);
         exit(1);
     }
+    if (errp == &error_warn) {
+        warn_report_err(err);
+    }
 }
 
 G_GNUC_PRINTF(6, 0)
@@ -71,7 +75,7 @@ static void error_setv(Error **errp,
     err->line = line;
     err->func = func;
 
-    error_handle_fatal(errp, err);
+    error_handle(errp, err);
     *errp = err;
 
     errno = saved_errno;
@@ -284,7 +288,7 @@ void error_propagate(Error **dst_errp, Error *local_err)
     if (!local_err) {
         return;
     }
-    error_handle_fatal(dst_errp, local_err);
+    error_handle(dst_errp, local_err);
     if (dst_errp && !*dst_errp) {
         *dst_errp = local_err;
     } else {
-- 
2.39.2



^ permalink raw reply related	[flat|nested] 35+ messages in thread

* [PULL v2 06/25] win32/socket: introduce qemu_socket_select() helper
  2023-03-13 11:46 [PULL v2 00/25] Win socket patches marcandre.lureau
                   ` (4 preceding siblings ...)
  2023-03-13 11:46 ` [PULL v2 05/25] error: add global &error_warn destination marcandre.lureau
@ 2023-03-13 11:46 ` marcandre.lureau
  2023-03-13 11:46 ` [PULL v2 07/25] win32/socket: introduce qemu_socket_unselect() helper marcandre.lureau
                   ` (19 subsequent siblings)
  25 siblings, 0 replies; 35+ messages in thread
From: marcandre.lureau @ 2023-03-13 11:46 UTC (permalink / raw)
  To: qemu-devel
  Cc: qemu-block, Dr. David Alan Gilbert, Daniel P. Berrangé,
	Philippe Mathieu-Daudé,
	Eric Blake, Samuel Thibault, Hanna Reitz, Stefan Weil,
	Thomas Huth, Fam Zheng, Beraldo Leal, Paolo Bonzini, Jason Wang,
	Michael Roth, Stefan Berger, qemu-arm, Joel Stanley,
	Alex Bennée, Peter Maydell, Stefan Hajnoczi,
	Markus Armbruster, Marc-André Lureau, Kevin Wolf,
	Laurent Vivier, Wainer dos Santos Moschetta

From: Marc-André Lureau <marcandre.lureau@redhat.com>

This is a wrapper for WSAEventSelect, with Error handling. By default,
it will produce a warning, so callers don't have to be modified
now, and yet we can spot potential mis-use.

Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Message-Id: <20230221124802.4103554-7-marcandre.lureau@redhat.com>
---
 include/sysemu/os-win32.h |  5 +++++
 io/channel-socket.c       |  4 ++--
 io/channel-watch.c        |  6 +++---
 util/aio-win32.c          |  2 +-
 util/main-loop.c          |  6 +++---
 util/oslib-win32.c        | 17 ++++++++++++++++-
 6 files changed, 30 insertions(+), 10 deletions(-)

diff --git a/include/sysemu/os-win32.h b/include/sysemu/os-win32.h
index 97d0243aee..9f842ae643 100644
--- a/include/sysemu/os-win32.h
+++ b/include/sysemu/os-win32.h
@@ -29,6 +29,7 @@
 #include <winsock2.h>
 #include <windows.h>
 #include <ws2tcpip.h>
+#include "qemu/typedefs.h"
 
 #ifdef HAVE_AFUNIX_H
 #include <afunix.h>
@@ -164,6 +165,10 @@ static inline void qemu_funlockfile(FILE *f)
 #endif
 }
 
+/* Helper for WSAEventSelect, to report errors */
+bool qemu_socket_select(SOCKET s, WSAEVENT hEventObject,
+                        long lNetworkEvents, Error **errp);
+
 /* We wrap all the sockets functions so that we can
  * set errno based on WSAGetLastError()
  */
diff --git a/io/channel-socket.c b/io/channel-socket.c
index 2040297d2b..0bc29c4808 100644
--- a/io/channel-socket.c
+++ b/io/channel-socket.c
@@ -442,7 +442,7 @@ static void qio_channel_socket_finalize(Object *obj)
             }
         }
 #ifdef WIN32
-        WSAEventSelect(ioc->fd, NULL, 0);
+        qemu_socket_select(ioc->fd, NULL, 0, NULL);
 #endif
         closesocket(ioc->fd);
         ioc->fd = -1;
@@ -846,7 +846,7 @@ qio_channel_socket_close(QIOChannel *ioc,
 
     if (sioc->fd != -1) {
 #ifdef WIN32
-        WSAEventSelect(sioc->fd, NULL, 0);
+        qemu_socket_select(sioc->fd, NULL, 0, NULL);
 #endif
         if (qio_channel_has_feature(ioc, QIO_CHANNEL_FEATURE_LISTEN)) {
             socket_listen_cleanup(sioc->fd, errp);
diff --git a/io/channel-watch.c b/io/channel-watch.c
index ad7c568a84..6ac41009fa 100644
--- a/io/channel-watch.c
+++ b/io/channel-watch.c
@@ -281,9 +281,9 @@ GSource *qio_channel_create_socket_watch(QIOChannel *ioc,
     GSource *source;
     QIOChannelSocketSource *ssource;
 
-    WSAEventSelect(socket, ioc->event,
-                   FD_READ | FD_ACCEPT | FD_CLOSE |
-                   FD_CONNECT | FD_WRITE | FD_OOB);
+    qemu_socket_select(socket, ioc->event,
+                       FD_READ | FD_ACCEPT | FD_CLOSE |
+                       FD_CONNECT | FD_WRITE | FD_OOB, NULL);
 
     source = g_source_new(&qio_channel_socket_source_funcs,
                           sizeof(QIOChannelSocketSource));
diff --git a/util/aio-win32.c b/util/aio-win32.c
index 80cfe012ad..be5136e486 100644
--- a/util/aio-win32.c
+++ b/util/aio-win32.c
@@ -115,7 +115,7 @@ void aio_set_fd_handler(AioContext *ctx,
 
         QLIST_INSERT_HEAD_RCU(&ctx->aio_handlers, node, node);
         event = event_notifier_get_handle(&ctx->notifier);
-        WSAEventSelect(node->pfd.fd, event, bitmask);
+        qemu_socket_select(node->pfd.fd, event, bitmask, NULL);
     }
     if (old_node) {
         aio_remove_fd_handler(ctx, old_node);
diff --git a/util/main-loop.c b/util/main-loop.c
index 3c0f525192..16e837fb12 100644
--- a/util/main-loop.c
+++ b/util/main-loop.c
@@ -416,9 +416,9 @@ void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
 
 void qemu_fd_register(int fd)
 {
-    WSAEventSelect(fd, event_notifier_get_handle(&qemu_aio_context->notifier),
-                   FD_READ | FD_ACCEPT | FD_CLOSE |
-                   FD_CONNECT | FD_WRITE | FD_OOB);
+    qemu_socket_select(fd, event_notifier_get_handle(&qemu_aio_context->notifier),
+                       FD_READ | FD_ACCEPT | FD_CLOSE |
+                       FD_CONNECT | FD_WRITE | FD_OOB, NULL);
 }
 
 static int pollfds_fill(GArray *pollfds, fd_set *rfds, fd_set *wfds,
diff --git a/util/oslib-win32.c b/util/oslib-win32.c
index 528c9ee156..df752fc762 100644
--- a/util/oslib-win32.c
+++ b/util/oslib-win32.c
@@ -180,7 +180,7 @@ static int socket_error(void)
 void qemu_socket_set_block(int fd)
 {
     unsigned long opt = 0;
-    WSAEventSelect(fd, NULL, 0);
+    qemu_socket_select(fd, NULL, 0, NULL);
     ioctlsocket(fd, FIONBIO, &opt);
 }
 
@@ -283,6 +283,21 @@ char *qemu_get_pid_name(pid_t pid)
 }
 
 
+bool qemu_socket_select(SOCKET s, WSAEVENT hEventObject,
+                        long lNetworkEvents, Error **errp)
+{
+    if (errp == NULL) {
+        errp = &error_warn;
+    }
+
+    if (WSAEventSelect(s, hEventObject, lNetworkEvents) != 0) {
+        error_setg_win32(errp, WSAGetLastError(), "failed to WSAEventSelect()");
+        return false;
+    }
+
+    return true;
+}
+
 #undef connect
 int qemu_connect_wrap(int sockfd, const struct sockaddr *addr,
                       socklen_t addrlen)
-- 
2.39.2



^ permalink raw reply related	[flat|nested] 35+ messages in thread

* [PULL v2 07/25] win32/socket: introduce qemu_socket_unselect() helper
  2023-03-13 11:46 [PULL v2 00/25] Win socket patches marcandre.lureau
                   ` (5 preceding siblings ...)
  2023-03-13 11:46 ` [PULL v2 06/25] win32/socket: introduce qemu_socket_select() helper marcandre.lureau
@ 2023-03-13 11:46 ` marcandre.lureau
  2023-03-13 11:46 ` [PULL v2 08/25] aio: make aio_set_fd_poll() static to aio-posix.c marcandre.lureau
                   ` (18 subsequent siblings)
  25 siblings, 0 replies; 35+ messages in thread
From: marcandre.lureau @ 2023-03-13 11:46 UTC (permalink / raw)
  To: qemu-devel
  Cc: qemu-block, Dr. David Alan Gilbert, Daniel P. Berrangé,
	Philippe Mathieu-Daudé,
	Eric Blake, Samuel Thibault, Hanna Reitz, Stefan Weil,
	Thomas Huth, Fam Zheng, Beraldo Leal, Paolo Bonzini, Jason Wang,
	Michael Roth, Stefan Berger, qemu-arm, Joel Stanley,
	Alex Bennée, Peter Maydell, Stefan Hajnoczi,
	Markus Armbruster, Marc-André Lureau, Kevin Wolf,
	Laurent Vivier, Wainer dos Santos Moschetta

From: Marc-André Lureau <marcandre.lureau@redhat.com>

A more explicit version of qemu_socket_select() with no events.

Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Message-Id: <20230221124802.4103554-8-marcandre.lureau@redhat.com>
---
 include/sysemu/os-win32.h | 2 ++
 io/channel-socket.c       | 4 ++--
 util/oslib-win32.c        | 7 ++++++-
 3 files changed, 10 insertions(+), 3 deletions(-)

diff --git a/include/sysemu/os-win32.h b/include/sysemu/os-win32.h
index 9f842ae643..504a8966c3 100644
--- a/include/sysemu/os-win32.h
+++ b/include/sysemu/os-win32.h
@@ -169,6 +169,8 @@ static inline void qemu_funlockfile(FILE *f)
 bool qemu_socket_select(SOCKET s, WSAEVENT hEventObject,
                         long lNetworkEvents, Error **errp);
 
+bool qemu_socket_unselect(SOCKET s, Error **errp);
+
 /* We wrap all the sockets functions so that we can
  * set errno based on WSAGetLastError()
  */
diff --git a/io/channel-socket.c b/io/channel-socket.c
index 0bc29c4808..03757c7a7e 100644
--- a/io/channel-socket.c
+++ b/io/channel-socket.c
@@ -442,7 +442,7 @@ static void qio_channel_socket_finalize(Object *obj)
             }
         }
 #ifdef WIN32
-        qemu_socket_select(ioc->fd, NULL, 0, NULL);
+        qemu_socket_unselect(ioc->fd, NULL);
 #endif
         closesocket(ioc->fd);
         ioc->fd = -1;
@@ -846,7 +846,7 @@ qio_channel_socket_close(QIOChannel *ioc,
 
     if (sioc->fd != -1) {
 #ifdef WIN32
-        qemu_socket_select(sioc->fd, NULL, 0, NULL);
+        qemu_socket_unselect(sioc->fd, NULL);
 #endif
         if (qio_channel_has_feature(ioc, QIO_CHANNEL_FEATURE_LISTEN)) {
             socket_listen_cleanup(sioc->fd, errp);
diff --git a/util/oslib-win32.c b/util/oslib-win32.c
index df752fc762..dbd32acc98 100644
--- a/util/oslib-win32.c
+++ b/util/oslib-win32.c
@@ -180,7 +180,7 @@ static int socket_error(void)
 void qemu_socket_set_block(int fd)
 {
     unsigned long opt = 0;
-    qemu_socket_select(fd, NULL, 0, NULL);
+    qemu_socket_unselect(fd, NULL);
     ioctlsocket(fd, FIONBIO, &opt);
 }
 
@@ -298,6 +298,11 @@ bool qemu_socket_select(SOCKET s, WSAEVENT hEventObject,
     return true;
 }
 
+bool qemu_socket_unselect(SOCKET s, Error **errp)
+{
+    return qemu_socket_select(s, NULL, 0, errp);
+}
+
 #undef connect
 int qemu_connect_wrap(int sockfd, const struct sockaddr *addr,
                       socklen_t addrlen)
-- 
2.39.2



^ permalink raw reply related	[flat|nested] 35+ messages in thread

* [PULL v2 08/25] aio: make aio_set_fd_poll() static to aio-posix.c
  2023-03-13 11:46 [PULL v2 00/25] Win socket patches marcandre.lureau
                   ` (6 preceding siblings ...)
  2023-03-13 11:46 ` [PULL v2 07/25] win32/socket: introduce qemu_socket_unselect() helper marcandre.lureau
@ 2023-03-13 11:46 ` marcandre.lureau
  2023-03-13 11:46 ` [PULL v2 09/25] aio/win32: aio_set_fd_handler() only supports SOCKET marcandre.lureau
                   ` (17 subsequent siblings)
  25 siblings, 0 replies; 35+ messages in thread
From: marcandre.lureau @ 2023-03-13 11:46 UTC (permalink / raw)
  To: qemu-devel
  Cc: qemu-block, Dr. David Alan Gilbert, Daniel P. Berrangé,
	Philippe Mathieu-Daudé,
	Eric Blake, Samuel Thibault, Hanna Reitz, Stefan Weil,
	Thomas Huth, Fam Zheng, Beraldo Leal, Paolo Bonzini, Jason Wang,
	Michael Roth, Stefan Berger, qemu-arm, Joel Stanley,
	Alex Bennée, Peter Maydell, Stefan Hajnoczi,
	Markus Armbruster, Marc-André Lureau, Kevin Wolf,
	Laurent Vivier, Wainer dos Santos Moschetta

From: Marc-André Lureau <marcandre.lureau@redhat.com>

Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Message-Id: <20230221124802.4103554-9-marcandre.lureau@redhat.com>
---
 include/block/aio.h | 8 --------
 util/aio-posix.c    | 6 +++---
 util/aio-win32.c    | 7 -------
 3 files changed, 3 insertions(+), 18 deletions(-)

diff --git a/include/block/aio.h b/include/block/aio.h
index 8fba6a3584..543717f294 100644
--- a/include/block/aio.h
+++ b/include/block/aio.h
@@ -482,14 +482,6 @@ void aio_set_fd_handler(AioContext *ctx,
                         IOHandler *io_poll_ready,
                         void *opaque);
 
-/* Set polling begin/end callbacks for a file descriptor that has already been
- * registered with aio_set_fd_handler.  Do nothing if the file descriptor is
- * not registered.
- */
-void aio_set_fd_poll(AioContext *ctx, int fd,
-                     IOHandler *io_poll_begin,
-                     IOHandler *io_poll_end);
-
 /* Register an event notifier and associated callbacks.  Behaves very similarly
  * to event_notifier_set_handler.  Unlike event_notifier_set_handler, these callbacks
  * will be invoked when using aio_poll().
diff --git a/util/aio-posix.c b/util/aio-posix.c
index 6cc6256d53..a8be940f76 100644
--- a/util/aio-posix.c
+++ b/util/aio-posix.c
@@ -180,9 +180,9 @@ void aio_set_fd_handler(AioContext *ctx,
     }
 }
 
-void aio_set_fd_poll(AioContext *ctx, int fd,
-                     IOHandler *io_poll_begin,
-                     IOHandler *io_poll_end)
+static void aio_set_fd_poll(AioContext *ctx, int fd,
+                            IOHandler *io_poll_begin,
+                            IOHandler *io_poll_end)
 {
     AioHandler *node = find_aio_handler(ctx, fd);
 
diff --git a/util/aio-win32.c b/util/aio-win32.c
index be5136e486..74d63fa21e 100644
--- a/util/aio-win32.c
+++ b/util/aio-win32.c
@@ -125,13 +125,6 @@ void aio_set_fd_handler(AioContext *ctx,
     aio_notify(ctx);
 }
 
-void aio_set_fd_poll(AioContext *ctx, int fd,
-                     IOHandler *io_poll_begin,
-                     IOHandler *io_poll_end)
-{
-    /* Not implemented */
-}
-
 void aio_set_event_notifier(AioContext *ctx,
                             EventNotifier *e,
                             bool is_external,
-- 
2.39.2



^ permalink raw reply related	[flat|nested] 35+ messages in thread

* [PULL v2 09/25] aio/win32: aio_set_fd_handler() only supports SOCKET
  2023-03-13 11:46 [PULL v2 00/25] Win socket patches marcandre.lureau
                   ` (7 preceding siblings ...)
  2023-03-13 11:46 ` [PULL v2 08/25] aio: make aio_set_fd_poll() static to aio-posix.c marcandre.lureau
@ 2023-03-13 11:46 ` marcandre.lureau
  2023-03-13 11:46 ` [PULL v2 10/25] main-loop: remove qemu_fd_register(), win32/slirp/socket specific marcandre.lureau
                   ` (16 subsequent siblings)
  25 siblings, 0 replies; 35+ messages in thread
From: marcandre.lureau @ 2023-03-13 11:46 UTC (permalink / raw)
  To: qemu-devel
  Cc: qemu-block, Dr. David Alan Gilbert, Daniel P. Berrangé,
	Philippe Mathieu-Daudé,
	Eric Blake, Samuel Thibault, Hanna Reitz, Stefan Weil,
	Thomas Huth, Fam Zheng, Beraldo Leal, Paolo Bonzini, Jason Wang,
	Michael Roth, Stefan Berger, qemu-arm, Joel Stanley,
	Alex Bennée, Peter Maydell, Stefan Hajnoczi,
	Markus Armbruster, Marc-André Lureau, Kevin Wolf,
	Laurent Vivier, Wainer dos Santos Moschetta

From: Marc-André Lureau <marcandre.lureau@redhat.com>

Let's check if the argument is actually a SOCKET, else report an error
and return.

Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Message-Id: <20230221124802.4103554-10-marcandre.lureau@redhat.com>
---
 util/aio-win32.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)

diff --git a/util/aio-win32.c b/util/aio-win32.c
index 74d63fa21e..08e8f5615d 100644
--- a/util/aio-win32.c
+++ b/util/aio-win32.c
@@ -22,6 +22,7 @@
 #include "qemu/sockets.h"
 #include "qapi/error.h"
 #include "qemu/rcu_queue.h"
+#include "qemu/error-report.h"
 
 struct AioHandler {
     EventNotifier *e;
@@ -70,10 +71,14 @@ void aio_set_fd_handler(AioContext *ctx,
                         IOHandler *io_poll_ready,
                         void *opaque)
 {
-    /* fd is a SOCKET in our case */
     AioHandler *old_node;
     AioHandler *node = NULL;
 
+    if (!fd_is_socket(fd)) {
+        error_report("fd=%d is not a socket, AIO implementation is missing", fd);
+        return;
+    }
+
     qemu_lockcnt_lock(&ctx->list_lock);
     QLIST_FOREACH(old_node, &ctx->aio_handlers, node) {
         if (old_node->pfd.fd == fd && !old_node->deleted) {
-- 
2.39.2



^ permalink raw reply related	[flat|nested] 35+ messages in thread

* [PULL v2 10/25] main-loop: remove qemu_fd_register(), win32/slirp/socket specific
  2023-03-13 11:46 [PULL v2 00/25] Win socket patches marcandre.lureau
                   ` (8 preceding siblings ...)
  2023-03-13 11:46 ` [PULL v2 09/25] aio/win32: aio_set_fd_handler() only supports SOCKET marcandre.lureau
@ 2023-03-13 11:46 ` marcandre.lureau
  2023-03-13 11:46 ` [PULL v2 11/25] slirp: unregister the win32 SOCKET marcandre.lureau
                   ` (15 subsequent siblings)
  25 siblings, 0 replies; 35+ messages in thread
From: marcandre.lureau @ 2023-03-13 11:46 UTC (permalink / raw)
  To: qemu-devel
  Cc: qemu-block, Dr. David Alan Gilbert, Daniel P. Berrangé,
	Philippe Mathieu-Daudé,
	Eric Blake, Samuel Thibault, Hanna Reitz, Stefan Weil,
	Thomas Huth, Fam Zheng, Beraldo Leal, Paolo Bonzini, Jason Wang,
	Michael Roth, Stefan Berger, qemu-arm, Joel Stanley,
	Alex Bennée, Peter Maydell, Stefan Hajnoczi,
	Markus Armbruster, Marc-André Lureau, Kevin Wolf,
	Laurent Vivier, Wainer dos Santos Moschetta

From: Marc-André Lureau <marcandre.lureau@redhat.com>

Open-code the socket registration where it's needed, to avoid
artificially used or unclear generic interface.

Furthermore, the following patches are going to make socket handling use
FD-only inside QEMU, but we need to handle win32 SOCKET from libslirp.

Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Message-Id: <20230221124802.4103554-12-marcandre.lureau@redhat.com>
---
 include/qemu/main-loop.h |  2 --
 net/slirp.c              |  8 +++++++-
 util/main-loop.c         | 11 -----------
 3 files changed, 7 insertions(+), 14 deletions(-)

diff --git a/include/qemu/main-loop.h b/include/qemu/main-loop.h
index c25f390696..b3e54e00bc 100644
--- a/include/qemu/main-loop.h
+++ b/include/qemu/main-loop.h
@@ -387,8 +387,6 @@ void qemu_cond_timedwait_iothread(QemuCond *cond, int ms);
 
 /* internal interfaces */
 
-void qemu_fd_register(int fd);
-
 #define qemu_bh_new(cb, opaque) \
     qemu_bh_new_full((cb), (opaque), (stringify(cb)))
 QEMUBH *qemu_bh_new_full(QEMUBHFunc *cb, void *opaque, const char *name);
diff --git a/net/slirp.c b/net/slirp.c
index 2ee3f1a0d7..0730a935ba 100644
--- a/net/slirp.c
+++ b/net/slirp.c
@@ -248,7 +248,13 @@ static void net_slirp_timer_mod(void *timer, int64_t expire_timer,
 
 static void net_slirp_register_poll_fd(int fd, void *opaque)
 {
-    qemu_fd_register(fd);
+#ifdef WIN32
+    AioContext *ctxt = qemu_get_aio_context();
+
+    qemu_socket_select(fd, event_notifier_get_handle(&ctxt->notifier),
+                       FD_READ | FD_ACCEPT | FD_CLOSE |
+                       FD_CONNECT | FD_WRITE | FD_OOB, NULL);
+#endif
 }
 
 static void net_slirp_unregister_poll_fd(int fd, void *opaque)
diff --git a/util/main-loop.c b/util/main-loop.c
index 16e837fb12..e180c85145 100644
--- a/util/main-loop.c
+++ b/util/main-loop.c
@@ -252,10 +252,6 @@ static int max_priority;
 static int glib_pollfds_idx;
 static int glib_n_poll_fds;
 
-void qemu_fd_register(int fd)
-{
-}
-
 static void glib_pollfds_fill(int64_t *cur_timeout)
 {
     GMainContext *context = g_main_context_default();
@@ -414,13 +410,6 @@ void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
     }
 }
 
-void qemu_fd_register(int fd)
-{
-    qemu_socket_select(fd, event_notifier_get_handle(&qemu_aio_context->notifier),
-                       FD_READ | FD_ACCEPT | FD_CLOSE |
-                       FD_CONNECT | FD_WRITE | FD_OOB, NULL);
-}
-
 static int pollfds_fill(GArray *pollfds, fd_set *rfds, fd_set *wfds,
                         fd_set *xfds)
 {
-- 
2.39.2



^ permalink raw reply related	[flat|nested] 35+ messages in thread

* [PULL v2 11/25] slirp: unregister the win32 SOCKET
  2023-03-13 11:46 [PULL v2 00/25] Win socket patches marcandre.lureau
                   ` (9 preceding siblings ...)
  2023-03-13 11:46 ` [PULL v2 10/25] main-loop: remove qemu_fd_register(), win32/slirp/socket specific marcandre.lureau
@ 2023-03-13 11:46 ` marcandre.lureau
  2023-03-13 11:46 ` [PULL v2 12/25] slirp: open-code qemu_socket_(un)select() marcandre.lureau
                   ` (14 subsequent siblings)
  25 siblings, 0 replies; 35+ messages in thread
From: marcandre.lureau @ 2023-03-13 11:46 UTC (permalink / raw)
  To: qemu-devel
  Cc: qemu-block, Dr. David Alan Gilbert, Daniel P. Berrangé,
	Philippe Mathieu-Daudé,
	Eric Blake, Samuel Thibault, Hanna Reitz, Stefan Weil,
	Thomas Huth, Fam Zheng, Beraldo Leal, Paolo Bonzini, Jason Wang,
	Michael Roth, Stefan Berger, qemu-arm, Joel Stanley,
	Alex Bennée, Peter Maydell, Stefan Hajnoczi,
	Markus Armbruster, Marc-André Lureau, Kevin Wolf,
	Laurent Vivier, Wainer dos Santos Moschetta

From: Marc-André Lureau <marcandre.lureau@redhat.com>

Presumably, this is what should happen when the SOCKET is to be removed.
(it probably worked until now because closesocket() does it implicitly,
but we never now how the slirp library could use the SOCKET later)

Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Message-Id: <20230221124802.4103554-13-marcandre.lureau@redhat.com>
---
 net/slirp.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/net/slirp.c b/net/slirp.c
index 0730a935ba..a7c35778a6 100644
--- a/net/slirp.c
+++ b/net/slirp.c
@@ -259,7 +259,9 @@ static void net_slirp_register_poll_fd(int fd, void *opaque)
 
 static void net_slirp_unregister_poll_fd(int fd, void *opaque)
 {
-    /* no qemu_fd_unregister */
+#ifdef WIN32
+    qemu_socket_unselect(fd, NULL);
+#endif
 }
 
 static void net_slirp_notify(void *opaque)
-- 
2.39.2



^ permalink raw reply related	[flat|nested] 35+ messages in thread

* [PULL v2 12/25] slirp: open-code qemu_socket_(un)select()
  2023-03-13 11:46 [PULL v2 00/25] Win socket patches marcandre.lureau
                   ` (10 preceding siblings ...)
  2023-03-13 11:46 ` [PULL v2 11/25] slirp: unregister the win32 SOCKET marcandre.lureau
@ 2023-03-13 11:46 ` marcandre.lureau
  2023-03-13 11:46 ` [PULL v2 13/25] win32: avoid mixing SOCKET and file descriptor space marcandre.lureau
                   ` (13 subsequent siblings)
  25 siblings, 0 replies; 35+ messages in thread
From: marcandre.lureau @ 2023-03-13 11:46 UTC (permalink / raw)
  To: qemu-devel
  Cc: qemu-block, Dr. David Alan Gilbert, Daniel P. Berrangé,
	Philippe Mathieu-Daudé,
	Eric Blake, Samuel Thibault, Hanna Reitz, Stefan Weil,
	Thomas Huth, Fam Zheng, Beraldo Leal, Paolo Bonzini, Jason Wang,
	Michael Roth, Stefan Berger, qemu-arm, Joel Stanley,
	Alex Bennée, Peter Maydell, Stefan Hajnoczi,
	Markus Armbruster, Marc-André Lureau, Kevin Wolf,
	Laurent Vivier, Wainer dos Santos Moschetta

From: Marc-André Lureau <marcandre.lureau@redhat.com>

We are about to make the QEMU socket API use file-descriptor space only,
but libslirp gives us SOCKET as fd, still.

Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Message-Id: <20230221124802.4103554-14-marcandre.lureau@redhat.com>
---
 net/slirp.c | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)

diff --git a/net/slirp.c b/net/slirp.c
index a7c35778a6..c33b3e02e7 100644
--- a/net/slirp.c
+++ b/net/slirp.c
@@ -251,16 +251,20 @@ static void net_slirp_register_poll_fd(int fd, void *opaque)
 #ifdef WIN32
     AioContext *ctxt = qemu_get_aio_context();
 
-    qemu_socket_select(fd, event_notifier_get_handle(&ctxt->notifier),
+    if (WSAEventSelect(fd, event_notifier_get_handle(&ctxt->notifier),
                        FD_READ | FD_ACCEPT | FD_CLOSE |
-                       FD_CONNECT | FD_WRITE | FD_OOB, NULL);
+                       FD_CONNECT | FD_WRITE | FD_OOB) != 0) {
+        error_setg_win32(&error_warn, WSAGetLastError(), "failed to WSAEventSelect()");
+    }
 #endif
 }
 
 static void net_slirp_unregister_poll_fd(int fd, void *opaque)
 {
 #ifdef WIN32
-    qemu_socket_unselect(fd, NULL);
+    if (WSAEventSelect(fd, NULL, 0) != 0) {
+        error_setg_win32(&error_warn, WSAGetLastError(), "failed to WSAEventSelect()");
+    }
 #endif
 }
 
-- 
2.39.2



^ permalink raw reply related	[flat|nested] 35+ messages in thread

* [PULL v2 13/25] win32: avoid mixing SOCKET and file descriptor space
  2023-03-13 11:46 [PULL v2 00/25] Win socket patches marcandre.lureau
                   ` (11 preceding siblings ...)
  2023-03-13 11:46 ` [PULL v2 12/25] slirp: open-code qemu_socket_(un)select() marcandre.lureau
@ 2023-03-13 11:46 ` marcandre.lureau
  2023-03-13 11:46 ` [PULL v2 14/25] os-posix: remove useless ioctlsocket() define marcandre.lureau
                   ` (12 subsequent siblings)
  25 siblings, 0 replies; 35+ messages in thread
From: marcandre.lureau @ 2023-03-13 11:46 UTC (permalink / raw)
  To: qemu-devel
  Cc: qemu-block, Dr. David Alan Gilbert, Daniel P. Berrangé,
	Philippe Mathieu-Daudé,
	Eric Blake, Samuel Thibault, Hanna Reitz, Stefan Weil,
	Thomas Huth, Fam Zheng, Beraldo Leal, Paolo Bonzini, Jason Wang,
	Michael Roth, Stefan Berger, qemu-arm, Joel Stanley,
	Alex Bennée, Peter Maydell, Stefan Hajnoczi,
	Markus Armbruster, Marc-André Lureau, Kevin Wolf,
	Laurent Vivier, Wainer dos Santos Moschetta

From: Marc-André Lureau <marcandre.lureau@redhat.com>

Until now, a win32 SOCKET handle is often cast to an int file
descriptor, as this is what other OS use for sockets. When necessary,
QEMU eventually queries whether it's a socket with the help of
fd_is_socket(). However, there is no guarantee of conflict between the
fd and SOCKET space. Such conflict would have surprising consequences,
we shouldn't mix them.

Also, it is often forgotten that SOCKET must be closed with
closesocket(), and not close().

Instead, let's make the win32 socket wrapper functions return and take a
file descriptor, and let util/ wrappers do the fd/SOCKET conversion as
necessary. A bit of adaptation is necessary in io/ as well.

Unfortunately, we can't drop closesocket() usage, despite
_open_osfhandle() documentation claiming transfer of ownership, testing
shows bad behaviour if you forget to call closesocket().

Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Message-Id: <20230221124802.4103554-15-marcandre.lureau@redhat.com>
---
 include/sysemu/os-win32.h |   4 +-
 io/channel-watch.c        |   6 +-
 util/aio-win32.c          |   9 +-
 util/oslib-win32.c        | 219 ++++++++++++++++++++++++++++++++------
 4 files changed, 197 insertions(+), 41 deletions(-)

diff --git a/include/sysemu/os-win32.h b/include/sysemu/os-win32.h
index 504a8966c3..cb1dcce618 100644
--- a/include/sysemu/os-win32.h
+++ b/include/sysemu/os-win32.h
@@ -166,10 +166,10 @@ static inline void qemu_funlockfile(FILE *f)
 }
 
 /* Helper for WSAEventSelect, to report errors */
-bool qemu_socket_select(SOCKET s, WSAEVENT hEventObject,
+bool qemu_socket_select(int sockfd, WSAEVENT hEventObject,
                         long lNetworkEvents, Error **errp);
 
-bool qemu_socket_unselect(SOCKET s, Error **errp);
+bool qemu_socket_unselect(int sockfd, Error **errp);
 
 /* We wrap all the sockets functions so that we can
  * set errno based on WSAGetLastError()
diff --git a/io/channel-watch.c b/io/channel-watch.c
index 6ac41009fa..64b486e378 100644
--- a/io/channel-watch.c
+++ b/io/channel-watch.c
@@ -275,13 +275,13 @@ GSource *qio_channel_create_fd_watch(QIOChannel *ioc,
 
 #ifdef CONFIG_WIN32
 GSource *qio_channel_create_socket_watch(QIOChannel *ioc,
-                                         int socket,
+                                         int sockfd,
                                          GIOCondition condition)
 {
     GSource *source;
     QIOChannelSocketSource *ssource;
 
-    qemu_socket_select(socket, ioc->event,
+    qemu_socket_select(sockfd, ioc->event,
                        FD_READ | FD_ACCEPT | FD_CLOSE |
                        FD_CONNECT | FD_WRITE | FD_OOB, NULL);
 
@@ -293,7 +293,7 @@ GSource *qio_channel_create_socket_watch(QIOChannel *ioc,
     object_ref(OBJECT(ioc));
 
     ssource->condition = condition;
-    ssource->socket = socket;
+    ssource->socket = _get_osfhandle(sockfd);
     ssource->revents = 0;
 
     ssource->fd.fd = (gintptr)ioc->event;
diff --git a/util/aio-win32.c b/util/aio-win32.c
index 08e8f5615d..6bded009a4 100644
--- a/util/aio-win32.c
+++ b/util/aio-win32.c
@@ -73,15 +73,18 @@ void aio_set_fd_handler(AioContext *ctx,
 {
     AioHandler *old_node;
     AioHandler *node = NULL;
+    SOCKET s;
 
     if (!fd_is_socket(fd)) {
         error_report("fd=%d is not a socket, AIO implementation is missing", fd);
         return;
     }
 
+    s = _get_osfhandle(fd);
+
     qemu_lockcnt_lock(&ctx->list_lock);
     QLIST_FOREACH(old_node, &ctx->aio_handlers, node) {
-        if (old_node->pfd.fd == fd && !old_node->deleted) {
+        if (old_node->pfd.fd == s && !old_node->deleted) {
             break;
         }
     }
@@ -92,7 +95,7 @@ void aio_set_fd_handler(AioContext *ctx,
 
         /* Alloc and insert if it's not already there */
         node = g_new0(AioHandler, 1);
-        node->pfd.fd = fd;
+        node->pfd.fd = s;
 
         node->pfd.events = 0;
         if (node->io_read) {
@@ -120,7 +123,7 @@ void aio_set_fd_handler(AioContext *ctx,
 
         QLIST_INSERT_HEAD_RCU(&ctx->aio_handlers, node, node);
         event = event_notifier_get_handle(&ctx->notifier);
-        qemu_socket_select(node->pfd.fd, event, bitmask, NULL);
+        qemu_socket_select(fd, event, bitmask, NULL);
     }
     if (old_node) {
         aio_remove_fd_handler(ctx, old_node);
diff --git a/util/oslib-win32.c b/util/oslib-win32.c
index dbd32acc98..7836fb0be3 100644
--- a/util/oslib-win32.c
+++ b/util/oslib-win32.c
@@ -283,13 +283,20 @@ char *qemu_get_pid_name(pid_t pid)
 }
 
 
-bool qemu_socket_select(SOCKET s, WSAEVENT hEventObject,
+bool qemu_socket_select(int sockfd, WSAEVENT hEventObject,
                         long lNetworkEvents, Error **errp)
 {
+    SOCKET s = _get_osfhandle(sockfd);
+
     if (errp == NULL) {
         errp = &error_warn;
     }
 
+    if (s == INVALID_SOCKET) {
+        error_setg(errp, "invalid socket fd=%d", sockfd);
+        return false;
+    }
+
     if (WSAEventSelect(s, hEventObject, lNetworkEvents) != 0) {
         error_setg_win32(errp, WSAGetLastError(), "failed to WSAEventSelect()");
         return false;
@@ -298,9 +305,9 @@ bool qemu_socket_select(SOCKET s, WSAEVENT hEventObject,
     return true;
 }
 
-bool qemu_socket_unselect(SOCKET s, Error **errp)
+bool qemu_socket_unselect(int sockfd, Error **errp)
 {
-    return qemu_socket_select(s, NULL, 0, errp);
+    return qemu_socket_select(sockfd, NULL, 0, errp);
 }
 
 #undef connect
@@ -308,7 +315,13 @@ int qemu_connect_wrap(int sockfd, const struct sockaddr *addr,
                       socklen_t addrlen)
 {
     int ret;
-    ret = connect(sockfd, addr, addrlen);
+    SOCKET s = _get_osfhandle(sockfd);
+
+    if (s == INVALID_SOCKET) {
+        return -1;
+    }
+
+    ret = connect(s, addr, addrlen);
     if (ret < 0) {
         if (WSAGetLastError() == WSAEWOULDBLOCK) {
             errno = EINPROGRESS;
@@ -324,7 +337,13 @@ int qemu_connect_wrap(int sockfd, const struct sockaddr *addr,
 int qemu_listen_wrap(int sockfd, int backlog)
 {
     int ret;
-    ret = listen(sockfd, backlog);
+    SOCKET s = _get_osfhandle(sockfd);
+
+    if (s == INVALID_SOCKET) {
+        return -1;
+    }
+
+    ret = listen(s, backlog);
     if (ret < 0) {
         errno = socket_error();
     }
@@ -337,7 +356,13 @@ int qemu_bind_wrap(int sockfd, const struct sockaddr *addr,
                    socklen_t addrlen)
 {
     int ret;
-    ret = bind(sockfd, addr, addrlen);
+    SOCKET s = _get_osfhandle(sockfd);
+
+    if (s == INVALID_SOCKET) {
+        return -1;
+    }
+
+    ret = bind(s, addr, addrlen);
     if (ret < 0) {
         errno = socket_error();
     }
@@ -345,28 +370,108 @@ int qemu_bind_wrap(int sockfd, const struct sockaddr *addr,
 }
 
 
-#undef socket
-int qemu_socket_wrap(int domain, int type, int protocol)
+#undef closesocket
+int qemu_closesocket_wrap(int fd)
 {
     int ret;
-    ret = socket(domain, type, protocol);
+    DWORD flags = 0;
+    SOCKET s = _get_osfhandle(fd);
+
+    if (s == INVALID_SOCKET) {
+        return -1;
+    }
+
+    /*
+     * If we were to just call _close on the descriptor, it would close the
+     * HANDLE, but it wouldn't free any of the resources associated to the
+     * SOCKET, and we can't call _close after calling closesocket, because
+     * closesocket has already closed the HANDLE, and _close would attempt to
+     * close the HANDLE again, resulting in a double free. We can however
+     * protect the HANDLE from actually being closed long enough to close the
+     * file descriptor, then close the socket itself.
+     */
+    if (!GetHandleInformation((HANDLE)s, &flags)) {
+        errno = EACCES;
+        return -1;
+    }
+
+    if (!SetHandleInformation((HANDLE)s, HANDLE_FLAG_PROTECT_FROM_CLOSE, HANDLE_FLAG_PROTECT_FROM_CLOSE)) {
+        errno = EACCES;
+        return -1;
+    }
+
+    ret = close(fd);
+
+    if (!SetHandleInformation((HANDLE)s, flags, flags)) {
+        errno = EACCES;
+        return -1;
+    }
+
+    /*
+     * close() returns EBADF since we PROTECT_FROM_CLOSE the underlying handle,
+     * but the FD is actually freed
+     */
+    if (ret < 0 && errno != EBADF) {
+        return ret;
+    }
+
+    ret = closesocket(s);
     if (ret < 0) {
         errno = socket_error();
     }
+
     return ret;
 }
 
 
+#undef socket
+int qemu_socket_wrap(int domain, int type, int protocol)
+{
+    SOCKET s;
+    int fd;
+
+    s = socket(domain, type, protocol);
+    if (s == -1) {
+        errno = socket_error();
+        return -1;
+    }
+
+    fd = _open_osfhandle(s, _O_BINARY);
+    if (fd < 0) {
+        closesocket(s);
+        /* _open_osfhandle may not set errno, and closesocket() may override it */
+        errno = ENOMEM;
+    }
+
+    return fd;
+}
+
+
 #undef accept
 int qemu_accept_wrap(int sockfd, struct sockaddr *addr,
                      socklen_t *addrlen)
 {
-    int ret;
-    ret = accept(sockfd, addr, addrlen);
-    if (ret < 0) {
+    int fd;
+    SOCKET s = _get_osfhandle(sockfd);
+
+    if (s == INVALID_SOCKET) {
+        return -1;
+    }
+
+    s = accept(s, addr, addrlen);
+    if (s == -1) {
         errno = socket_error();
+        return -1;
     }
-    return ret;
+
+    fd = _open_osfhandle(s, _O_BINARY);
+    if (fd < 0) {
+        closesocket(s);
+        /* _open_osfhandle may not set errno, and closesocket() may override it */
+        errno = ENOMEM;
+    }
+
+    return fd;
 }
 
 
@@ -374,7 +479,13 @@ int qemu_accept_wrap(int sockfd, struct sockaddr *addr,
 int qemu_shutdown_wrap(int sockfd, int how)
 {
     int ret;
-    ret = shutdown(sockfd, how);
+    SOCKET s = _get_osfhandle(sockfd);
+
+    if (s == INVALID_SOCKET) {
+        return -1;
+    }
+
+    ret = shutdown(s, how);
     if (ret < 0) {
         errno = socket_error();
     }
@@ -386,19 +497,13 @@ int qemu_shutdown_wrap(int sockfd, int how)
 int qemu_ioctlsocket_wrap(int fd, int req, void *val)
 {
     int ret;
-    ret = ioctlsocket(fd, req, val);
-    if (ret < 0) {
-        errno = socket_error();
-    }
-    return ret;
-}
+    SOCKET s = _get_osfhandle(fd);
 
+    if (s == INVALID_SOCKET) {
+        return -1;
+    }
 
-#undef closesocket
-int qemu_closesocket_wrap(int fd)
-{
-    int ret;
-    ret = closesocket(fd);
+    ret = ioctlsocket(s, req, val);
     if (ret < 0) {
         errno = socket_error();
     }
@@ -411,7 +516,13 @@ int qemu_getsockopt_wrap(int sockfd, int level, int optname,
                          void *optval, socklen_t *optlen)
 {
     int ret;
-    ret = getsockopt(sockfd, level, optname, optval, optlen);
+    SOCKET s = _get_osfhandle(sockfd);
+
+    if (s == INVALID_SOCKET) {
+        return -1;
+    }
+
+    ret = getsockopt(s, level, optname, optval, optlen);
     if (ret < 0) {
         errno = socket_error();
     }
@@ -424,7 +535,13 @@ int qemu_setsockopt_wrap(int sockfd, int level, int optname,
                          const void *optval, socklen_t optlen)
 {
     int ret;
-    ret = setsockopt(sockfd, level, optname, optval, optlen);
+    SOCKET s = _get_osfhandle(sockfd);
+
+    if (s == INVALID_SOCKET) {
+        return -1;
+    }
+
+    ret = setsockopt(s, level, optname, optval, optlen);
     if (ret < 0) {
         errno = socket_error();
     }
@@ -437,7 +554,13 @@ int qemu_getpeername_wrap(int sockfd, struct sockaddr *addr,
                           socklen_t *addrlen)
 {
     int ret;
-    ret = getpeername(sockfd, addr, addrlen);
+    SOCKET s = _get_osfhandle(sockfd);
+
+    if (s == INVALID_SOCKET) {
+        return -1;
+    }
+
+    ret = getpeername(s, addr, addrlen);
     if (ret < 0) {
         errno = socket_error();
     }
@@ -450,7 +573,13 @@ int qemu_getsockname_wrap(int sockfd, struct sockaddr *addr,
                           socklen_t *addrlen)
 {
     int ret;
-    ret = getsockname(sockfd, addr, addrlen);
+    SOCKET s = _get_osfhandle(sockfd);
+
+    if (s == INVALID_SOCKET) {
+        return -1;
+    }
+
+    ret = getsockname(s, addr, addrlen);
     if (ret < 0) {
         errno = socket_error();
     }
@@ -462,7 +591,13 @@ int qemu_getsockname_wrap(int sockfd, struct sockaddr *addr,
 ssize_t qemu_send_wrap(int sockfd, const void *buf, size_t len, int flags)
 {
     int ret;
-    ret = send(sockfd, buf, len, flags);
+    SOCKET s = _get_osfhandle(sockfd);
+
+    if (s == INVALID_SOCKET) {
+        return -1;
+    }
+
+    ret = send(s, buf, len, flags);
     if (ret < 0) {
         errno = socket_error();
     }
@@ -475,7 +610,13 @@ ssize_t qemu_sendto_wrap(int sockfd, const void *buf, size_t len, int flags,
                          const struct sockaddr *addr, socklen_t addrlen)
 {
     int ret;
-    ret = sendto(sockfd, buf, len, flags, addr, addrlen);
+    SOCKET s = _get_osfhandle(sockfd);
+
+    if (s == INVALID_SOCKET) {
+        return -1;
+    }
+
+    ret = sendto(s, buf, len, flags, addr, addrlen);
     if (ret < 0) {
         errno = socket_error();
     }
@@ -487,7 +628,13 @@ ssize_t qemu_sendto_wrap(int sockfd, const void *buf, size_t len, int flags,
 ssize_t qemu_recv_wrap(int sockfd, void *buf, size_t len, int flags)
 {
     int ret;
-    ret = recv(sockfd, buf, len, flags);
+    SOCKET s = _get_osfhandle(sockfd);
+
+    if (s == INVALID_SOCKET) {
+        return -1;
+    }
+
+    ret = recv(s, buf, len, flags);
     if (ret < 0) {
         errno = socket_error();
     }
@@ -500,7 +647,13 @@ ssize_t qemu_recvfrom_wrap(int sockfd, void *buf, size_t len, int flags,
                            struct sockaddr *addr, socklen_t *addrlen)
 {
     int ret;
-    ret = recvfrom(sockfd, buf, len, flags, addr, addrlen);
+    SOCKET s = _get_osfhandle(sockfd);
+
+    if (s == INVALID_SOCKET) {
+        return -1;
+    }
+
+    ret = recvfrom(s, buf, len, flags, addr, addrlen);
     if (ret < 0) {
         errno = socket_error();
     }
-- 
2.39.2



^ permalink raw reply related	[flat|nested] 35+ messages in thread

* [PULL v2 14/25] os-posix: remove useless ioctlsocket() define
  2023-03-13 11:46 [PULL v2 00/25] Win socket patches marcandre.lureau
                   ` (12 preceding siblings ...)
  2023-03-13 11:46 ` [PULL v2 13/25] win32: avoid mixing SOCKET and file descriptor space marcandre.lureau
@ 2023-03-13 11:46 ` marcandre.lureau
  2023-03-13 11:46 ` [PULL v2 15/25] win32: replace closesocket() with close() wrapper marcandre.lureau
                   ` (11 subsequent siblings)
  25 siblings, 0 replies; 35+ messages in thread
From: marcandre.lureau @ 2023-03-13 11:46 UTC (permalink / raw)
  To: qemu-devel
  Cc: qemu-block, Dr. David Alan Gilbert, Daniel P. Berrangé,
	Philippe Mathieu-Daudé,
	Eric Blake, Samuel Thibault, Hanna Reitz, Stefan Weil,
	Thomas Huth, Fam Zheng, Beraldo Leal, Paolo Bonzini, Jason Wang,
	Michael Roth, Stefan Berger, qemu-arm, Joel Stanley,
	Alex Bennée, Peter Maydell, Stefan Hajnoczi,
	Markus Armbruster, Marc-André Lureau, Kevin Wolf,
	Laurent Vivier, Wainer dos Santos Moschetta

From: Marc-André Lureau <marcandre.lureau@redhat.com>

The API is specific to win32.

Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
Reviewed-by: Daniel P. Berrangé <berrange@redhat.com>
Message-Id: <20230221124802.4103554-16-marcandre.lureau@redhat.com>
---
 include/sysemu/os-posix.h | 1 -
 1 file changed, 1 deletion(-)

diff --git a/include/sysemu/os-posix.h b/include/sysemu/os-posix.h
index 58de7c994d..378213fc86 100644
--- a/include/sysemu/os-posix.h
+++ b/include/sysemu/os-posix.h
@@ -52,7 +52,6 @@ void os_setup_post(void);
 int os_mlock(void);
 
 #define closesocket(s) close(s)
-#define ioctlsocket(s, r, v) ioctl(s, r, v)
 
 int os_set_daemonize(bool d);
 bool is_daemonized(void);
-- 
2.39.2



^ permalink raw reply related	[flat|nested] 35+ messages in thread

* [PULL v2 15/25] win32: replace closesocket() with close() wrapper
  2023-03-13 11:46 [PULL v2 00/25] Win socket patches marcandre.lureau
                   ` (13 preceding siblings ...)
  2023-03-13 11:46 ` [PULL v2 14/25] os-posix: remove useless ioctlsocket() define marcandre.lureau
@ 2023-03-13 11:46 ` marcandre.lureau
  2023-03-13 11:46 ` [PULL v2 16/25] tests: fix path separator, use g_build_filename() marcandre.lureau
                   ` (10 subsequent siblings)
  25 siblings, 0 replies; 35+ messages in thread
From: marcandre.lureau @ 2023-03-13 11:46 UTC (permalink / raw)
  To: qemu-devel
  Cc: qemu-block, Dr. David Alan Gilbert, Daniel P. Berrangé,
	Philippe Mathieu-Daudé,
	Eric Blake, Samuel Thibault, Hanna Reitz, Stefan Weil,
	Thomas Huth, Fam Zheng, Beraldo Leal, Paolo Bonzini, Jason Wang,
	Michael Roth, Stefan Berger, qemu-arm, Joel Stanley,
	Alex Bennée, Peter Maydell, Stefan Hajnoczi,
	Markus Armbruster, Marc-André Lureau, Kevin Wolf,
	Laurent Vivier, Wainer dos Santos Moschetta

From: Marc-André Lureau <marcandre.lureau@redhat.com>

Use a close() wrapper instead, so that we don't need to worry about
closesocket() vs close() anymore, let's hope.

Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Message-Id: <20230221124802.4103554-17-marcandre.lureau@redhat.com>
---
 include/sysemu/os-posix.h   |  2 --
 include/sysemu/os-win32.h   |  8 +++---
 backends/tpm/tpm_emulator.c |  6 ++--
 crypto/afalg.c              |  6 ++--
 hw/hyperv/syndbg.c          |  4 +--
 io/channel-socket.c         | 10 +++----
 net/dgram.c                 | 14 +++++-----
 net/socket.c                | 22 +++++++--------
 tests/qtest/libqtest.c      |  8 +++---
 tests/qtest/microbit-test.c |  2 +-
 tests/qtest/netdev-socket.c | 10 +++----
 tests/unit/socket-helpers.c |  8 +++---
 util/oslib-win32.c          | 56 +++++++++++++++++++------------------
 util/qemu-sockets.c         | 22 +++++++--------
 14 files changed, 89 insertions(+), 89 deletions(-)

diff --git a/include/sysemu/os-posix.h b/include/sysemu/os-posix.h
index 378213fc86..1030d39904 100644
--- a/include/sysemu/os-posix.h
+++ b/include/sysemu/os-posix.h
@@ -51,8 +51,6 @@ void os_daemonize(void);
 void os_setup_post(void);
 int os_mlock(void);
 
-#define closesocket(s) close(s)
-
 int os_set_daemonize(bool d);
 bool is_daemonized(void);
 
diff --git a/include/sysemu/os-win32.h b/include/sysemu/os-win32.h
index cb1dcce618..e2849f88ab 100644
--- a/include/sysemu/os-win32.h
+++ b/include/sysemu/os-win32.h
@@ -175,6 +175,10 @@ bool qemu_socket_unselect(int sockfd, Error **errp);
  * set errno based on WSAGetLastError()
  */
 
+#undef close
+#define close qemu_close_wrap
+int qemu_close_wrap(int fd);
+
 #undef connect
 #define connect qemu_connect_wrap
 int qemu_connect_wrap(int sockfd, const struct sockaddr *addr,
@@ -206,10 +210,6 @@ int qemu_shutdown_wrap(int sockfd, int how);
 #define ioctlsocket qemu_ioctlsocket_wrap
 int qemu_ioctlsocket_wrap(int fd, int req, void *val);
 
-#undef closesocket
-#define closesocket qemu_closesocket_wrap
-int qemu_closesocket_wrap(int fd);
-
 #undef getsockopt
 #define getsockopt qemu_getsockopt_wrap
 int qemu_getsockopt_wrap(int sockfd, int level, int optname,
diff --git a/backends/tpm/tpm_emulator.c b/backends/tpm/tpm_emulator.c
index d18144b92e..402a2d6312 100644
--- a/backends/tpm/tpm_emulator.c
+++ b/backends/tpm/tpm_emulator.c
@@ -573,13 +573,13 @@ static int tpm_emulator_prepare_data_fd(TPMEmulator *tpm_emu)
         goto err_exit;
     }
 
-    closesocket(fds[1]);
+    close(fds[1]);
 
     return 0;
 
 err_exit:
-    closesocket(fds[0]);
-    closesocket(fds[1]);
+    close(fds[0]);
+    close(fds[1]);
     return -1;
 }
 
diff --git a/crypto/afalg.c b/crypto/afalg.c
index 10046bb0ae..348301e703 100644
--- a/crypto/afalg.c
+++ b/crypto/afalg.c
@@ -59,7 +59,7 @@ qcrypto_afalg_socket_bind(const char *type, const char *name,
 
     if (bind(sbind, (const struct sockaddr *)&salg, sizeof(salg)) != 0) {
         error_setg_errno(errp, errno, "Failed to bind socket");
-        closesocket(sbind);
+        close(sbind);
         return -1;
     }
 
@@ -105,11 +105,11 @@ void qcrypto_afalg_comm_free(QCryptoAFAlg *afalg)
     }
 
     if (afalg->tfmfd != -1) {
-        closesocket(afalg->tfmfd);
+        close(afalg->tfmfd);
     }
 
     if (afalg->opfd != -1) {
-        closesocket(afalg->opfd);
+        close(afalg->opfd);
     }
 
     g_free(afalg);
diff --git a/hw/hyperv/syndbg.c b/hw/hyperv/syndbg.c
index 94fe1b534b..065e12fb1e 100644
--- a/hw/hyperv/syndbg.c
+++ b/hw/hyperv/syndbg.c
@@ -340,7 +340,7 @@ static void hv_syndbg_realize(DeviceState *dev, Error **errp)
     syndbg->servaddr.sin_family = AF_INET;
     if (connect(syndbg->socket, (struct sockaddr *)&syndbg->servaddr,
                 sizeof(syndbg->servaddr)) < 0) {
-        closesocket(syndbg->socket);
+        close(syndbg->socket);
         error_setg(errp, "%s failed to connect to socket", TYPE_HV_SYNDBG);
         return;
     }
@@ -357,7 +357,7 @@ static void hv_syndbg_unrealize(DeviceState *dev)
 
     if (syndbg->socket > 0) {
         qemu_set_fd_handler(syndbg->socket, NULL, NULL, NULL);
-        closesocket(syndbg->socket);
+        close(syndbg->socket);
     }
 }
 
diff --git a/io/channel-socket.c b/io/channel-socket.c
index 03757c7a7e..b0ea7d48b3 100644
--- a/io/channel-socket.c
+++ b/io/channel-socket.c
@@ -159,7 +159,7 @@ int qio_channel_socket_connect_sync(QIOChannelSocket *ioc,
 
     trace_qio_channel_socket_connect_complete(ioc, fd);
     if (qio_channel_socket_set_fd(ioc, fd, errp) < 0) {
-        closesocket(fd);
+        close(fd);
         return -1;
     }
 
@@ -233,7 +233,7 @@ int qio_channel_socket_listen_sync(QIOChannelSocket *ioc,
 
     trace_qio_channel_socket_listen_complete(ioc, fd);
     if (qio_channel_socket_set_fd(ioc, fd, errp) < 0) {
-        closesocket(fd);
+        close(fd);
         return -1;
     }
     qio_channel_set_feature(QIO_CHANNEL(ioc), QIO_CHANNEL_FEATURE_LISTEN);
@@ -310,7 +310,7 @@ int qio_channel_socket_dgram_sync(QIOChannelSocket *ioc,
 
     trace_qio_channel_socket_dgram_complete(ioc, fd);
     if (qio_channel_socket_set_fd(ioc, fd, errp) < 0) {
-        closesocket(fd);
+        close(fd);
         return -1;
     }
 
@@ -444,7 +444,7 @@ static void qio_channel_socket_finalize(Object *obj)
 #ifdef WIN32
         qemu_socket_unselect(ioc->fd, NULL);
 #endif
-        closesocket(ioc->fd);
+        close(ioc->fd);
         ioc->fd = -1;
     }
 }
@@ -852,7 +852,7 @@ qio_channel_socket_close(QIOChannel *ioc,
             socket_listen_cleanup(sioc->fd, errp);
         }
 
-        if (closesocket(sioc->fd) < 0) {
+        if (close(sioc->fd) < 0) {
             sioc->fd = -1;
             error_setg_errno(&err, errno, "Unable to close socket");
             error_propagate(errp, err);
diff --git a/net/dgram.c b/net/dgram.c
index 9f7bf38376..48f653bceb 100644
--- a/net/dgram.c
+++ b/net/dgram.c
@@ -230,7 +230,7 @@ static int net_dgram_mcast_create(struct sockaddr_in *mcastaddr,
     return fd;
 fail:
     if (fd >= 0) {
-        closesocket(fd);
+        close(fd);
     }
     return -1;
 }
@@ -352,7 +352,7 @@ static int net_dgram_mcast_init(NetClientState *peer,
             if (convert_host_port(saddr, local->u.inet.host, local->u.inet.port,
                                   errp) < 0) {
                 g_free(saddr);
-                closesocket(fd);
+                close(fd);
                 return -1;
             }
 
@@ -360,14 +360,14 @@ static int net_dgram_mcast_init(NetClientState *peer,
             if (saddr->sin_addr.s_addr == 0) {
                 error_setg(errp, "can't setup multicast destination address");
                 g_free(saddr);
-                closesocket(fd);
+                close(fd);
                 return -1;
             }
             /* clone dgram socket */
             newfd = net_dgram_mcast_create(saddr, NULL, errp);
             if (newfd < 0) {
                 g_free(saddr);
-                closesocket(fd);
+                close(fd);
                 return -1;
             }
             /* clone newfd to fd, close newfd */
@@ -494,14 +494,14 @@ int net_init_dgram(const Netdev *netdev, const char *name,
         if (ret < 0) {
             error_setg_errno(errp, errno,
                              "can't set socket option SO_REUSEADDR");
-            closesocket(fd);
+            close(fd);
             return -1;
         }
         ret = bind(fd, (struct sockaddr *)&laddr_in, sizeof(laddr_in));
         if (ret < 0) {
             error_setg_errno(errp, errno, "can't bind ip=%s to socket",
                              inet_ntoa(laddr_in.sin_addr));
-            closesocket(fd);
+            close(fd);
             return -1;
         }
         qemu_socket_set_nonblock(fd);
@@ -548,7 +548,7 @@ int net_init_dgram(const Netdev *netdev, const char *name,
         if (ret < 0) {
             error_setg_errno(errp, errno, "can't bind unix=%s to socket",
                              laddr_un.sun_path);
-            closesocket(fd);
+            close(fd);
             return -1;
         }
         qemu_socket_set_nonblock(fd);
diff --git a/net/socket.c b/net/socket.c
index 2fc5696755..ba6e5b0b00 100644
--- a/net/socket.c
+++ b/net/socket.c
@@ -172,7 +172,7 @@ static void net_socket_send(void *opaque)
         if (s->listen_fd != -1) {
             qemu_set_fd_handler(s->listen_fd, net_socket_accept, NULL, s);
         }
-        closesocket(s->fd);
+        close(s->fd);
 
         s->fd = -1;
         net_socket_rs_init(&s->rs, net_socket_rs_finalize, false);
@@ -299,7 +299,7 @@ static int net_socket_mcast_create(struct sockaddr_in *mcastaddr,
     return fd;
 fail:
     if (fd >= 0)
-        closesocket(fd);
+        close(fd);
     return -1;
 }
 
@@ -314,7 +314,7 @@ static void net_socket_cleanup(NetClientState *nc)
     }
     if (s->listen_fd != -1) {
         qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
-        closesocket(s->listen_fd);
+        close(s->listen_fd);
         s->listen_fd = -1;
     }
 }
@@ -399,7 +399,7 @@ static NetSocketState *net_socket_fd_init_dgram(NetClientState *peer,
     return s;
 
 err:
-    closesocket(fd);
+    close(fd);
     return NULL;
 }
 
@@ -456,7 +456,7 @@ static NetSocketState *net_socket_fd_init(NetClientState *peer,
     if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
         (socklen_t *)&optlen)< 0) {
         error_setg(errp, "can't get socket option SO_TYPE");
-        closesocket(fd);
+        close(fd);
         return NULL;
     }
     switch(so_type) {
@@ -468,7 +468,7 @@ static NetSocketState *net_socket_fd_init(NetClientState *peer,
     default:
         error_setg(errp, "socket type=%d for fd=%d must be either"
                    " SOCK_DGRAM or SOCK_STREAM", so_type, fd);
-        closesocket(fd);
+        close(fd);
     }
     return NULL;
 }
@@ -526,13 +526,13 @@ static int net_socket_listen_init(NetClientState *peer,
     if (ret < 0) {
         error_setg_errno(errp, errno, "can't bind ip=%s to socket",
                          inet_ntoa(saddr.sin_addr));
-        closesocket(fd);
+        close(fd);
         return -1;
     }
     ret = listen(fd, 0);
     if (ret < 0) {
         error_setg_errno(errp, errno, "can't listen on socket");
-        closesocket(fd);
+        close(fd);
         return -1;
     }
 
@@ -579,7 +579,7 @@ static int net_socket_connect_init(NetClientState *peer,
                 break;
             } else {
                 error_setg_errno(errp, errno, "can't connect socket");
-                closesocket(fd);
+                close(fd);
                 return -1;
             }
         } else {
@@ -671,14 +671,14 @@ static int net_socket_udp_init(NetClientState *peer,
     if (ret < 0) {
         error_setg_errno(errp, errno,
                          "can't set socket option SO_REUSEADDR");
-        closesocket(fd);
+        close(fd);
         return -1;
     }
     ret = bind(fd, (struct sockaddr *)&laddr, sizeof(laddr));
     if (ret < 0) {
         error_setg_errno(errp, errno, "can't bind ip=%s to socket",
                          inet_ntoa(laddr.sin_addr));
-        closesocket(fd);
+        close(fd);
         return -1;
     }
     qemu_socket_set_nonblock(fd);
diff --git a/tests/qtest/libqtest.c b/tests/qtest/libqtest.c
index 2bfd460531..dee2032331 100644
--- a/tests/qtest/libqtest.c
+++ b/tests/qtest/libqtest.c
@@ -124,7 +124,7 @@ static int socket_accept(int sock)
                    (void *)&timeout, sizeof(timeout))) {
         fprintf(stderr, "%s failed to set SO_RCVTIMEO: %s\n",
                 __func__, strerror(errno));
-        closesocket(sock);
+        close(sock);
         return -1;
     }
 
@@ -135,7 +135,7 @@ static int socket_accept(int sock)
     if (ret == -1) {
         fprintf(stderr, "%s failed: %s\n", __func__, strerror(errno));
     }
-    closesocket(sock);
+    close(sock);
 
     return ret;
 }
@@ -564,8 +564,8 @@ void qtest_quit(QTestState *s)
     qtest_remove_abrt_handler(s);
 
     qtest_kill_qemu(s);
-    closesocket(s->fd);
-    closesocket(s->qmp_fd);
+    close(s->fd);
+    close(s->qmp_fd);
     g_string_free(s->rx, true);
 
     for (GList *it = s->pending_events; it != NULL; it = it->next) {
diff --git a/tests/qtest/microbit-test.c b/tests/qtest/microbit-test.c
index 4bc267020b..6022a92b6a 100644
--- a/tests/qtest/microbit-test.c
+++ b/tests/qtest/microbit-test.c
@@ -107,7 +107,7 @@ static void test_nrf51_uart(void)
     g_assert_true(recv(sock_fd, s, 10, 0) == 5);
     g_assert_true(memcmp(s, "world", 5) == 0);
 
-    closesocket(sock_fd);
+    close(sock_fd);
 
     qtest_quit(qts);
 }
diff --git a/tests/qtest/netdev-socket.c b/tests/qtest/netdev-socket.c
index 270e424bee..9cf1b0698e 100644
--- a/tests/qtest/netdev-socket.c
+++ b/tests/qtest/netdev-socket.c
@@ -99,7 +99,7 @@ static int inet_get_free_port_multiple(int nb, int *port, bool ipv6)
 
     nb = i;
     for (i = 0; i < nb; i++) {
-        closesocket(sock[i]);
+        close(sock[i]);
     }
 
     return nb;
@@ -361,8 +361,8 @@ static void test_stream_fd(void)
     qtest_quit(qts1);
     qtest_quit(qts0);
 
-    closesocket(sock[0]);
-    closesocket(sock[1]);
+    close(sock[0]);
+    close(sock[1]);
 }
 #endif
 
@@ -487,8 +487,8 @@ static void test_dgram_fd(void)
     qtest_quit(qts1);
     qtest_quit(qts0);
 
-    closesocket(sv[0]);
-    closesocket(sv[1]);
+    close(sv[0]);
+    close(sv[1]);
 }
 #endif
 
diff --git a/tests/unit/socket-helpers.c b/tests/unit/socket-helpers.c
index 914b3aa0cf..6de27baee2 100644
--- a/tests/unit/socket-helpers.c
+++ b/tests/unit/socket-helpers.c
@@ -117,13 +117,13 @@ static int socket_can_bind_connect(const char *hostname, int family)
 
  cleanup:
     if (afd != -1) {
-        closesocket(afd);
+        close(afd);
     }
     if (cfd != -1) {
-        closesocket(cfd);
+        close(cfd);
     }
     if (lfd != -1) {
-        closesocket(lfd);
+        close(lfd);
     }
     if (res) {
         freeaddrinfo(res);
@@ -160,7 +160,7 @@ void socket_check_afunix_support(bool *has_afunix)
     int fd;
 
     fd = socket(PF_UNIX, SOCK_STREAM, 0);
-    closesocket(fd);
+    close(fd);
 
 #ifdef _WIN32
     *has_afunix = (fd != (int)INVALID_SOCKET);
diff --git a/util/oslib-win32.c b/util/oslib-win32.c
index 7836fb0be3..29a667ae3d 100644
--- a/util/oslib-win32.c
+++ b/util/oslib-win32.c
@@ -370,39 +370,39 @@ int qemu_bind_wrap(int sockfd, const struct sockaddr *addr,
 }
 
 
-#undef closesocket
-int qemu_closesocket_wrap(int fd)
+#undef close
+int qemu_close_wrap(int fd)
 {
     int ret;
     DWORD flags = 0;
-    SOCKET s = _get_osfhandle(fd);
+    SOCKET s = INVALID_SOCKET;
 
-    if (s == INVALID_SOCKET) {
-        return -1;
-    }
+    if (fd_is_socket(fd)) {
+        s = _get_osfhandle(fd);
 
-    /*
-     * If we were to just call _close on the descriptor, it would close the
-     * HANDLE, but it wouldn't free any of the resources associated to the
-     * SOCKET, and we can't call _close after calling closesocket, because
-     * closesocket has already closed the HANDLE, and _close would attempt to
-     * close the HANDLE again, resulting in a double free. We can however
-     * protect the HANDLE from actually being closed long enough to close the
-     * file descriptor, then close the socket itself.
-     */
-    if (!GetHandleInformation((HANDLE)s, &flags)) {
-        errno = EACCES;
-        return -1;
-    }
+        /*
+         * If we were to just call _close on the descriptor, it would close the
+         * HANDLE, but it wouldn't free any of the resources associated to the
+         * SOCKET, and we can't call _close after calling closesocket, because
+         * closesocket has already closed the HANDLE, and _close would attempt to
+         * close the HANDLE again, resulting in a double free. We can however
+         * protect the HANDLE from actually being closed long enough to close the
+         * file descriptor, then close the socket itself.
+         */
+        if (!GetHandleInformation((HANDLE)s, &flags)) {
+            errno = EACCES;
+            return -1;
+        }
 
-    if (!SetHandleInformation((HANDLE)s, HANDLE_FLAG_PROTECT_FROM_CLOSE, HANDLE_FLAG_PROTECT_FROM_CLOSE)) {
-        errno = EACCES;
-        return -1;
+        if (!SetHandleInformation((HANDLE)s, HANDLE_FLAG_PROTECT_FROM_CLOSE, HANDLE_FLAG_PROTECT_FROM_CLOSE)) {
+            errno = EACCES;
+            return -1;
+        }
     }
 
     ret = close(fd);
 
-    if (!SetHandleInformation((HANDLE)s, flags, flags)) {
+    if (s != INVALID_SOCKET && !SetHandleInformation((HANDLE)s, flags, flags)) {
         errno = EACCES;
         return -1;
     }
@@ -411,13 +411,15 @@ int qemu_closesocket_wrap(int fd)
      * close() returns EBADF since we PROTECT_FROM_CLOSE the underlying handle,
      * but the FD is actually freed
      */
-    if (ret < 0 && errno != EBADF) {
+    if (ret < 0 && (s == INVALID_SOCKET || errno != EBADF)) {
         return ret;
     }
 
-    ret = closesocket(s);
-    if (ret < 0) {
-        errno = socket_error();
+    if (s != INVALID_SOCKET) {
+        ret = closesocket(s);
+        if (ret < 0) {
+            errno = socket_error();
+        }
     }
 
     return ret;
diff --git a/util/qemu-sockets.c b/util/qemu-sockets.c
index 6538859b87..c06a4dce77 100644
--- a/util/qemu-sockets.c
+++ b/util/qemu-sockets.c
@@ -326,7 +326,7 @@ static int inet_listen_saddr(InetSocketAddress *saddr,
              * recover from this situation, so we need to recreate the
              * socket to allow bind attempts for subsequent ports:
              */
-            closesocket(slisten);
+            close(slisten);
             slisten = -1;
         }
     }
@@ -337,7 +337,7 @@ static int inet_listen_saddr(InetSocketAddress *saddr,
 listen_failed:
     saved_errno = errno;
     if (slisten >= 0) {
-        closesocket(slisten);
+        close(slisten);
     }
     freeaddrinfo(res);
     errno = saved_errno;
@@ -380,7 +380,7 @@ static int inet_connect_addr(const InetSocketAddress *saddr,
     if (rc < 0) {
         error_setg_errno(errp, errno, "Failed to connect to '%s:%s'",
                          saddr->host, saddr->port);
-        closesocket(sock);
+        close(sock);
         return -1;
     }
 
@@ -483,7 +483,7 @@ int inet_connect_saddr(InetSocketAddress *saddr, Error **errp)
 
         if (ret < 0) {
             error_setg_errno(errp, errno, "Unable to set KEEPALIVE");
-            closesocket(sock);
+            close(sock);
             return -1;
         }
     }
@@ -580,7 +580,7 @@ static int inet_dgram_saddr(InetSocketAddress *sraddr,
 
 err:
     if (sock != -1) {
-        closesocket(sock);
+        close(sock);
     }
     if (local) {
         freeaddrinfo(local);
@@ -777,7 +777,7 @@ static int vsock_connect_addr(const VsockSocketAddress *vaddr,
     if (rc < 0) {
         error_setg_errno(errp, errno, "Failed to connect to '%s:%s'",
                          vaddr->cid, vaddr->port);
-        closesocket(sock);
+        close(sock);
         return -1;
     }
 
@@ -814,13 +814,13 @@ static int vsock_listen_saddr(VsockSocketAddress *vaddr,
 
     if (bind(slisten, (const struct sockaddr *)&svm, sizeof(svm)) != 0) {
         error_setg_errno(errp, errno, "Failed to bind socket");
-        closesocket(slisten);
+        close(slisten);
         return -1;
     }
 
     if (listen(slisten, num) != 0) {
         error_setg_errno(errp, errno, "Failed to listen on socket");
-        closesocket(slisten);
+        close(slisten);
         return -1;
     }
     return slisten;
@@ -978,7 +978,7 @@ static int unix_listen_saddr(UnixSocketAddress *saddr,
 
 err:
     g_free(pathbuf);
-    closesocket(sock);
+    close(sock);
     return -1;
 }
 
@@ -1041,7 +1041,7 @@ static int unix_connect_saddr(UnixSocketAddress *saddr, Error **errp)
     return sock;
 
  err:
-    closesocket(sock);
+    close(sock);
     return -1;
 }
 
@@ -1238,7 +1238,7 @@ int socket_listen(SocketAddress *addr, int num, Error **errp)
          */
         if (listen(fd, num) != 0) {
             error_setg_errno(errp, errno, "Failed to listen on fd socket");
-            closesocket(fd);
+            close(fd);
             return -1;
         }
         break;
-- 
2.39.2



^ permalink raw reply related	[flat|nested] 35+ messages in thread

* [PULL v2 16/25] tests: fix path separator, use g_build_filename()
  2023-03-13 11:46 [PULL v2 00/25] Win socket patches marcandre.lureau
                   ` (14 preceding siblings ...)
  2023-03-13 11:46 ` [PULL v2 15/25] win32: replace closesocket() with close() wrapper marcandre.lureau
@ 2023-03-13 11:46 ` marcandre.lureau
  2023-03-13 11:46 ` [PULL v2 17/25] char: do not double-close fd when failing to add client marcandre.lureau
                   ` (9 subsequent siblings)
  25 siblings, 0 replies; 35+ messages in thread
From: marcandre.lureau @ 2023-03-13 11:46 UTC (permalink / raw)
  To: qemu-devel
  Cc: qemu-block, Dr. David Alan Gilbert, Daniel P. Berrangé,
	Philippe Mathieu-Daudé,
	Eric Blake, Samuel Thibault, Hanna Reitz, Stefan Weil,
	Thomas Huth, Fam Zheng, Beraldo Leal, Paolo Bonzini, Jason Wang,
	Michael Roth, Stefan Berger, qemu-arm, Joel Stanley,
	Alex Bennée, Peter Maydell, Stefan Hajnoczi,
	Markus Armbruster, Marc-André Lureau, Kevin Wolf,
	Laurent Vivier, Wainer dos Santos Moschetta

From: Marc-André Lureau <marcandre.lureau@redhat.com>

Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
Reviewed-by: Philippe Mathieu-Daudé <philmd@linaro.org>
Reviewed-by: Thomas Huth <thuth@redhat.com>
Message-Id: <20230306122751.2355515-2-marcandre.lureau@redhat.com>
---
 tests/unit/test-io-channel-command.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/tests/unit/test-io-channel-command.c b/tests/unit/test-io-channel-command.c
index c6e66a8c33..4f022617df 100644
--- a/tests/unit/test-io-channel-command.c
+++ b/tests/unit/test-io-channel-command.c
@@ -35,7 +35,7 @@ static char *socat = NULL;
 static void test_io_channel_command_fifo(bool async)
 {
     g_autofree gchar *tmpdir = g_dir_make_tmp("qemu-test-io-channel.XXXXXX", NULL);
-    g_autofree gchar *fifo = g_strdup_printf("%s/%s", tmpdir, TEST_FIFO);
+    g_autofree gchar *fifo = g_build_filename(tmpdir, TEST_FIFO, NULL);
     g_autofree gchar *srcargs = g_strdup_printf("%s - PIPE:%s,wronly", socat, fifo);
     g_autofree gchar *dstargs = g_strdup_printf("%s PIPE:%s,rdonly -", socat, fifo);
     g_auto(GStrv) srcargv = g_strsplit(srcargs, " ", -1);
-- 
2.39.2



^ permalink raw reply related	[flat|nested] 35+ messages in thread

* [PULL v2 17/25] char: do not double-close fd when failing to add client
  2023-03-13 11:46 [PULL v2 00/25] Win socket patches marcandre.lureau
                   ` (15 preceding siblings ...)
  2023-03-13 11:46 ` [PULL v2 16/25] tests: fix path separator, use g_build_filename() marcandre.lureau
@ 2023-03-13 11:46 ` marcandre.lureau
  2023-03-13 11:46 ` [PULL v2 18/25] tests/docker: fix a win32 error due to portability marcandre.lureau
                   ` (8 subsequent siblings)
  25 siblings, 0 replies; 35+ messages in thread
From: marcandre.lureau @ 2023-03-13 11:46 UTC (permalink / raw)
  To: qemu-devel
  Cc: qemu-block, Dr. David Alan Gilbert, Daniel P. Berrangé,
	Philippe Mathieu-Daudé,
	Eric Blake, Samuel Thibault, Hanna Reitz, Stefan Weil,
	Thomas Huth, Fam Zheng, Beraldo Leal, Paolo Bonzini, Jason Wang,
	Michael Roth, Stefan Berger, qemu-arm, Joel Stanley,
	Alex Bennée, Peter Maydell, Stefan Hajnoczi,
	Markus Armbruster, Marc-André Lureau, Kevin Wolf,
	Laurent Vivier, Wainer dos Santos Moschetta

From: Marc-André Lureau <marcandre.lureau@redhat.com>

The caller is already closing the fd on failure.

Fixes: c3054a6e6a ("char: Factor out qmp_add_client() parts and move to chardev/")
Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
Reviewed-by: Philippe Mathieu-Daudé <philmd@linaro.org>
Reviewed-by: Thomas Huth <thuth@redhat.com>
Message-Id: <20230306122751.2355515-3-marcandre.lureau@redhat.com>
---
 chardev/char.c | 2 --
 1 file changed, 2 deletions(-)

diff --git a/chardev/char.c b/chardev/char.c
index 11eab7764c..e69390601f 100644
--- a/chardev/char.c
+++ b/chardev/char.c
@@ -1175,12 +1175,10 @@ bool qmp_add_client_char(int fd, bool has_skipauth, bool skipauth,
 
     if (!s) {
         error_setg(errp, "protocol '%s' is invalid", protocol);
-        close(fd);
         return false;
     }
     if (qemu_chr_add_client(s, fd) < 0) {
         error_setg(errp, "failed to add client");
-        close(fd);
         return false;
     }
     return true;
-- 
2.39.2



^ permalink raw reply related	[flat|nested] 35+ messages in thread

* [PULL v2 18/25] tests/docker: fix a win32 error due to portability
  2023-03-13 11:46 [PULL v2 00/25] Win socket patches marcandre.lureau
                   ` (16 preceding siblings ...)
  2023-03-13 11:46 ` [PULL v2 17/25] char: do not double-close fd when failing to add client marcandre.lureau
@ 2023-03-13 11:46 ` marcandre.lureau
  2023-03-13 11:46 ` [PULL v2 19/25] osdep: implement qemu_socketpair() for win32 marcandre.lureau
                   ` (7 subsequent siblings)
  25 siblings, 0 replies; 35+ messages in thread
From: marcandre.lureau @ 2023-03-13 11:46 UTC (permalink / raw)
  To: qemu-devel
  Cc: qemu-block, Dr. David Alan Gilbert, Daniel P. Berrangé,
	Philippe Mathieu-Daudé,
	Eric Blake, Samuel Thibault, Hanna Reitz, Stefan Weil,
	Thomas Huth, Fam Zheng, Beraldo Leal, Paolo Bonzini, Jason Wang,
	Michael Roth, Stefan Berger, qemu-arm, Joel Stanley,
	Alex Bennée, Peter Maydell, Stefan Hajnoczi,
	Markus Armbruster, Marc-André Lureau, Kevin Wolf,
	Laurent Vivier, Wainer dos Santos Moschetta

From: Marc-André Lureau <marcandre.lureau@redhat.com>

docker.py is run during configure, and produces an error: No module
named 'pwd'.

Use a more portable and recommended alternative to lookup the user
"login name".

Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
Reviewed-by: Philippe Mathieu-Daudé <philmd@linaro.org>
Message-Id: <20230306122751.2355515-4-marcandre.lureau@redhat.com>
---
 tests/docker/docker.py | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/tests/docker/docker.py b/tests/docker/docker.py
index 3a1ed7cb18..688ef62989 100755
--- a/tests/docker/docker.py
+++ b/tests/docker/docker.py
@@ -23,10 +23,10 @@
 import tempfile
 import re
 import signal
+import getpass
 from tarfile import TarFile, TarInfo
 from io import StringIO, BytesIO
 from shutil import copy, rmtree
-from pwd import getpwuid
 from datetime import datetime, timedelta
 
 
@@ -316,7 +316,7 @@ def build_image(self, tag, docker_dir, dockerfile,
 
         if user:
             uid = os.getuid()
-            uname = getpwuid(uid).pw_name
+            uname = getpass.getuser()
             tmp_df.write("\n")
             tmp_df.write("RUN id %s 2>/dev/null || useradd -u %d -U %s" %
                          (uname, uid, uname))
@@ -570,7 +570,7 @@ def run(self, args, argv):
 
         if args.user:
             uid = os.getuid()
-            uname = getpwuid(uid).pw_name
+            uname = getpass.getuser()
             df.write("\n")
             df.write("RUN id %s 2>/dev/null || useradd -u %d -U %s" %
                      (uname, uid, uname))
-- 
2.39.2



^ permalink raw reply related	[flat|nested] 35+ messages in thread

* [PULL v2 19/25] osdep: implement qemu_socketpair() for win32
  2023-03-13 11:46 [PULL v2 00/25] Win socket patches marcandre.lureau
                   ` (17 preceding siblings ...)
  2023-03-13 11:46 ` [PULL v2 18/25] tests/docker: fix a win32 error due to portability marcandre.lureau
@ 2023-03-13 11:46 ` marcandre.lureau
  2023-03-13 11:46 ` [PULL v2 20/25] qmp: 'add_client' actually expects sockets marcandre.lureau
                   ` (6 subsequent siblings)
  25 siblings, 0 replies; 35+ messages in thread
From: marcandre.lureau @ 2023-03-13 11:46 UTC (permalink / raw)
  To: qemu-devel
  Cc: qemu-block, Dr. David Alan Gilbert, Daniel P. Berrangé,
	Philippe Mathieu-Daudé,
	Eric Blake, Samuel Thibault, Hanna Reitz, Stefan Weil,
	Thomas Huth, Fam Zheng, Beraldo Leal, Paolo Bonzini, Jason Wang,
	Michael Roth, Stefan Berger, qemu-arm, Joel Stanley,
	Alex Bennée, Peter Maydell, Stefan Hajnoczi,
	Markus Armbruster, Marc-André Lureau, Kevin Wolf,
	Laurent Vivier, Wainer dos Santos Moschetta

From: Marc-André Lureau <marcandre.lureau@redhat.com>

Manually implement a socketpair() function, using UNIX sockets and
simple peer credential checking.

QEMU doesn't make much use of socketpair, beside vhost-user which is not
available for win32 at this point. However, I intend to use it for
writing some new portable tests.

Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
Reviewed-by: Daniel P. Berrangé <berrange@redhat.com>
Message-Id: <20230306122751.2355515-5-marcandre.lureau@redhat.com>
---
 include/qemu/sockets.h |   2 -
 util/oslib-win32.c     | 110 +++++++++++++++++++++++++++++++++++++++++
 2 files changed, 110 insertions(+), 2 deletions(-)

diff --git a/include/qemu/sockets.h b/include/qemu/sockets.h
index 2b0698a7c9..d935fd80da 100644
--- a/include/qemu/sockets.h
+++ b/include/qemu/sockets.h
@@ -15,7 +15,6 @@ int inet_aton(const char *cp, struct in_addr *ia);
 bool fd_is_socket(int fd);
 int qemu_socket(int domain, int type, int protocol);
 
-#ifndef WIN32
 /**
  * qemu_socketpair:
  * @domain: specifies a communication domain, such as PF_UNIX
@@ -30,7 +29,6 @@ int qemu_socket(int domain, int type, int protocol);
  * Return 0 on success.
  */
 int qemu_socketpair(int domain, int type, int protocol, int sv[2]);
-#endif
 
 int qemu_accept(int s, struct sockaddr *addr, socklen_t *addrlen);
 /*
diff --git a/util/oslib-win32.c b/util/oslib-win32.c
index 29a667ae3d..16f8a67f7e 100644
--- a/util/oslib-win32.c
+++ b/util/oslib-win32.c
@@ -310,6 +310,116 @@ bool qemu_socket_unselect(int sockfd, Error **errp)
     return qemu_socket_select(sockfd, NULL, 0, errp);
 }
 
+int qemu_socketpair(int domain, int type, int protocol, int sv[2])
+{
+    struct sockaddr_un addr = {
+        0,
+    };
+    socklen_t socklen;
+    int listener = -1;
+    int client = -1;
+    int server = -1;
+    g_autofree char *path = NULL;
+    int tmpfd;
+    u_long arg;
+    int ret = -1;
+
+    g_return_val_if_fail(sv != NULL, -1);
+
+    addr.sun_family = AF_UNIX;
+    socklen = sizeof(addr);
+
+    tmpfd = g_file_open_tmp(NULL, &path, NULL);
+    if (tmpfd == -1 || !path) {
+        errno = EACCES;
+        goto out;
+    }
+
+    close(tmpfd);
+
+    if (strlen(path) >= sizeof(addr.sun_path)) {
+        errno = EINVAL;
+        goto out;
+    }
+
+    strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
+
+    listener = socket(domain, type, protocol);
+    if (listener == -1) {
+        goto out;
+    }
+
+    if (DeleteFile(path) == 0 && GetLastError() != ERROR_FILE_NOT_FOUND) {
+        errno = EACCES;
+        goto out;
+    }
+    g_clear_pointer(&path, g_free);
+
+    if (bind(listener, (struct sockaddr *)&addr, socklen) == -1) {
+        goto out;
+    }
+
+    if (listen(listener, 1) == -1) {
+        goto out;
+    }
+
+    client = socket(domain, type, protocol);
+    if (client == -1) {
+        goto out;
+    }
+
+    arg = 1;
+    if (ioctlsocket(client, FIONBIO, &arg) != NO_ERROR) {
+        goto out;
+    }
+
+    if (connect(client, (struct sockaddr *)&addr, socklen) == -1 &&
+        WSAGetLastError() != WSAEWOULDBLOCK) {
+        goto out;
+    }
+
+    server = accept(listener, NULL, NULL);
+    if (server == -1) {
+        goto out;
+    }
+
+    arg = 0;
+    if (ioctlsocket(client, FIONBIO, &arg) != NO_ERROR) {
+        goto out;
+    }
+
+    arg = 0;
+    if (ioctlsocket(client, SIO_AF_UNIX_GETPEERPID, &arg) != NO_ERROR) {
+        goto out;
+    }
+
+    if (arg != GetCurrentProcessId()) {
+        errno = EPERM;
+        goto out;
+    }
+
+    sv[0] = server;
+    server = -1;
+    sv[1] = client;
+    client = -1;
+    ret = 0;
+
+out:
+    if (listener != -1) {
+        close(listener);
+    }
+    if (client != -1) {
+        close(client);
+    }
+    if (server != -1) {
+        close(server);
+    }
+    if (path) {
+        DeleteFile(path);
+    }
+    return ret;
+}
+
 #undef connect
 int qemu_connect_wrap(int sockfd, const struct sockaddr *addr,
                       socklen_t addrlen)
-- 
2.39.2



^ permalink raw reply related	[flat|nested] 35+ messages in thread

* [PULL v2 20/25] qmp: 'add_client' actually expects sockets
  2023-03-13 11:46 [PULL v2 00/25] Win socket patches marcandre.lureau
                   ` (18 preceding siblings ...)
  2023-03-13 11:46 ` [PULL v2 19/25] osdep: implement qemu_socketpair() for win32 marcandre.lureau
@ 2023-03-13 11:46 ` marcandre.lureau
  2023-03-13 11:46 ` [PULL v2 21/25] monitor: release the lock before calling close() marcandre.lureau
                   ` (5 subsequent siblings)
  25 siblings, 0 replies; 35+ messages in thread
From: marcandre.lureau @ 2023-03-13 11:46 UTC (permalink / raw)
  To: qemu-devel
  Cc: qemu-block, Dr. David Alan Gilbert, Daniel P. Berrangé,
	Philippe Mathieu-Daudé,
	Eric Blake, Samuel Thibault, Hanna Reitz, Stefan Weil,
	Thomas Huth, Fam Zheng, Beraldo Leal, Paolo Bonzini, Jason Wang,
	Michael Roth, Stefan Berger, qemu-arm, Joel Stanley,
	Alex Bennée, Peter Maydell, Stefan Hajnoczi,
	Markus Armbruster, Marc-André Lureau, Kevin Wolf,
	Laurent Vivier, Wainer dos Santos Moschetta

From: Marc-André Lureau <marcandre.lureau@redhat.com>

Whether it is SPICE, VNC, D-Bus, or the socket chardev, they all
actually expect a socket kind or will fail in different ways at runtime.

Throw an error early if the given 'add_client' fd is not a socket, and
close it to avoid leaks.

This allows to replace the close() call with a more correct & portable
closesocket() version.

(this will allow importing sockets on Windows with a specialized command
in the following patch, while keeping the remaining monitor associated
sockets/add_client code & usage untouched)

Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
Reviewed-by: Philippe Mathieu-Daudé <philmd@linaro.org>
Acked-by: Markus Armbruster <armbru@redhat.com>
Message-Id: <20230306122751.2355515-6-marcandre.lureau@redhat.com>
---
 qapi/misc.json     | 3 +++
 monitor/qmp-cmds.c | 7 +++++++
 2 files changed, 10 insertions(+)

diff --git a/qapi/misc.json b/qapi/misc.json
index 27ef5a2b20..f0217cfba0 100644
--- a/qapi/misc.json
+++ b/qapi/misc.json
@@ -14,6 +14,9 @@
 # Allow client connections for VNC, Spice and socket based
 # character devices to be passed in to QEMU via SCM_RIGHTS.
 #
+# If the FD associated with @fdname is not a socket, the command will fail and
+# the FD will be closed.
+#
 # @protocol: protocol name. Valid names are "vnc", "spice", "@dbus-display" or
 #            the name of a character device (eg. from -chardev id=XXXX)
 #
diff --git a/monitor/qmp-cmds.c b/monitor/qmp-cmds.c
index 859012aef4..b0f948d337 100644
--- a/monitor/qmp-cmds.c
+++ b/monitor/qmp-cmds.c
@@ -14,6 +14,7 @@
  */
 
 #include "qemu/osdep.h"
+#include "qemu/sockets.h"
 #include "monitor-internal.h"
 #include "monitor/qdev.h"
 #include "monitor/qmp-helpers.h"
@@ -139,6 +140,12 @@ void qmp_add_client(const char *protocol, const char *fdname,
         return;
     }
 
+    if (!fd_is_socket(fd)) {
+        error_setg(errp, "parameter @fdname must name a socket");
+        close(fd);
+        return;
+    }
+
     for (i = 0; i < ARRAY_SIZE(protocol_table); i++) {
         if (!strcmp(protocol, protocol_table[i].name)) {
             if (!protocol_table[i].add_client(fd, has_skipauth, skipauth,
-- 
2.39.2



^ permalink raw reply related	[flat|nested] 35+ messages in thread

* [PULL v2 21/25] monitor: release the lock before calling close()
  2023-03-13 11:46 [PULL v2 00/25] Win socket patches marcandre.lureau
                   ` (19 preceding siblings ...)
  2023-03-13 11:46 ` [PULL v2 20/25] qmp: 'add_client' actually expects sockets marcandre.lureau
@ 2023-03-13 11:46 ` marcandre.lureau
  2023-03-13 11:46 ` [PULL v2 22/25] qmp: add 'get-win32-socket' marcandre.lureau
                   ` (4 subsequent siblings)
  25 siblings, 0 replies; 35+ messages in thread
From: marcandre.lureau @ 2023-03-13 11:46 UTC (permalink / raw)
  To: qemu-devel
  Cc: qemu-block, Dr. David Alan Gilbert, Daniel P. Berrangé,
	Philippe Mathieu-Daudé,
	Eric Blake, Samuel Thibault, Hanna Reitz, Stefan Weil,
	Thomas Huth, Fam Zheng, Beraldo Leal, Paolo Bonzini, Jason Wang,
	Michael Roth, Stefan Berger, qemu-arm, Joel Stanley,
	Alex Bennée, Peter Maydell, Stefan Hajnoczi,
	Markus Armbruster, Marc-André Lureau, Kevin Wolf,
	Laurent Vivier, Wainer dos Santos Moschetta

From: Marc-André Lureau <marcandre.lureau@redhat.com>

As per comment, presumably to avoid syscall in critical section.

Fixes: 0210c3b39bef08 ("monitor: Use LOCK_GUARD macros")
Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
Reviewed-by: Philippe Mathieu-Daudé <philmd@linaro.org>
Message-Id: <20230306122751.2355515-7-marcandre.lureau@redhat.com>
---
 monitor/fds.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)

diff --git a/monitor/fds.c b/monitor/fds.c
index 26b39a0ce6..7daf1064e1 100644
--- a/monitor/fds.c
+++ b/monitor/fds.c
@@ -80,7 +80,8 @@ void qmp_getfd(const char *fdname, Error **errp)
         return;
     }
 
-    QEMU_LOCK_GUARD(&cur_mon->mon_lock);
+    /* See close() call below. */
+    qemu_mutex_lock(&cur_mon->mon_lock);
     QLIST_FOREACH(monfd, &cur_mon->fds, next) {
         if (strcmp(monfd->name, fdname) != 0) {
             continue;
@@ -88,6 +89,7 @@ void qmp_getfd(const char *fdname, Error **errp)
 
         tmp_fd = monfd->fd;
         monfd->fd = fd;
+        qemu_mutex_unlock(&cur_mon->mon_lock);
         /* Make sure close() is outside critical section */
         close(tmp_fd);
         return;
@@ -98,6 +100,7 @@ void qmp_getfd(const char *fdname, Error **errp)
     monfd->fd = fd;
 
     QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
+    qemu_mutex_unlock(&cur_mon->mon_lock);
 }
 
 void qmp_closefd(const char *fdname, Error **errp)
-- 
2.39.2



^ permalink raw reply related	[flat|nested] 35+ messages in thread

* [PULL v2 22/25] qmp: add 'get-win32-socket'
  2023-03-13 11:46 [PULL v2 00/25] Win socket patches marcandre.lureau
                   ` (20 preceding siblings ...)
  2023-03-13 11:46 ` [PULL v2 21/25] monitor: release the lock before calling close() marcandre.lureau
@ 2023-03-13 11:46 ` marcandre.lureau
  2023-03-13 11:46 ` [PULL v2 23/25] libqtest: make qtest_qmp_add_client work on win32 marcandre.lureau
                   ` (3 subsequent siblings)
  25 siblings, 0 replies; 35+ messages in thread
From: marcandre.lureau @ 2023-03-13 11:46 UTC (permalink / raw)
  To: qemu-devel
  Cc: qemu-block, Dr. David Alan Gilbert, Daniel P. Berrangé,
	Philippe Mathieu-Daudé,
	Eric Blake, Samuel Thibault, Hanna Reitz, Stefan Weil,
	Thomas Huth, Fam Zheng, Beraldo Leal, Paolo Bonzini, Jason Wang,
	Michael Roth, Stefan Berger, qemu-arm, Joel Stanley,
	Alex Bennée, Peter Maydell, Stefan Hajnoczi,
	Markus Armbruster, Marc-André Lureau, Kevin Wolf,
	Laurent Vivier, Wainer dos Santos Moschetta

From: Marc-André Lureau <marcandre.lureau@redhat.com>

A process with enough capabilities can duplicate a socket to QEMU. Add a
QMP command to import it and add it to the monitor fd list, so it can be
later used by other commands.

Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
Acked-by: Markus Armbruster <armbru@redhat.com>
Message-Id: <20230306122751.2355515-9-marcandre.lureau@redhat.com>
---
 qapi/misc.json | 31 ++++++++++++++++++++
 monitor/fds.c  | 76 +++++++++++++++++++++++++++++++++++++++-----------
 2 files changed, 91 insertions(+), 16 deletions(-)

diff --git a/qapi/misc.json b/qapi/misc.json
index f0217cfba0..5ef6286af3 100644
--- a/qapi/misc.json
+++ b/qapi/misc.json
@@ -275,6 +275,37 @@
 ##
 { 'command': 'getfd', 'data': {'fdname': 'str'} }
 
+##
+# @get-win32-socket:
+#
+# Add a socket that was duplicated to QEMU process with
+# WSADuplicateSocketW() via WSASocket() & WSAPROTOCOL_INFOW structure
+# and assign it a name (the SOCKET is associated with a CRT file
+# descriptor)
+#
+# @info: the WSAPROTOCOL_INFOW structure (encoded in base64)
+#
+# @fdname: file descriptor name
+#
+# Returns: Nothing on success
+#
+# Since: 8.0
+#
+# Notes: If @fdname already exists, the file descriptor assigned to
+#        it will be closed and replaced by the received file
+#        descriptor.
+#
+#        The 'closefd' command can be used to explicitly close the
+#        file descriptor when it is no longer needed.
+#
+# Example:
+#
+# -> { "execute": "get-win32-socket", "arguments": { "info": "abcd123..", fdname": "skclient" } }
+# <- { "return": {} }
+#
+##
+{ 'command': 'get-win32-socket', 'data': {'info': 'str', 'fdname': 'str'}, 'if': 'CONFIG_WIN32' }
+
 ##
 # @closefd:
 #
diff --git a/monitor/fds.c b/monitor/fds.c
index 7daf1064e1..9ed4197358 100644
--- a/monitor/fds.c
+++ b/monitor/fds.c
@@ -61,46 +61,55 @@ struct MonFdset {
 static QemuMutex mon_fdsets_lock;
 static QLIST_HEAD(, MonFdset) mon_fdsets;
 
-void qmp_getfd(const char *fdname, Error **errp)
+static bool monitor_add_fd(Monitor *mon, int fd, const char *fdname, Error **errp)
 {
-    Monitor *cur_mon = monitor_cur();
     mon_fd_t *monfd;
-    int fd, tmp_fd;
-
-    fd = qemu_chr_fe_get_msgfd(&cur_mon->chr);
-    if (fd == -1) {
-        error_setg(errp, "No file descriptor supplied via SCM_RIGHTS");
-        return;
-    }
 
     if (qemu_isdigit(fdname[0])) {
         close(fd);
         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "fdname",
                    "a name not starting with a digit");
-        return;
+        return false;
     }
 
     /* See close() call below. */
-    qemu_mutex_lock(&cur_mon->mon_lock);
-    QLIST_FOREACH(monfd, &cur_mon->fds, next) {
+    qemu_mutex_lock(&mon->mon_lock);
+    QLIST_FOREACH(monfd, &mon->fds, next) {
+        int tmp_fd;
+
         if (strcmp(monfd->name, fdname) != 0) {
             continue;
         }
 
         tmp_fd = monfd->fd;
         monfd->fd = fd;
-        qemu_mutex_unlock(&cur_mon->mon_lock);
+        qemu_mutex_unlock(&mon->mon_lock);
         /* Make sure close() is outside critical section */
         close(tmp_fd);
-        return;
+        return true;
     }
 
     monfd = g_new0(mon_fd_t, 1);
     monfd->name = g_strdup(fdname);
     monfd->fd = fd;
 
-    QLIST_INSERT_HEAD(&cur_mon->fds, monfd, next);
-    qemu_mutex_unlock(&cur_mon->mon_lock);
+    QLIST_INSERT_HEAD(&mon->fds, monfd, next);
+    qemu_mutex_unlock(&mon->mon_lock);
+    return true;
+}
+
+void qmp_getfd(const char *fdname, Error **errp)
+{
+    Monitor *cur_mon = monitor_cur();
+    int fd;
+
+    fd = qemu_chr_fe_get_msgfd(&cur_mon->chr);
+    if (fd == -1) {
+        error_setg(errp, "No file descriptor supplied via SCM_RIGHTS");
+        return;
+    }
+
+    monitor_add_fd(cur_mon, fd, fdname, errp);
 }
 
 void qmp_closefd(const char *fdname, Error **errp)
@@ -214,6 +223,41 @@ error:
     return NULL;
 }
 
+#ifdef WIN32
+void qmp_get_win32_socket(const char *infos, const char *fdname, Error **errp)
+{
+    g_autofree WSAPROTOCOL_INFOW *info = NULL;
+    gsize len;
+    SOCKET sk;
+    int fd;
+
+    info = (void *)g_base64_decode(infos, &len);
+    if (len != sizeof(*info)) {
+        error_setg(errp, "Invalid WSAPROTOCOL_INFOW value");
+        return;
+    }
+
+    sk = WSASocketW(FROM_PROTOCOL_INFO,
+                    FROM_PROTOCOL_INFO,
+                    FROM_PROTOCOL_INFO,
+                    info, 0, 0);
+    if (sk == INVALID_SOCKET) {
+        error_setg_win32(errp, WSAGetLastError(), "Couldn't import socket");
+        return;
+    }
+
+    fd = _open_osfhandle(sk, _O_BINARY);
+    if (fd < 0) {
+        error_setg_errno(errp, errno, "Failed to associate a FD with the SOCKET");
+        closesocket(sk);
+        return;
+    }
+
+    monitor_add_fd(monitor_cur(), fd, fdname, errp);
+}
+#endif
+
+
 void qmp_remove_fd(int64_t fdset_id, bool has_fd, int64_t fd, Error **errp)
 {
     MonFdset *mon_fdset;
-- 
2.39.2



^ permalink raw reply related	[flat|nested] 35+ messages in thread

* [PULL v2 23/25] libqtest: make qtest_qmp_add_client work on win32
  2023-03-13 11:46 [PULL v2 00/25] Win socket patches marcandre.lureau
                   ` (21 preceding siblings ...)
  2023-03-13 11:46 ` [PULL v2 22/25] qmp: add 'get-win32-socket' marcandre.lureau
@ 2023-03-13 11:46 ` marcandre.lureau
  2023-03-13 11:46 ` [PULL v2 24/25] qtest: enable vnc-display test " marcandre.lureau
                   ` (2 subsequent siblings)
  25 siblings, 0 replies; 35+ messages in thread
From: marcandre.lureau @ 2023-03-13 11:46 UTC (permalink / raw)
  To: qemu-devel
  Cc: qemu-block, Dr. David Alan Gilbert, Daniel P. Berrangé,
	Philippe Mathieu-Daudé,
	Eric Blake, Samuel Thibault, Hanna Reitz, Stefan Weil,
	Thomas Huth, Fam Zheng, Beraldo Leal, Paolo Bonzini, Jason Wang,
	Michael Roth, Stefan Berger, qemu-arm, Joel Stanley,
	Alex Bennée, Peter Maydell, Stefan Hajnoczi,
	Markus Armbruster, Marc-André Lureau, Kevin Wolf,
	Laurent Vivier, Wainer dos Santos Moschetta

From: Marc-André Lureau <marcandre.lureau@redhat.com>

Use the "get-win32-socket" function to pass an opened socket to QEMU,
instead of using "getfd", which relies on socket ancillary FD message
passing.

Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
Reviewed-by: Daniel P. Berrangé <berrange@redhat.com>
Message-Id: <20230306122751.2355515-10-marcandre.lureau@redhat.com>
---
 tests/qtest/libqtest.h |  5 ++---
 tests/qtest/libqtest.c | 18 ++++++++++++++++--
 2 files changed, 18 insertions(+), 5 deletions(-)

diff --git a/tests/qtest/libqtest.h b/tests/qtest/libqtest.h
index fcf1c3c3b3..8d7d450963 100644
--- a/tests/qtest/libqtest.h
+++ b/tests/qtest/libqtest.h
@@ -758,17 +758,16 @@ void qtest_qmp_device_add_qdict(QTestState *qts, const char *drv,
 void qtest_qmp_device_add(QTestState *qts, const char *driver, const char *id,
                           const char *fmt, ...) G_GNUC_PRINTF(4, 5);
 
-#ifndef _WIN32
 /**
  * qtest_qmp_add_client:
  * @qts: QTestState instance to operate on
  * @protocol: the protocol to add to
  * @fd: the client file-descriptor
  *
- * Call QMP ``getfd`` followed by ``add_client`` with the given @fd.
+ * Call QMP ``getfd`` (on Windows ``get-win32-socket``) followed by
+ * ``add_client`` with the given @fd.
  */
 void qtest_qmp_add_client(QTestState *qts, const char *protocol, int fd);
-#endif /* _WIN32 */
 
 /**
  * qtest_qmp_device_del_send:
diff --git a/tests/qtest/libqtest.c b/tests/qtest/libqtest.c
index dee2032331..c3a0ef5bb4 100644
--- a/tests/qtest/libqtest.c
+++ b/tests/qtest/libqtest.c
@@ -1478,13 +1478,28 @@ void qtest_qmp_device_add(QTestState *qts, const char *driver, const char *id,
     qobject_unref(args);
 }
 
-#ifndef _WIN32
 void qtest_qmp_add_client(QTestState *qts, const char *protocol, int fd)
 {
     QDict *resp;
 
+#ifdef WIN32
+    WSAPROTOCOL_INFOW info;
+    g_autofree char *info64  = NULL;
+    SOCKET s;
+
+    assert(fd_is_socket(fd));
+    s = _get_osfhandle(fd);
+    if (WSADuplicateSocketW(s, GetProcessId((HANDLE)qts->qemu_pid), &info) == SOCKET_ERROR) {
+        g_autofree char *emsg = g_win32_error_message(WSAGetLastError());
+        g_error("WSADuplicateSocketW failed: %s", emsg);
+    }
+    info64 = g_base64_encode((guchar *)&info, sizeof(info));
+    resp = qtest_qmp(qts, "{'execute': 'get-win32-socket',"
+                     "'arguments': {'fdname': 'fdname', 'info': %s}}", info64);
+#else
     resp = qtest_qmp_fds(qts, &fd, 1, "{'execute': 'getfd',"
                          "'arguments': {'fdname': 'fdname'}}");
+#endif
     g_assert(resp);
     g_assert(!qdict_haskey(resp, "event")); /* We don't expect any events */
     g_assert(!qdict_haskey(resp, "error"));
@@ -1498,7 +1513,6 @@ void qtest_qmp_add_client(QTestState *qts, const char *protocol, int fd)
     g_assert(!qdict_haskey(resp, "error"));
     qobject_unref(resp);
 }
-#endif
 
 /*
  * Generic hot-unplugging test via the device_del QMP command.
-- 
2.39.2



^ permalink raw reply related	[flat|nested] 35+ messages in thread

* [PULL v2 24/25] qtest: enable vnc-display test on win32
  2023-03-13 11:46 [PULL v2 00/25] Win socket patches marcandre.lureau
                   ` (22 preceding siblings ...)
  2023-03-13 11:46 ` [PULL v2 23/25] libqtest: make qtest_qmp_add_client work on win32 marcandre.lureau
@ 2023-03-13 11:46 ` marcandre.lureau
  2023-03-13 11:46 ` [PULL v2 25/25] monitor: restrict command getfd to POSIX hosts marcandre.lureau
  2023-03-13 17:09 ` [PULL v2 00/25] Win socket patches Peter Maydell
  25 siblings, 0 replies; 35+ messages in thread
From: marcandre.lureau @ 2023-03-13 11:46 UTC (permalink / raw)
  To: qemu-devel
  Cc: qemu-block, Dr. David Alan Gilbert, Daniel P. Berrangé,
	Philippe Mathieu-Daudé,
	Eric Blake, Samuel Thibault, Hanna Reitz, Stefan Weil,
	Thomas Huth, Fam Zheng, Beraldo Leal, Paolo Bonzini, Jason Wang,
	Michael Roth, Stefan Berger, qemu-arm, Joel Stanley,
	Alex Bennée, Peter Maydell, Stefan Hajnoczi,
	Markus Armbruster, Marc-André Lureau, Kevin Wolf,
	Laurent Vivier, Wainer dos Santos Moschetta

From: Marc-André Lureau <marcandre.lureau@redhat.com>

Now that qtest_qmp_add_client() works on win32, we can enable the VNC
test.

Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
Acked-by: Thomas Huth <thuth@redhat.com>
Message-Id: <20230306122751.2355515-11-marcandre.lureau@redhat.com>
---
 tests/qtest/vnc-display-test.c | 12 +++++++-----
 1 file changed, 7 insertions(+), 5 deletions(-)

diff --git a/tests/qtest/vnc-display-test.c b/tests/qtest/vnc-display-test.c
index e52a4326ec..f8933b0761 100644
--- a/tests/qtest/vnc-display-test.c
+++ b/tests/qtest/vnc-display-test.c
@@ -19,7 +19,7 @@ typedef struct Test {
     GMainLoop *loop;
 } Test;
 
-#if !defined(WIN32) && !defined(CONFIG_DARWIN)
+#if !defined(CONFIG_DARWIN)
 
 static void on_vnc_error(VncConnection* self,
                          const char* msg)
@@ -38,10 +38,7 @@ static void on_vnc_auth_failure(VncConnection *self,
 static bool
 test_setup(Test *test)
 {
-#ifdef WIN32
-    g_test_skip("Not supported on Windows yet");
-    return false;
-#elif defined(CONFIG_DARWIN)
+#if defined(CONFIG_DARWIN)
     g_test_skip("Broken on Darwin");
     return false;
 #else
@@ -59,7 +56,12 @@ test_setup(Test *test)
     g_signal_connect(test->conn, "vnc-auth-failure",
                      G_CALLBACK(on_vnc_auth_failure), NULL);
     vnc_connection_set_auth_type(test->conn, VNC_CONNECTION_AUTH_NONE);
+
+#ifdef WIN32
+    vnc_connection_open_fd(test->conn, _get_osfhandle(pair[0]));
+#else
     vnc_connection_open_fd(test->conn, pair[0]);
+#endif
 
     test->loop = g_main_loop_new(NULL, FALSE);
     return true;
-- 
2.39.2



^ permalink raw reply related	[flat|nested] 35+ messages in thread

* [PULL v2 25/25] monitor: restrict command getfd to POSIX hosts
  2023-03-13 11:46 [PULL v2 00/25] Win socket patches marcandre.lureau
                   ` (23 preceding siblings ...)
  2023-03-13 11:46 ` [PULL v2 24/25] qtest: enable vnc-display test " marcandre.lureau
@ 2023-03-13 11:46 ` marcandre.lureau
  2023-03-13 17:09 ` [PULL v2 00/25] Win socket patches Peter Maydell
  25 siblings, 0 replies; 35+ messages in thread
From: marcandre.lureau @ 2023-03-13 11:46 UTC (permalink / raw)
  To: qemu-devel
  Cc: qemu-block, Dr. David Alan Gilbert, Daniel P. Berrangé,
	Philippe Mathieu-Daudé,
	Eric Blake, Samuel Thibault, Hanna Reitz, Stefan Weil,
	Thomas Huth, Fam Zheng, Beraldo Leal, Paolo Bonzini, Jason Wang,
	Michael Roth, Stefan Berger, qemu-arm, Joel Stanley,
	Alex Bennée, Peter Maydell, Stefan Hajnoczi,
	Markus Armbruster, Marc-André Lureau, Kevin Wolf,
	Laurent Vivier, Wainer dos Santos Moschetta

From: Marc-André Lureau <marcandre.lureau@redhat.com>

Currently, the function will simply fail if ancillary fds are not
provided, for ex on unsupported platforms.

This changes the failure from:

    {"error": {"class": "GenericError", "desc": "No file descriptor
    supplied via SCM_RIGHTS"}}

to:

    {"error": {"class": "CommandNotFound", "desc": "The command getfd
    has not been found"}}

Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
Reviewed-by: Markus Armbruster <armbru@redhat.com>
---
 qapi/misc.json     | 2 +-
 monitor/fds.c      | 2 ++
 monitor/hmp-cmds.c | 2 ++
 hmp-commands.hx    | 2 ++
 4 files changed, 7 insertions(+), 1 deletion(-)

diff --git a/qapi/misc.json b/qapi/misc.json
index 5ef6286af3..6ddd16ea28 100644
--- a/qapi/misc.json
+++ b/qapi/misc.json
@@ -273,7 +273,7 @@
 # <- { "return": {} }
 #
 ##
-{ 'command': 'getfd', 'data': {'fdname': 'str'} }
+{ 'command': 'getfd', 'data': {'fdname': 'str'}, 'if': 'CONFIG_POSIX' }
 
 ##
 # @get-win32-socket:
diff --git a/monitor/fds.c b/monitor/fds.c
index 9ed4197358..d86c2c674c 100644
--- a/monitor/fds.c
+++ b/monitor/fds.c
@@ -98,6 +98,7 @@ static bool monitor_add_fd(Monitor *mon, int fd, const char *fdname, Error **err
     return true;
 }
 
+#ifdef CONFIG_POSIX
 void qmp_getfd(const char *fdname, Error **errp)
 {
     Monitor *cur_mon = monitor_cur();
@@ -111,6 +112,7 @@ void qmp_getfd(const char *fdname, Error **errp)
 
     monitor_add_fd(cur_mon, fd, fdname, errp);
 }
+#endif
 
 void qmp_closefd(const char *fdname, Error **errp)
 {
diff --git a/monitor/hmp-cmds.c b/monitor/hmp-cmds.c
index 34bd8c67d7..6c559b48c8 100644
--- a/monitor/hmp-cmds.c
+++ b/monitor/hmp-cmds.c
@@ -192,6 +192,7 @@ void hmp_change(Monitor *mon, const QDict *qdict)
     hmp_handle_error(mon, err);
 }
 
+#ifdef CONFIG_POSIX
 void hmp_getfd(Monitor *mon, const QDict *qdict)
 {
     const char *fdname = qdict_get_str(qdict, "fdname");
@@ -200,6 +201,7 @@ void hmp_getfd(Monitor *mon, const QDict *qdict)
     qmp_getfd(fdname, &err);
     hmp_handle_error(mon, err);
 }
+#endif
 
 void hmp_closefd(Monitor *mon, const QDict *qdict)
 {
diff --git a/hmp-commands.hx b/hmp-commands.hx
index b87c250e23..bb85ee1d26 100644
--- a/hmp-commands.hx
+++ b/hmp-commands.hx
@@ -1486,6 +1486,7 @@ SRST
   Inject an MCE on the given CPU (x86 only).
 ERST
 
+#ifdef CONFIG_POSIX
     {
         .name       = "getfd",
         .args_type  = "fdname:s",
@@ -1501,6 +1502,7 @@ SRST
   mechanism on unix sockets, it is stored using the name *fdname* for
   later use by other monitor commands.
 ERST
+#endif
 
     {
         .name       = "closefd",
-- 
2.39.2



^ permalink raw reply related	[flat|nested] 35+ messages in thread

* Re: [PULL v2 00/25] Win socket patches
  2023-03-13 11:46 [PULL v2 00/25] Win socket patches marcandre.lureau
                   ` (24 preceding siblings ...)
  2023-03-13 11:46 ` [PULL v2 25/25] monitor: restrict command getfd to POSIX hosts marcandre.lureau
@ 2023-03-13 17:09 ` Peter Maydell
  25 siblings, 0 replies; 35+ messages in thread
From: Peter Maydell @ 2023-03-13 17:09 UTC (permalink / raw)
  To: marcandre.lureau
  Cc: qemu-devel, qemu-block, Dr. David Alan Gilbert,
	Daniel P. Berrangé, Philippe Mathieu-Daudé,
	Eric Blake, Samuel Thibault, Hanna Reitz, Stefan Weil,
	Thomas Huth, Fam Zheng, Beraldo Leal, Paolo Bonzini, Jason Wang,
	Michael Roth, Stefan Berger, qemu-arm, Joel Stanley,
	Alex Bennée, Stefan Hajnoczi, Markus Armbruster, Kevin Wolf,
	Laurent Vivier, Wainer dos Santos Moschetta

On Mon, 13 Mar 2023 at 11:46, <marcandre.lureau@redhat.com> wrote:
>
> From: Marc-André Lureau <marcandre.lureau@redhat.com>
>
> The following changes since commit 29c8a9e31a982874ce4e2c15f2bf82d5f8dc3517:
>
>   Merge tag 'linux-user-for-8.0-pull-request' of https://gitlab.com/laurent_vivier/qemu into staging (2023-03-12 10:57:00 +0000)
>
> are available in the Git repository at:
>
>   https://gitlab.com/marcandre.lureau/qemu.git tags/win-socket-pull-request
>
> for you to fetch changes up to 4bf21c7f748bee42b6f4692f8c37a11d1033b2d1:
>
>   monitor: restrict command getfd to POSIX hosts (2023-03-13 15:46:09 +0400)
>
> ----------------------------------------------------------------
> QMP command to import win32 sockets
>
> ----------------------------------------------------------------


Applied, thanks.

Please update the changelog at https://wiki.qemu.org/ChangeLog/8.0
for any user-visible changes.

-- PMM


^ permalink raw reply	[flat|nested] 35+ messages in thread

* Re: [PULL v2 05/25] error: add global &error_warn destination
  2023-03-13 11:46 ` [PULL v2 05/25] error: add global &error_warn destination marcandre.lureau
@ 2023-04-06 13:16   ` Peter Maydell
  2023-04-06 13:17     ` Peter Maydell
  0 siblings, 1 reply; 35+ messages in thread
From: Peter Maydell @ 2023-04-06 13:16 UTC (permalink / raw)
  To: marcandre.lureau
  Cc: qemu-devel, Daniel P. Berrangé, Stefan Berger, Markus Armbruster

On Mon, 13 Mar 2023 at 11:47, <marcandre.lureau@redhat.com> wrote:
>
> From: Marc-André Lureau <marcandre.lureau@redhat.com>
>
> This can help debugging issues or develop, when error handling is
> introduced.
>
> Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
> Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
> Message-Id: <20230221124802.4103554-6-marcandre.lureau@redhat.com>

Hi; Coverity points out that this introduces a use-after-free
(CID 1507493):

> -static void error_handle_fatal(Error **errp, Error *err)
> +static void error_handle(Error **errp, Error *err)
>  {
>      if (errp == &error_abort) {
>          fprintf(stderr, "Unexpected error in %s() at %s:%d:\n",
> @@ -43,6 +44,9 @@ static void error_handle_fatal(Error **errp, Error *err)
>          error_report_err(err);
>          exit(1);
>      }
> +    if (errp == &error_warn) {
> +        warn_report_err(err);
> +    }
>  }

The old error_handle_fatal() either:
 * did not return
 * or it left the passed in 'err' alone

The new error_handle() introduces a new case, which
calls warn_report_err() and returns. warn_report_err()
prints the error and frees 'err'. Neither of the callsites
seems to expect the possibility "error_handle() returned
but 'err' is no longer valid":

>  G_GNUC_PRINTF(6, 0)
> @@ -71,7 +75,7 @@ static void error_setv(Error **errp,
>      err->line = line;
>      err->func = func;
>
> -    error_handle_fatal(errp, err);
> +    error_handle(errp, err);
>      *errp = err;

Here we stuff the now-invalid pointer into *errp
(ie into the global local_error). Probably harmless
but definitely rather odd.

>      errno = saved_errno;
> @@ -284,7 +288,7 @@ void error_propagate(Error **dst_errp, Error *local_err)
>      if (!local_err) {
>          return;
>      }
> -    error_handle_fatal(dst_errp, local_err);
> +    error_handle(dst_errp, local_err);
>      if (dst_errp && !*dst_errp) {
>          *dst_errp = local_err;
>      } else {

Here, if error_warn happens to be NULL then we'll
stuff the freed pointer into it. But if error_warn
is not NULL (eg because we've already had one use of
it) then the 'else' clause here does an error_free(local_err),
which is a double-free.

thanks
-- PMM


^ permalink raw reply	[flat|nested] 35+ messages in thread

* Re: [PULL v2 05/25] error: add global &error_warn destination
  2023-04-06 13:16   ` Peter Maydell
@ 2023-04-06 13:17     ` Peter Maydell
  2023-04-06 14:13       ` Stefan Berger
  0 siblings, 1 reply; 35+ messages in thread
From: Peter Maydell @ 2023-04-06 13:17 UTC (permalink / raw)
  To: marcandre.lureau
  Cc: qemu-devel, Daniel P. Berrangé, Stefan Berger, Markus Armbruster

On Thu, 6 Apr 2023 at 14:16, Peter Maydell <peter.maydell@linaro.org> wrote:
>
> On Mon, 13 Mar 2023 at 11:47, <marcandre.lureau@redhat.com> wrote:
> >
> > From: Marc-André Lureau <marcandre.lureau@redhat.com>
> >
> > This can help debugging issues or develop, when error handling is
> > introduced.
> >
> > Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
> > Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
> > Message-Id: <20230221124802.4103554-6-marcandre.lureau@redhat.com>
>
> Hi; Coverity points out that this introduces a use-after-free
> (CID 1507493):

...and also CID 1508179 (same issue, just one warning about the
callsite in error_setv() and one about the callsite in
error_propagate()).

thanks
-- PMM


^ permalink raw reply	[flat|nested] 35+ messages in thread

* Re: [PULL v2 05/25] error: add global &error_warn destination
  2023-04-06 13:17     ` Peter Maydell
@ 2023-04-06 14:13       ` Stefan Berger
  2023-04-06 14:36         ` Peter Maydell
  2023-04-06 15:17         ` Markus Armbruster
  0 siblings, 2 replies; 35+ messages in thread
From: Stefan Berger @ 2023-04-06 14:13 UTC (permalink / raw)
  To: Peter Maydell, marcandre.lureau
  Cc: qemu-devel, Daniel P. Berrangé, Stefan Berger, Markus Armbruster



On 4/6/23 09:17, Peter Maydell wrote:
> On Thu, 6 Apr 2023 at 14:16, Peter Maydell <peter.maydell@linaro.org> wrote:
>>
>> On Mon, 13 Mar 2023 at 11:47, <marcandre.lureau@redhat.com> wrote:
>>>
>>> From: Marc-André Lureau <marcandre.lureau@redhat.com>
>>>
>>> This can help debugging issues or develop, when error handling is
>>> introduced.
>>>
>>> Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
>>> Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
>>> Message-Id: <20230221124802.4103554-6-marcandre.lureau@redhat.com>
>>
>> Hi; Coverity points out that this introduces a use-after-free
>> (CID 1507493):
> 
> ...and also CID 1508179 (same issue, just one warning about the
> callsite in error_setv() and one about the callsite in
> error_propagate()).
> 
> thanks
> -- PMM
> 

I'll be out starting tomorrow. I don't see Marc-André online.

Would this be acceptable?
It ensures that if error_handle() returns, err has been freed.
In the other two cases a copy is being made of the Error that can then be used after the error_handle() call.


diff --git a/util/error.c b/util/error.c
index 5537245da6..7a2296e969 100644
--- a/util/error.c
+++ b/util/error.c
@@ -46,6 +46,8 @@ static void error_handle(Error **errp, Error *err)
      }
      if (errp == &error_warn) {
          warn_report_err(err);
+    } else {
+        error_free(err);
      }
  }

@@ -55,7 +57,7 @@ static void error_setv(Error **errp,
                         ErrorClass err_class, const char *fmt, va_list ap,
                         const char *suffix)
  {
-    Error *err;
+    Error *err, *err_bak;
      int saved_errno = errno;

      if (errp == NULL) {
@@ -75,8 +77,10 @@ static void error_setv(Error **errp,
      err->line = line;
      err->func = func;

+    err_bak = error_copy(err);
      error_handle(errp, err);
-    *errp = err;
+
+    *errp = err_bak;

      errno = saved_errno;
  }
@@ -285,14 +289,14 @@ void error_free_or_abort(Error **errp)

  void error_propagate(Error **dst_errp, Error *local_err)
  {
+    Error *local_err_bak;
      if (!local_err) {
          return;
      }
+    local_err_bak = error_copy(local_err);
      error_handle(dst_errp, local_err);
      if (dst_errp && !*dst_errp) {
-        *dst_errp = local_err;
-    } else {
-        error_free(local_err);
+        *dst_errp = local_err_bak;
      }
  }



^ permalink raw reply related	[flat|nested] 35+ messages in thread

* Re: [PULL v2 05/25] error: add global &error_warn destination
  2023-04-06 14:13       ` Stefan Berger
@ 2023-04-06 14:36         ` Peter Maydell
  2023-04-06 15:00           ` Stefan Berger
  2023-04-06 15:17         ` Markus Armbruster
  1 sibling, 1 reply; 35+ messages in thread
From: Peter Maydell @ 2023-04-06 14:36 UTC (permalink / raw)
  To: Stefan Berger
  Cc: marcandre.lureau, qemu-devel, Daniel P. Berrangé,
	Stefan Berger, Markus Armbruster

On Thu, 6 Apr 2023 at 15:13, Stefan Berger <stefanb@linux.ibm.com> wrote:
> I'll be out starting tomorrow. I don't see Marc-André online.
>
> Would this be acceptable?
> It ensures that if error_handle() returns, err has been freed.
> In the other two cases a copy is being made of the Error that can then be used after the error_handle() call.

"Not error_warn" is the common case, so it doesn't seem
great to copy the error around like that. My thoughts were
either:
 (1) error_handle() should handle all of the error cases,
like this:

    if (errp == &error_abort) {
       ...
       abort();
    }
    if (errp == &error_fatal) {
       ...
       exit(1);
    }
    if (errp = &error_warn) {
        warn_report_err(err);
    } else if (errp && !*errp) {
        *errp = err;
    } else {
        error_free(err);
    }

and delete the "set *errp" logic from the callers.

(note that error_setv() has done checks already that mean it
will always take the "(errp && !*errp)" path, so we don't need
to special-case for which caller this was.)

(2) error_handle() should return a bool to say whether it's handled
the error entirely and the callsite should do nothing further
with it.

I prefer (1) I think but would defer to people with more
experience with the Error APIs.

thanks
-- PMM


^ permalink raw reply	[flat|nested] 35+ messages in thread

* Re: [PULL v2 05/25] error: add global &error_warn destination
  2023-04-06 14:36         ` Peter Maydell
@ 2023-04-06 15:00           ` Stefan Berger
  2023-04-06 15:04             ` Peter Maydell
  2023-04-06 15:30             ` Marc-André Lureau
  0 siblings, 2 replies; 35+ messages in thread
From: Stefan Berger @ 2023-04-06 15:00 UTC (permalink / raw)
  To: Peter Maydell
  Cc: marcandre.lureau, qemu-devel, Daniel P. Berrangé,
	Stefan Berger, Markus Armbruster



On 4/6/23 10:36, Peter Maydell wrote:
> On Thu, 6 Apr 2023 at 15:13, Stefan Berger <stefanb@linux.ibm.com> wrote:
>> I'll be out starting tomorrow. I don't see Marc-André online.
>>
>> Would this be acceptable?
>> It ensures that if error_handle() returns, err has been freed.
>> In the other two cases a copy is being made of the Error that can then be used after the error_handle() call.
> 
> "Not error_warn" is the common case, so it doesn't seem
> great to copy the error around like that. My thoughts were
> either:
>   (1) error_handle() should handle all of the error cases,
> like this:
> 
>      if (errp == &error_abort) {
>         ...
>         abort();
>      }
>      if (errp == &error_fatal) {
>         ...
>         exit(1);
>      }
>      if (errp = &error_warn) {
>          warn_report_err(err);
>      } else if (errp && !*errp) {
>          *errp = err;
>      } else {
>          error_free(err);
>      }
> 
> and delete the "set *errp" logic from the callers.


Like this?

diff --git a/util/error.c b/util/error.c
index 5537245da6..e5e247209a 100644
--- a/util/error.c
+++ b/util/error.c
@@ -46,6 +46,10 @@ static void error_handle(Error **errp, Error *err)
      }
      if (errp == &error_warn) {
          warn_report_err(err);
+    } else if (errp && !*errp) {
+        *errp = err;
+    } else {
+        error_free(err);
      }
  }

@@ -76,7 +80,6 @@ static void error_setv(Error **errp,
      err->func = func;

      error_handle(errp, err);
-    *errp = err;

      errno = saved_errno;
  }
@@ -289,11 +292,6 @@ void error_propagate(Error **dst_errp, Error *local_err)
          return;
      }
      error_handle(dst_errp, local_err);
-    if (dst_errp && !*dst_errp) {
-        *dst_errp = local_err;
-    } else {
-        error_free(local_err);
-    }
  }

  void error_propagate_prepend(Error **dst_errp, Error *err,



> 
> (note that error_setv() has done checks already that mean it
> will always take the "(errp && !*errp)" path, so we don't need
> to special-case for which caller this was.)
> 
> (2) error_handle() should return a bool to say whether it's handled
> the error entirely and the callsite should do nothing further

> with it.
> 
> I prefer (1) I think but would defer to people with more
> experience with the Error APIs.
> 
> thanks
> -- PMM


^ permalink raw reply related	[flat|nested] 35+ messages in thread

* Re: [PULL v2 05/25] error: add global &error_warn destination
  2023-04-06 15:00           ` Stefan Berger
@ 2023-04-06 15:04             ` Peter Maydell
  2023-04-06 15:30             ` Marc-André Lureau
  1 sibling, 0 replies; 35+ messages in thread
From: Peter Maydell @ 2023-04-06 15:04 UTC (permalink / raw)
  To: Stefan Berger
  Cc: marcandre.lureau, qemu-devel, Daniel P. Berrangé,
	Stefan Berger, Markus Armbruster

On Thu, 6 Apr 2023 at 16:00, Stefan Berger <stefanb@linux.ibm.com> wrote:
>
>
>
> On 4/6/23 10:36, Peter Maydell wrote:
> > On Thu, 6 Apr 2023 at 15:13, Stefan Berger <stefanb@linux.ibm.com> wrote:
> >> I'll be out starting tomorrow. I don't see Marc-André online.
> >>
> >> Would this be acceptable?
> >> It ensures that if error_handle() returns, err has been freed.
> >> In the other two cases a copy is being made of the Error that can then be used after the error_handle() call.
> >
> > "Not error_warn" is the common case, so it doesn't seem
> > great to copy the error around like that. My thoughts were
> > either:
> >   (1) error_handle() should handle all of the error cases,
> > like this:
> >
> >      if (errp == &error_abort) {
> >         ...
> >         abort();
> >      }
> >      if (errp == &error_fatal) {
> >         ...
> >         exit(1);
> >      }
> >      if (errp = &error_warn) {
> >          warn_report_err(err);
> >      } else if (errp && !*errp) {
> >          *errp = err;
> >      } else {
> >          error_free(err);
> >      }
> >
> > and delete the "set *errp" logic from the callers.
>
>
> Like this?
>
> diff --git a/util/error.c b/util/error.c
> index 5537245da6..e5e247209a 100644
> --- a/util/error.c
> +++ b/util/error.c
> @@ -46,6 +46,10 @@ static void error_handle(Error **errp, Error *err)
>       }
>       if (errp == &error_warn) {
>           warn_report_err(err);
> +    } else if (errp && !*errp) {
> +        *errp = err;
> +    } else {
> +        error_free(err);
>       }
>   }
>
> @@ -76,7 +80,6 @@ static void error_setv(Error **errp,
>       err->func = func;
>
>       error_handle(errp, err);
> -    *errp = err;
>
>       errno = saved_errno;
>   }
> @@ -289,11 +292,6 @@ void error_propagate(Error **dst_errp, Error *local_err)
>           return;
>       }
>       error_handle(dst_errp, local_err);
> -    if (dst_errp && !*dst_errp) {
> -        *dst_errp = local_err;
> -    } else {
> -        error_free(local_err);
> -    }
>   }
>
>   void error_propagate_prepend(Error **dst_errp, Error *err,

Yes, that's what I had in mind.

-- PMM


^ permalink raw reply	[flat|nested] 35+ messages in thread

* Re: [PULL v2 05/25] error: add global &error_warn destination
  2023-04-06 14:13       ` Stefan Berger
  2023-04-06 14:36         ` Peter Maydell
@ 2023-04-06 15:17         ` Markus Armbruster
  1 sibling, 0 replies; 35+ messages in thread
From: Markus Armbruster @ 2023-04-06 15:17 UTC (permalink / raw)
  To: Stefan Berger
  Cc: Peter Maydell, marcandre.lureau, qemu-devel,
	Daniel P. Berrangé,
	Stefan Berger

Stefan Berger <stefanb@linux.ibm.com> writes:

> On 4/6/23 09:17, Peter Maydell wrote:
>> On Thu, 6 Apr 2023 at 14:16, Peter Maydell <peter.maydell@linaro.org> wrote:
>>>
>>> On Mon, 13 Mar 2023 at 11:47, <marcandre.lureau@redhat.com> wrote:
>>>>
>>>> From: Marc-André Lureau <marcandre.lureau@redhat.com>
>>>>
>>>> This can help debugging issues or develop, when error handling is
>>>> introduced.
>>>>
>>>> Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
>>>> Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
>>>> Message-Id: <20230221124802.4103554-6-marcandre.lureau@redhat.com>
>>>
>>> Hi; Coverity points out that this introduces a use-after-free
>>> (CID 1507493):
>>
>> ...and also CID 1508179 (same issue, just one warning about the
>> callsite in error_setv() and one about the callsite in
>> error_propagate()).
>>
>> thanks
>> -- PMM
>> 
>
> I'll be out starting tomorrow. I don't see Marc-André online.

I'll also be out starting tomorrow, until April 17.

The patch went in without my review, because I was unable to review it
in time.

As Coverity points out, it broke a design invariant.  Red "rethink this"
flag.  Can't do until I'm back.  Can't review the Stefan's proposed fix
either, because that one needs just as much thinking.

I suggest to treat &error_warn exactly like NULL for the release.

[...]



^ permalink raw reply	[flat|nested] 35+ messages in thread

* Re: [PULL v2 05/25] error: add global &error_warn destination
  2023-04-06 15:00           ` Stefan Berger
  2023-04-06 15:04             ` Peter Maydell
@ 2023-04-06 15:30             ` Marc-André Lureau
  1 sibling, 0 replies; 35+ messages in thread
From: Marc-André Lureau @ 2023-04-06 15:30 UTC (permalink / raw)
  To: Stefan Berger
  Cc: Peter Maydell, qemu-devel, Daniel P. Berrangé,
	Stefan Berger, Markus Armbruster

Hi

On Thu, Apr 6, 2023 at 7:00 PM Stefan Berger <stefanb@linux.ibm.com> wrote:
>
>
>
> On 4/6/23 10:36, Peter Maydell wrote:
> > On Thu, 6 Apr 2023 at 15:13, Stefan Berger <stefanb@linux.ibm.com> wrote:
> >> I'll be out starting tomorrow. I don't see Marc-André online.
> >>
> >> Would this be acceptable?
> >> It ensures that if error_handle() returns, err has been freed.
> >> In the other two cases a copy is being made of the Error that can then be used after the error_handle() call.
> >
> > "Not error_warn" is the common case, so it doesn't seem
> > great to copy the error around like that. My thoughts were
> > either:
> >   (1) error_handle() should handle all of the error cases,
> > like this:
> >
> >      if (errp == &error_abort) {
> >         ...
> >         abort();
> >      }
> >      if (errp == &error_fatal) {
> >         ...
> >         exit(1);
> >      }
> >      if (errp = &error_warn) {
> >          warn_report_err(err);
> >      } else if (errp && !*errp) {
> >          *errp = err;
> >      } else {
> >          error_free(err);
> >      }
> >
> > and delete the "set *errp" logic from the callers.
>
>
> Like this?
>
> diff --git a/util/error.c b/util/error.c
> index 5537245da6..e5e247209a 100644
> --- a/util/error.c
> +++ b/util/error.c
> @@ -46,6 +46,10 @@ static void error_handle(Error **errp, Error *err)
>       }
>       if (errp == &error_warn) {
>           warn_report_err(err);
> +    } else if (errp && !*errp) {
> +        *errp = err;
> +    } else {
> +        error_free(err);
>       }
>   }
>
> @@ -76,7 +80,6 @@ static void error_setv(Error **errp,
>       err->func = func;
>
>       error_handle(errp, err);
> -    *errp = err;
>
>       errno = saved_errno;
>   }
> @@ -289,11 +292,6 @@ void error_propagate(Error **dst_errp, Error *local_err)
>           return;
>       }
>       error_handle(dst_errp, local_err);
> -    if (dst_errp && !*dst_errp) {
> -        *dst_errp = local_err;
> -    } else {
> -        error_free(local_err);
> -    }
>   }
>


looks like a fix to me, send a patch?
thanks

>   void error_propagate_prepend(Error **dst_errp, Error *err,
>
>
>
> >
> > (note that error_setv() has done checks already that mean it
> > will always take the "(errp && !*errp)" path, so we don't need
> > to special-case for which caller this was.)
> >
> > (2) error_handle() should return a bool to say whether it's handled
> > the error entirely and the callsite should do nothing further
>
> > with it.
> >
> > I prefer (1) I think but would defer to people with more
> > experience with the Error APIs.
> >
> > thanks
> > -- PMM
>


-- 
Marc-André Lureau


^ permalink raw reply	[flat|nested] 35+ messages in thread

end of thread, other threads:[~2023-04-06 15:31 UTC | newest]

Thread overview: 35+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2023-03-13 11:46 [PULL v2 00/25] Win socket patches marcandre.lureau
2023-03-13 11:46 ` [PULL v2 01/25] util: drop qemu_fork() marcandre.lureau
2023-03-13 11:46 ` [PULL v2 02/25] tests: use closesocket() marcandre.lureau
2023-03-13 11:46 ` [PULL v2 03/25] io: " marcandre.lureau
2023-03-13 11:46 ` [PULL v2 04/25] tests: add test-error-report marcandre.lureau
2023-03-13 11:46 ` [PULL v2 05/25] error: add global &error_warn destination marcandre.lureau
2023-04-06 13:16   ` Peter Maydell
2023-04-06 13:17     ` Peter Maydell
2023-04-06 14:13       ` Stefan Berger
2023-04-06 14:36         ` Peter Maydell
2023-04-06 15:00           ` Stefan Berger
2023-04-06 15:04             ` Peter Maydell
2023-04-06 15:30             ` Marc-André Lureau
2023-04-06 15:17         ` Markus Armbruster
2023-03-13 11:46 ` [PULL v2 06/25] win32/socket: introduce qemu_socket_select() helper marcandre.lureau
2023-03-13 11:46 ` [PULL v2 07/25] win32/socket: introduce qemu_socket_unselect() helper marcandre.lureau
2023-03-13 11:46 ` [PULL v2 08/25] aio: make aio_set_fd_poll() static to aio-posix.c marcandre.lureau
2023-03-13 11:46 ` [PULL v2 09/25] aio/win32: aio_set_fd_handler() only supports SOCKET marcandre.lureau
2023-03-13 11:46 ` [PULL v2 10/25] main-loop: remove qemu_fd_register(), win32/slirp/socket specific marcandre.lureau
2023-03-13 11:46 ` [PULL v2 11/25] slirp: unregister the win32 SOCKET marcandre.lureau
2023-03-13 11:46 ` [PULL v2 12/25] slirp: open-code qemu_socket_(un)select() marcandre.lureau
2023-03-13 11:46 ` [PULL v2 13/25] win32: avoid mixing SOCKET and file descriptor space marcandre.lureau
2023-03-13 11:46 ` [PULL v2 14/25] os-posix: remove useless ioctlsocket() define marcandre.lureau
2023-03-13 11:46 ` [PULL v2 15/25] win32: replace closesocket() with close() wrapper marcandre.lureau
2023-03-13 11:46 ` [PULL v2 16/25] tests: fix path separator, use g_build_filename() marcandre.lureau
2023-03-13 11:46 ` [PULL v2 17/25] char: do not double-close fd when failing to add client marcandre.lureau
2023-03-13 11:46 ` [PULL v2 18/25] tests/docker: fix a win32 error due to portability marcandre.lureau
2023-03-13 11:46 ` [PULL v2 19/25] osdep: implement qemu_socketpair() for win32 marcandre.lureau
2023-03-13 11:46 ` [PULL v2 20/25] qmp: 'add_client' actually expects sockets marcandre.lureau
2023-03-13 11:46 ` [PULL v2 21/25] monitor: release the lock before calling close() marcandre.lureau
2023-03-13 11:46 ` [PULL v2 22/25] qmp: add 'get-win32-socket' marcandre.lureau
2023-03-13 11:46 ` [PULL v2 23/25] libqtest: make qtest_qmp_add_client work on win32 marcandre.lureau
2023-03-13 11:46 ` [PULL v2 24/25] qtest: enable vnc-display test " marcandre.lureau
2023-03-13 11:46 ` [PULL v2 25/25] monitor: restrict command getfd to POSIX hosts marcandre.lureau
2023-03-13 17:09 ` [PULL v2 00/25] Win socket patches Peter Maydell

This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.