* [PATCH v4 0/3] nbd/client-connection: Fix client returning a closed channel
@ 2026-11-30 12:44 Guillaume Vincke
2026-11-30 12:44 ` [PATCH v4 1/3] " Guillaume Vincke
` (2 more replies)
0 siblings, 3 replies; 14+ messages in thread
From: Guillaume Vincke @ 2026-11-30 12:44 UTC (permalink / raw)
To: qemu-devel
Cc: qemu-block, Eric Blake, Vladimir Sementsov-Ogievskiy, Kevin Wolf,
Hanna Reitz, Guillaume Vincke
Based-on: <20261130111327.178850-1-guillaume.vincke@ovhcloud.com>
NBD client relies on lazy reconnection on error. There is a case where
nbd_co_establish_connection() will hand back a channel disconnected by
its peer. This leads to the request running on the dead channel. When
reconnect-delay is set to 0 (the default), this bug prevents the
nbd-connect thread from running on the first operation. This patch set
addresses this specific case.
Found while searching for a way to force client reconnection to simplify
the resize of idle nodes which will be the subject of another patch set.
v1: https://patchew.org/QEMU/20260925155346.357703-1-guillaume.vincke@ovhcloud.com/
v2: https://patchew.org/QEMU/20261016084136.233836-1-guillaume.vincke@ovhcloud.com/
v3: https://patchew.org/QEMU/20261105164124.249395-1-guillaume.vincke@ovhcloud.com/
v1 -> v2:
- patch 1: Pick up Eric Blake's formatting changes.
- patch 2: Start the connect thread after the NBD server so the test no
longer depends on the 1s connect retry, which made v1 fail in CI. Raise
the connect wait to 1s.
v2 -> v3:
- patch 2: Restrict the test to qcow2. The luks CI failure was the
missing key-secret and the parallels failure was the dirty-image repair
message. Neither was timing.
v3 -> v4:
- patch 1: Add Eric Blake's Reviewed-by.
- patch 2 (new): Detect closed TLS channels. A server may send
close_notify before closing, which the raw socket peek reads as data.
- patch 3: Wait for the connect thread to park with
x-debug-query-nbd-client instead of sleeping. Add a TLS test with
a minimal NBD server that sends close_notify.
Guillaume Vincke (3):
nbd/client-connection: Fix client returning a closed channel
nbd/client-connection: Fix client returning a closed TLS channel
iotests: Add coverage for NBD connect thread start delay
nbd/client-connection.c | 84 +++++++
tests/qemu-iotests/tests/nbd-stale-connection | 70 ++++++
.../tests/nbd-stale-connection.out | 17 ++
.../tests/nbd-stale-tls-connection | 205 ++++++++++++++++++
.../tests/nbd-stale-tls-connection.out | 14 ++
5 files changed, 390 insertions(+)
create mode 100755 tests/qemu-iotests/tests/nbd-stale-connection
create mode 100644 tests/qemu-iotests/tests/nbd-stale-connection.out
create mode 100755 tests/qemu-iotests/tests/nbd-stale-tls-connection
create mode 100644 tests/qemu-iotests/tests/nbd-stale-tls-connection.out
--
2.43.0
^ permalink raw reply [flat|nested] 14+ messages in thread* [PATCH v4 1/3] nbd/client-connection: Fix client returning a closed channel 2026-11-30 12:44 [PATCH v4 0/3] nbd/client-connection: Fix client returning a closed channel Guillaume Vincke @ 2026-11-30 12:44 ` Guillaume Vincke 2026-12-01 17:14 ` Daniel P. Berrangé 2026-11-30 12:44 ` [PATCH v4 2/3] nbd/client-connection: Fix client returning a closed TLS channel Guillaume Vincke 2026-11-30 12:44 ` [PATCH v4 3/3] iotests: Add coverage for NBD connect thread start delay Guillaume Vincke 2 siblings, 1 reply; 14+ messages in thread From: Guillaume Vincke @ 2026-11-30 12:44 UTC (permalink / raw) To: qemu-devel Cc: qemu-block, Eric Blake, Vladimir Sementsov-Ogievskiy, Kevin Wolf, Hanna Reitz, Guillaume Vincke When a server closes the connection after a successful handshake but before running any operations, the channel returned by nbd_co_establish_connection() is the closed one and the connect thread is not started. When configured with reconnect-delay=0 (the default), this situation generates at least two IO errors. The first one happens when trying to issue an operation to the closed socket. The connect thread will be started on the next request, which may happen long after, and will create the second error as nbd_co_establish_connection() returns a NULL channel. Peeking the channel to detect FIN or RST avoids the first IO error and does not delay the starting of the connect thread. Signed-off-by: Guillaume Vincke <guillaume.vincke@ovhcloud.com> Reviewed-by: Eric Blake <eblake@redhat.com> --- nbd/client-connection.c | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/nbd/client-connection.c b/nbd/client-connection.c index 580ebe160b..78caea3c37 100644 --- a/nbd/client-connection.c +++ b/nbd/client-connection.c @@ -296,6 +296,23 @@ void nbd_client_connection_release(NBDClientConnection *conn) } } +/* Only true when the peer closed the channel. Does not detect if dead. */ +static bool nbd_channel_is_closed(QIOChannel *ioc) +{ + char data; + struct iovec iov = { .iov_base = &data, .iov_len = 1 }; + ssize_t len = -1; + + if (!qio_channel_has_feature(ioc, QIO_CHANNEL_FEATURE_READ_MSG_PEEK)) { + return false; + } + + len = qio_channel_readv_full( + ioc, &iov, 1, NULL, NULL, QIO_CHANNEL_READ_FLAG_MSG_PEEK, NULL); + + return len == 0 || (len < 0 && len != QIO_CHANNEL_ERR_BLOCK); +} + /* * Get a new connection in context of @conn: * if the thread is running, wait for completion @@ -317,6 +334,7 @@ nbd_co_establish_connection(NBDClientConnection *conn, NBDExportInfo *info, bool blocking, Error **errp) { QemuThread thread; + QIOChannel *ioc; if (conn->do_negotiation) { assert(info); @@ -330,6 +348,20 @@ nbd_co_establish_connection(NBDClientConnection *conn, NBDExportInfo *info, assert(!conn->wait_co); if (!conn->running) { + if (conn->sioc) { + /* discard if the socket got closed by its peer */ + ioc = QIO_CHANNEL(conn->sioc); + if (!qio_channel_set_blocking(ioc, false, NULL) || + nbd_channel_is_closed(ioc)) { + + qio_channel_close(ioc, NULL); + object_unref(OBJECT(conn->sioc)); + conn->sioc = NULL; + object_unref(OBJECT(conn->ioc)); + conn->ioc = NULL; + } + } + if (conn->sioc) { /* Previous attempt finally succeeded in background */ if (conn->do_negotiation) { -- 2.43.0 ^ permalink raw reply related [flat|nested] 14+ messages in thread
* Re: [PATCH v4 1/3] nbd/client-connection: Fix client returning a closed channel 2026-11-30 12:44 ` [PATCH v4 1/3] " Guillaume Vincke @ 2026-12-01 17:14 ` Daniel P. Berrangé 2026-12-03 12:57 ` guillaume vincke 0 siblings, 1 reply; 14+ messages in thread From: Daniel P. Berrangé @ 2026-12-01 17:14 UTC (permalink / raw) To: Guillaume Vincke Cc: qemu-devel, qemu-block, Eric Blake, Vladimir Sementsov-Ogievskiy, Kevin Wolf, Hanna Reitz On Mon, Nov 30, 2026 at 01:44:42PM +0100, Guillaume Vincke wrote: > When a server closes the connection after a successful handshake but > before running any operations, the channel returned by > nbd_co_establish_connection() is the closed one and the connect thread > is not started. > > When configured with reconnect-delay=0 (the default), this situation > generates at least two IO errors. The first one happens when trying to > issue an operation to the closed socket. The connect thread will be > started on the next request, which may happen long after, and will > create the second error as nbd_co_establish_connection() returns a NULL > channel. > > Peeking the channel to detect FIN or RST avoids the first IO error and > does not delay the starting of the connect thread. > > Signed-off-by: Guillaume Vincke <guillaume.vincke@ovhcloud.com> > Reviewed-by: Eric Blake <eblake@redhat.com> > --- > nbd/client-connection.c | 32 ++++++++++++++++++++++++++++++++ > 1 file changed, 32 insertions(+) > > diff --git a/nbd/client-connection.c b/nbd/client-connection.c > index 580ebe160b..78caea3c37 100644 > --- a/nbd/client-connection.c > +++ b/nbd/client-connection.c > @@ -296,6 +296,23 @@ void nbd_client_connection_release(NBDClientConnection *conn) > } > } > > +/* Only true when the peer closed the channel. Does not detect if dead. */ > +static bool nbd_channel_is_closed(QIOChannel *ioc) > +{ > + char data; > + struct iovec iov = { .iov_base = &data, .iov_len = 1 }; > + ssize_t len = -1; > + > + if (!qio_channel_has_feature(ioc, QIO_CHANNEL_FEATURE_READ_MSG_PEEK)) { > + return false; > + } > + > + len = qio_channel_readv_full( > + ioc, &iov, 1, NULL, NULL, QIO_CHANNEL_READ_FLAG_MSG_PEEK, NULL); > + > + return len == 0 || (len < 0 && len != QIO_CHANNEL_ERR_BLOCK); > +} > + > /* > * Get a new connection in context of @conn: > * if the thread is running, wait for completion > @@ -317,6 +334,7 @@ nbd_co_establish_connection(NBDClientConnection *conn, NBDExportInfo *info, > bool blocking, Error **errp) > { > QemuThread thread; > + QIOChannel *ioc; > > if (conn->do_negotiation) { > assert(info); > @@ -330,6 +348,20 @@ nbd_co_establish_connection(NBDClientConnection *conn, NBDExportInfo *info, > assert(!conn->wait_co); > > if (!conn->running) { > + if (conn->sioc) { > + /* discard if the socket got closed by its peer */ > + ioc = QIO_CHANNEL(conn->sioc); > + if (!qio_channel_set_blocking(ioc, false, NULL) || > + nbd_channel_is_closed(ioc)) { > + > + qio_channel_close(ioc, NULL); > + object_unref(OBJECT(conn->sioc)); > + conn->sioc = NULL; > + object_unref(OBJECT(conn->ioc)); > + conn->ioc = NULL; > + } > + } nbd_channel_is_closed() could return "FALSE", and then the client could go away, before we get to this next part. IOW, peeking at the channel doesn't look like it is inherently fixing anything, instead it is playing with a race condition for when the peer closed the connection. > + > if (conn->sioc) { Identical condition to the newly added one above, so they could be one single condition > /* Previous attempt finally succeeded in background */ > if (conn->do_negotiation) { > -- > 2.43.0 > > > With regards, Daniel -- |: https://berrange.com ~~ https://hachyderm.io/@berrange :| |: https://libvirt.org ~~ https://entangle-photo.org :| |: https://pixelfed.art/berrange ~~ https://fstop138.berrange.com :| ^ permalink raw reply [flat|nested] 14+ messages in thread
* Re: [PATCH v4 1/3] nbd/client-connection: Fix client returning a closed channel 2026-12-01 17:14 ` Daniel P. Berrangé @ 2026-12-03 12:57 ` guillaume vincke 2026-12-03 16:02 ` Daniel P. Berrangé 0 siblings, 1 reply; 14+ messages in thread From: guillaume vincke @ 2026-12-03 12:57 UTC (permalink / raw) To: berrange Cc: qemu-devel, qemu-block, Eric Blake, Vladimir Sementsov-Ogievskiy, Kevin Wolf, Hanna Reitz On 12/1/26 18:14, Daniel P. Berrangé wrote: > On Mon, Nov 30, 2026 at 01:44:42PM +0100, Guillaume Vincke wrote: >> When a server closes the connection after a successful handshake but >> before running any operations, the channel returned by >> nbd_co_establish_connection() is the closed one and the connect thread >> is not started. >> >> When configured with reconnect-delay=0 (the default), this situation >> generates at least two IO errors. The first one happens when trying to >> issue an operation to the closed socket. The connect thread will be >> started on the next request, which may happen long after, and will >> create the second error as nbd_co_establish_connection() returns a NULL >> channel. >> >> Peeking the channel to detect FIN or RST avoids the first IO error and >> does not delay the starting of the connect thread. >> >> Signed-off-by: Guillaume Vincke <guillaume.vincke@ovhcloud.com> >> Reviewed-by: Eric Blake <eblake@redhat.com> >> --- >> nbd/client-connection.c | 32 ++++++++++++++++++++++++++++++++ >> 1 file changed, 32 insertions(+) >> >> diff --git a/nbd/client-connection.c b/nbd/client-connection.c >> index 580ebe160b..78caea3c37 100644 >> --- a/nbd/client-connection.c >> +++ b/nbd/client-connection.c >> @@ -296,6 +296,23 @@ void nbd_client_connection_release(NBDClientConnection *conn) >> } >> } >> >> +/* Only true when the peer closed the channel. Does not detect if dead. */ >> +static bool nbd_channel_is_closed(QIOChannel *ioc) >> +{ >> + char data; >> + struct iovec iov = { .iov_base = &data, .iov_len = 1 }; >> + ssize_t len = -1; >> + >> + if (!qio_channel_has_feature(ioc, QIO_CHANNEL_FEATURE_READ_MSG_PEEK)) { >> + return false; >> + } >> + >> + len = qio_channel_readv_full( >> + ioc, &iov, 1, NULL, NULL, QIO_CHANNEL_READ_FLAG_MSG_PEEK, NULL); >> + >> + return len == 0 || (len < 0 && len != QIO_CHANNEL_ERR_BLOCK); >> +} >> + >> /* >> * Get a new connection in context of @conn: >> * if the thread is running, wait for completion >> @@ -317,6 +334,7 @@ nbd_co_establish_connection(NBDClientConnection *conn, NBDExportInfo *info, >> bool blocking, Error **errp) >> { >> QemuThread thread; >> + QIOChannel *ioc; >> >> if (conn->do_negotiation) { >> assert(info); >> @@ -330,6 +348,20 @@ nbd_co_establish_connection(NBDClientConnection *conn, NBDExportInfo *info, >> assert(!conn->wait_co); >> >> if (!conn->running) { >> + if (conn->sioc) { >> + /* discard if the socket got closed by its peer */ >> + ioc = QIO_CHANNEL(conn->sioc); >> + if (!qio_channel_set_blocking(ioc, false, NULL) || >> + nbd_channel_is_closed(ioc)) { >> + >> + qio_channel_close(ioc, NULL); >> + object_unref(OBJECT(conn->sioc)); >> + conn->sioc = NULL; >> + object_unref(OBJECT(conn->ioc)); >> + conn->ioc = NULL; >> + } >> + } > > nbd_channel_is_closed() could return "FALSE", and then the > client could go away, before we get to this next part. > > IOW, peeking at the channel doesn't look like it is inherently > fixing anything, instead it is playing with a race condition > for when the peer closed the connection. > Thanks for the review. You are right on this. It does not prevent using a channel closed after the check but it considerably reduces the window. Without that patch, we always get a closed channel if the server closes the connection while it is parked. The channel stays parked as long as the device is idle. The race condition you describe represents the short window between the check and the first request. So, the patch addresses the certain failure, not the residual race. > > >> + >> if (conn->sioc) { > > Identical condition to the newly added one above, so they > could be one single condition Will handle that in v5. > >> /* Previous attempt finally succeeded in background */ >> if (conn->do_negotiation) { >> -- >> 2.43.0 >> >> >> > > With regards, > Daniel ^ permalink raw reply [flat|nested] 14+ messages in thread
* Re: [PATCH v4 1/3] nbd/client-connection: Fix client returning a closed channel 2026-12-03 12:57 ` guillaume vincke @ 2026-12-03 16:02 ` Daniel P. Berrangé 2026-12-03 17:17 ` guillaume vincke 0 siblings, 1 reply; 14+ messages in thread From: Daniel P. Berrangé @ 2026-12-03 16:02 UTC (permalink / raw) To: guillaume vincke Cc: qemu-devel, qemu-block, Eric Blake, Vladimir Sementsov-Ogievskiy, Kevin Wolf, Hanna Reitz On Thu, Dec 03, 2026 at 01:57:44PM +0100, guillaume vincke wrote: > On 12/1/26 18:14, Daniel P. Berrangé wrote: > > On Mon, Nov 30, 2026 at 01:44:42PM +0100, Guillaume Vincke wrote: > > > When a server closes the connection after a successful handshake but > > > before running any operations, the channel returned by > > > nbd_co_establish_connection() is the closed one and the connect thread > > > is not started. > > > > > > When configured with reconnect-delay=0 (the default), this situation > > > generates at least two IO errors. The first one happens when trying to > > > issue an operation to the closed socket. The connect thread will be > > > started on the next request, which may happen long after, and will > > > create the second error as nbd_co_establish_connection() returns a NULL > > > channel. > > > > > > Peeking the channel to detect FIN or RST avoids the first IO error and > > > does not delay the starting of the connect thread. > > > > > > Signed-off-by: Guillaume Vincke <guillaume.vincke@ovhcloud.com> > > > Reviewed-by: Eric Blake <eblake@redhat.com> > > > --- > > > nbd/client-connection.c | 32 ++++++++++++++++++++++++++++++++ > > > 1 file changed, 32 insertions(+) > > > > > > diff --git a/nbd/client-connection.c b/nbd/client-connection.c > > > index 580ebe160b..78caea3c37 100644 > > > --- a/nbd/client-connection.c > > > +++ b/nbd/client-connection.c > > > @@ -296,6 +296,23 @@ void nbd_client_connection_release(NBDClientConnection *conn) > > > } > > > } > > > +/* Only true when the peer closed the channel. Does not detect if dead. */ > > > +static bool nbd_channel_is_closed(QIOChannel *ioc) > > > +{ > > > + char data; > > > + struct iovec iov = { .iov_base = &data, .iov_len = 1 }; > > > + ssize_t len = -1; > > > + > > > + if (!qio_channel_has_feature(ioc, QIO_CHANNEL_FEATURE_READ_MSG_PEEK)) { > > > + return false; > > > + } > > > + > > > + len = qio_channel_readv_full( > > > + ioc, &iov, 1, NULL, NULL, QIO_CHANNEL_READ_FLAG_MSG_PEEK, NULL); > > > + > > > + return len == 0 || (len < 0 && len != QIO_CHANNEL_ERR_BLOCK); > > > +} > > > + > > > /* > > > * Get a new connection in context of @conn: > > > * if the thread is running, wait for completion > > > @@ -317,6 +334,7 @@ nbd_co_establish_connection(NBDClientConnection *conn, NBDExportInfo *info, > > > bool blocking, Error **errp) > > > { > > > QemuThread thread; > > > + QIOChannel *ioc; > > > if (conn->do_negotiation) { > > > assert(info); > > > @@ -330,6 +348,20 @@ nbd_co_establish_connection(NBDClientConnection *conn, NBDExportInfo *info, > > > assert(!conn->wait_co); > > > if (!conn->running) { > > > + if (conn->sioc) { > > > + /* discard if the socket got closed by its peer */ > > > + ioc = QIO_CHANNEL(conn->sioc); > > > + if (!qio_channel_set_blocking(ioc, false, NULL) || > > > + nbd_channel_is_closed(ioc)) { > > > + > > > + qio_channel_close(ioc, NULL); > > > + object_unref(OBJECT(conn->sioc)); > > > + conn->sioc = NULL; > > > + object_unref(OBJECT(conn->ioc)); > > > + conn->ioc = NULL; > > > + } > > > + } > > > > nbd_channel_is_closed() could return "FALSE", and then the > > client could go away, before we get to this next part. > > > > IOW, peeking at the channel doesn't look like it is inherently > > fixing anything, instead it is playing with a race condition > > for when the peer closed the connection. > > > > Thanks for the review. > You are right on this. It does not prevent using a channel closed after > the check but it considerably reduces the window. Without that patch, we > always get a closed channel if the server closes the connection while it > is parked. The channel stays parked as long as the device is idle. The > race condition you describe represents the short window between the > check and the first request. So, the patch addresses the certain > failure, not the residual race. I'm still struggling to understand why we need to create all these hacks for detecting EOF by peeking at incoming bytes at only one specific place int he code, when the QIOChannel code has a well defined mechanism to detect it - create a I/O watch and look for G_IO_HUP to be signalled. With regards, Daniel -- |: https://berrange.com ~~ https://hachyderm.io/@berrange :| |: https://libvirt.org ~~ https://entangle-photo.org :| |: https://pixelfed.art/berrange ~~ https://fstop138.berrange.com :| ^ permalink raw reply [flat|nested] 14+ messages in thread
* Re: [PATCH v4 1/3] nbd/client-connection: Fix client returning a closed channel 2026-12-03 16:02 ` Daniel P. Berrangé @ 2026-12-03 17:17 ` guillaume vincke 2026-12-03 17:29 ` Daniel P. Berrangé 2026-12-03 17:31 ` Eric Blake 0 siblings, 2 replies; 14+ messages in thread From: guillaume vincke @ 2026-12-03 17:17 UTC (permalink / raw) To: berrange Cc: qemu-devel, qemu-block, Eric Blake, Vladimir Sementsov-Ogievskiy, Kevin Wolf, Hanna Reitz On 12/3/26 17:02, Daniel P. Berrangé wrote: > On Thu, Dec 03, 2026 at 01:57:44PM +0100, guillaume vincke wrote: >> On 12/1/26 18:14, Daniel P. Berrangé wrote: >>> On Mon, Nov 30, 2026 at 01:44:42PM +0100, Guillaume Vincke wrote: >>>> When a server closes the connection after a successful handshake but >>>> before running any operations, the channel returned by >>>> nbd_co_establish_connection() is the closed one and the connect thread >>>> is not started. >>>> >>>> When configured with reconnect-delay=0 (the default), this situation >>>> generates at least two IO errors. The first one happens when trying to >>>> issue an operation to the closed socket. The connect thread will be >>>> started on the next request, which may happen long after, and will >>>> create the second error as nbd_co_establish_connection() returns a NULL >>>> channel. >>>> >>>> Peeking the channel to detect FIN or RST avoids the first IO error and >>>> does not delay the starting of the connect thread. >>>> >>>> Signed-off-by: Guillaume Vincke <guillaume.vincke@ovhcloud.com> >>>> Reviewed-by: Eric Blake <eblake@redhat.com> >>>> --- >>>> nbd/client-connection.c | 32 ++++++++++++++++++++++++++++++++ >>>> 1 file changed, 32 insertions(+) >>>> >>>> diff --git a/nbd/client-connection.c b/nbd/client-connection.c >>>> index 580ebe160b..78caea3c37 100644 >>>> --- a/nbd/client-connection.c >>>> +++ b/nbd/client-connection.c >>>> @@ -296,6 +296,23 @@ void nbd_client_connection_release(NBDClientConnection *conn) >>>> } >>>> } >>>> +/* Only true when the peer closed the channel. Does not detect if dead. */ >>>> +static bool nbd_channel_is_closed(QIOChannel *ioc) >>>> +{ >>>> + char data; >>>> + struct iovec iov = { .iov_base = &data, .iov_len = 1 }; >>>> + ssize_t len = -1; >>>> + >>>> + if (!qio_channel_has_feature(ioc, QIO_CHANNEL_FEATURE_READ_MSG_PEEK)) { >>>> + return false; >>>> + } >>>> + >>>> + len = qio_channel_readv_full( >>>> + ioc, &iov, 1, NULL, NULL, QIO_CHANNEL_READ_FLAG_MSG_PEEK, NULL); >>>> + >>>> + return len == 0 || (len < 0 && len != QIO_CHANNEL_ERR_BLOCK); >>>> +} >>>> + >>>> /* >>>> * Get a new connection in context of @conn: >>>> * if the thread is running, wait for completion >>>> @@ -317,6 +334,7 @@ nbd_co_establish_connection(NBDClientConnection *conn, NBDExportInfo *info, >>>> bool blocking, Error **errp) >>>> { >>>> QemuThread thread; >>>> + QIOChannel *ioc; >>>> if (conn->do_negotiation) { >>>> assert(info); >>>> @@ -330,6 +348,20 @@ nbd_co_establish_connection(NBDClientConnection *conn, NBDExportInfo *info, >>>> assert(!conn->wait_co); >>>> if (!conn->running) { >>>> + if (conn->sioc) { >>>> + /* discard if the socket got closed by its peer */ >>>> + ioc = QIO_CHANNEL(conn->sioc); >>>> + if (!qio_channel_set_blocking(ioc, false, NULL) || >>>> + nbd_channel_is_closed(ioc)) { >>>> + >>>> + qio_channel_close(ioc, NULL); >>>> + object_unref(OBJECT(conn->sioc)); >>>> + conn->sioc = NULL; >>>> + object_unref(OBJECT(conn->ioc)); >>>> + conn->ioc = NULL; >>>> + } >>>> + } >>> >>> nbd_channel_is_closed() could return "FALSE", and then the >>> client could go away, before we get to this next part. >>> >>> IOW, peeking at the channel doesn't look like it is inherently >>> fixing anything, instead it is playing with a race condition >>> for when the peer closed the connection. >>> >> >> Thanks for the review. >> You are right on this. It does not prevent using a channel closed after >> the check but it considerably reduces the window. Without that patch, we >> always get a closed channel if the server closes the connection while it >> is parked. The channel stays parked as long as the device is idle. The >> race condition you describe represents the short window between the >> check and the first request. So, the patch addresses the certain >> failure, not the residual race. > > I'm still struggling to understand why we need to create all these > hacks for detecting EOF by peeking at incoming bytes at only one > specific place int he code, when the QIOChannel code has a well > defined mechanism to detect it - create a I/O watch and look for > G_IO_HUP to be signalled. > I did not know this was the expected mechanism. Thanks for pointing that out. I understand that you consider the peeking to be a hack. The problem with TLS is that a read stops after each non-data record so a one-shot check cannot tell whether a close_notify is still queued without looking at the underlying socket. Your solution would avoid all that but it requires attaching the parked channel to the AioContext which looks like a bigger change. Would you prefer that solution ? > > With regards, > Daniel ^ permalink raw reply [flat|nested] 14+ messages in thread
* Re: [PATCH v4 1/3] nbd/client-connection: Fix client returning a closed channel 2026-12-03 17:17 ` guillaume vincke @ 2026-12-03 17:29 ` Daniel P. Berrangé 2026-12-03 17:31 ` Eric Blake 1 sibling, 0 replies; 14+ messages in thread From: Daniel P. Berrangé @ 2026-12-03 17:29 UTC (permalink / raw) To: guillaume vincke Cc: qemu-devel, qemu-block, Eric Blake, Vladimir Sementsov-Ogievskiy, Kevin Wolf, Hanna Reitz On Thu, Dec 03, 2026 at 06:17:26PM +0100, guillaume vincke wrote: > On 12/3/26 17:02, Daniel P. Berrangé wrote: > > On Thu, Dec 03, 2026 at 01:57:44PM +0100, guillaume vincke wrote: > > > On 12/1/26 18:14, Daniel P. Berrangé wrote: > > > > On Mon, Nov 30, 2026 at 01:44:42PM +0100, Guillaume Vincke wrote: > > > > > When a server closes the connection after a successful handshake but > > > > > before running any operations, the channel returned by > > > > > nbd_co_establish_connection() is the closed one and the connect thread > > > > > is not started. > > > > > > > > > > When configured with reconnect-delay=0 (the default), this situation > > > > > generates at least two IO errors. The first one happens when trying to > > > > > issue an operation to the closed socket. The connect thread will be > > > > > started on the next request, which may happen long after, and will > > > > > create the second error as nbd_co_establish_connection() returns a NULL > > > > > channel. > > > > > > > > > > Peeking the channel to detect FIN or RST avoids the first IO error and > > > > > does not delay the starting of the connect thread. > > > > > > > > > > Signed-off-by: Guillaume Vincke <guillaume.vincke@ovhcloud.com> > > > > > Reviewed-by: Eric Blake <eblake@redhat.com> > > > > > --- > > > > > nbd/client-connection.c | 32 ++++++++++++++++++++++++++++++++ > > > > > 1 file changed, 32 insertions(+) > > > > > > > > > > diff --git a/nbd/client-connection.c b/nbd/client-connection.c > > > > > index 580ebe160b..78caea3c37 100644 > > > > > --- a/nbd/client-connection.c > > > > > +++ b/nbd/client-connection.c > > > > > @@ -296,6 +296,23 @@ void nbd_client_connection_release(NBDClientConnection *conn) > > > > > } > > > > > } > > > > > +/* Only true when the peer closed the channel. Does not detect if dead. */ > > > > > +static bool nbd_channel_is_closed(QIOChannel *ioc) > > > > > +{ > > > > > + char data; > > > > > + struct iovec iov = { .iov_base = &data, .iov_len = 1 }; > > > > > + ssize_t len = -1; > > > > > + > > > > > + if (!qio_channel_has_feature(ioc, QIO_CHANNEL_FEATURE_READ_MSG_PEEK)) { > > > > > + return false; > > > > > + } > > > > > + > > > > > + len = qio_channel_readv_full( > > > > > + ioc, &iov, 1, NULL, NULL, QIO_CHANNEL_READ_FLAG_MSG_PEEK, NULL); > > > > > + > > > > > + return len == 0 || (len < 0 && len != QIO_CHANNEL_ERR_BLOCK); > > > > > +} > > > > > + > > > > > /* > > > > > * Get a new connection in context of @conn: > > > > > * if the thread is running, wait for completion > > > > > @@ -317,6 +334,7 @@ nbd_co_establish_connection(NBDClientConnection *conn, NBDExportInfo *info, > > > > > bool blocking, Error **errp) > > > > > { > > > > > QemuThread thread; > > > > > + QIOChannel *ioc; > > > > > if (conn->do_negotiation) { > > > > > assert(info); > > > > > @@ -330,6 +348,20 @@ nbd_co_establish_connection(NBDClientConnection *conn, NBDExportInfo *info, > > > > > assert(!conn->wait_co); > > > > > if (!conn->running) { > > > > > + if (conn->sioc) { > > > > > + /* discard if the socket got closed by its peer */ > > > > > + ioc = QIO_CHANNEL(conn->sioc); > > > > > + if (!qio_channel_set_blocking(ioc, false, NULL) || > > > > > + nbd_channel_is_closed(ioc)) { > > > > > + > > > > > + qio_channel_close(ioc, NULL); > > > > > + object_unref(OBJECT(conn->sioc)); > > > > > + conn->sioc = NULL; > > > > > + object_unref(OBJECT(conn->ioc)); > > > > > + conn->ioc = NULL; > > > > > + } > > > > > + } > > > > > > > > nbd_channel_is_closed() could return "FALSE", and then the > > > > client could go away, before we get to this next part. > > > > > > > > IOW, peeking at the channel doesn't look like it is inherently > > > > fixing anything, instead it is playing with a race condition > > > > for when the peer closed the connection. > > > > > > > > > > Thanks for the review. > > > You are right on this. It does not prevent using a channel closed after > > > the check but it considerably reduces the window. Without that patch, we > > > always get a closed channel if the server closes the connection while it > > > is parked. The channel stays parked as long as the device is idle. The > > > race condition you describe represents the short window between the > > > check and the first request. So, the patch addresses the certain > > > failure, not the residual race. > > > > I'm still struggling to understand why we need to create all these > > hacks for detecting EOF by peeking at incoming bytes at only one > > specific place int he code, when the QIOChannel code has a well > > defined mechanism to detect it - create a I/O watch and look for > > G_IO_HUP to be signalled. > > > > I did not know this was the expected mechanism. Thanks for pointing > that out. > I understand that you consider the peeking to be a hack. The problem > with TLS is that a read stops after each non-data record so a one-shot > check cannot tell whether a close_notify is still queued without > looking at the underlying socket. Your solution would avoid all that > but it requires attaching the parked channel to the AioContext which > looks like a bigger change. Would you prefer that solution ? I can just say that's the recommended approach from the I/O channel API design. I don't know enough about the block/nbd code to give advice on the specific challenges/tradeoffs of integration. So I'll defer to Eric to give an opinion on this alternative implementation idea. With regards, Daniel -- |: https://berrange.com ~~ https://hachyderm.io/@berrange :| |: https://libvirt.org ~~ https://entangle-photo.org :| |: https://pixelfed.art/berrange ~~ https://fstop138.berrange.com :| ^ permalink raw reply [flat|nested] 14+ messages in thread
* Re: [PATCH v4 1/3] nbd/client-connection: Fix client returning a closed channel 2026-12-03 17:17 ` guillaume vincke 2026-12-03 17:29 ` Daniel P. Berrangé @ 2026-12-03 17:31 ` Eric Blake 1 sibling, 0 replies; 14+ messages in thread From: Eric Blake @ 2026-12-03 17:31 UTC (permalink / raw) To: guillaume vincke Cc: berrange, qemu-devel, qemu-block, Vladimir Sementsov-Ogievskiy, Kevin Wolf, Hanna Reitz On Thu, Dec 03, 2026 at 06:17:26PM +0100, guillaume vincke wrote: > > I'm still struggling to understand why we need to create all these > > hacks for detecting EOF by peeking at incoming bytes at only one > > specific place int he code, when the QIOChannel code has a well > > defined mechanism to detect it - create a I/O watch and look for > > G_IO_HUP to be signalled. > > > > I did not know this was the expected mechanism. Thanks for pointing > that out. > I understand that you consider the peeking to be a hack. The problem > with TLS is that a read stops after each non-data record so a one-shot > check cannot tell whether a close_notify is still queued without > looking at the underlying socket. Your solution would avoid all that > but it requires attaching the parked channel to the AioContext which > looks like a bigger change. Would you prefer that solution ? I also admit to not being aware enough of G_IO_HUP to have been able to suggest it while reviewing earlier versions. But I would much rather centralize as much knowledge as we can in the io/ directory, rather than having to special-case things in the nbd/ directory. Associating the handshake with the right AioContext seems like the right approach to pursue, even if it requires a bigger change to get there. -- Eric Blake, Principal Software Engineer Red Hat, Inc. Virtualization: qemu.org | libguestfs.org ^ permalink raw reply [flat|nested] 14+ messages in thread
* [PATCH v4 2/3] nbd/client-connection: Fix client returning a closed TLS channel 2026-11-30 12:44 [PATCH v4 0/3] nbd/client-connection: Fix client returning a closed channel Guillaume Vincke 2026-11-30 12:44 ` [PATCH v4 1/3] " Guillaume Vincke @ 2026-11-30 12:44 ` Guillaume Vincke 2026-12-01 16:23 ` Eric Blake 2026-11-30 12:44 ` [PATCH v4 3/3] iotests: Add coverage for NBD connect thread start delay Guillaume Vincke 2 siblings, 1 reply; 14+ messages in thread From: Guillaume Vincke @ 2026-11-30 12:44 UTC (permalink / raw) To: qemu-devel Cc: qemu-block, Eric Blake, Vladimir Sementsov-Ogievskiy, Kevin Wolf, Hanna Reitz, Guillaume Vincke The previous patch adds a verification on the client connection parked channel to reconnect it when closed instead of returning it. That patch handles plain channels but fails TLS as a server may send a close_notify, or TLS 1.3 records before closing, leaving bytes in the socket and reporting the closed channel as alive. Add the nbd_idle_tls_channel_is_closed() function which is the TLS counterpart of nbd_channel_is_closed(). As gnutls handles one record per read, it reads until the socket is empty, to reach a close queued behind other records. The fact that it needs to process the whole content makes this function only safe when the channel is idle, which is our case because the parked channel is negotiated and has not carried any request yet. The nbd_parked_channel_is_closed() function is also added to switch between the two cases. Signed-off-by: Guillaume Vincke <guillaume.vincke@ovhcloud.com> --- nbd/client-connection.c | 54 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 53 insertions(+), 1 deletion(-) diff --git a/nbd/client-connection.c b/nbd/client-connection.c index 78caea3c37..0a8a0d836d 100644 --- a/nbd/client-connection.c +++ b/nbd/client-connection.c @@ -313,6 +313,58 @@ static bool nbd_channel_is_closed(QIOChannel *ioc) return len == 0 || (len < 0 && len != QIO_CHANNEL_ERR_BLOCK); } +/* + * Only called on a non-blocking channel while the thread isn't running. + * Only true when the peer closed the channel. Does not detect if dead. + */ +static bool nbd_idle_tls_channel_is_closed(QIOChannelTLS *tioc) +{ + char data; + struct iovec iov = { .iov_base = &data, .iov_len = 1 }; + QIOChannel *ioc = QIO_CHANNEL(tioc); + ssize_t len; + + for (;;) { + if (qio_channel_readv(ioc, &iov, 1, NULL) != QIO_CHANNEL_ERR_BLOCK) { + /* Reached EOF, got an error or got unexpected data */ + return true; + } + + len = qio_channel_readv_full(tioc->master, + &iov, + 1, + NULL, + NULL, + QIO_CHANNEL_READ_FLAG_MSG_PEEK, + NULL); + if (len == QIO_CHANNEL_ERR_BLOCK) { + return false; + } + /* Channel is not empty. Continue with the next record */ + } +} + +/* + * Called with a non-blocking channel, conn->mutex held and the thread not + * running. + * Only true when the peer closed the channel. Does not detect if dead. + */ +static bool nbd_parked_channel_is_closed(NBDClientConnection *conn) +{ + if (conn->ioc) { + /* + * To check if a TLS channel is closed, we need it to be idle. + * If do_negotiation is false, the server already sent the greetings + * but the client did not handle it. + * An assert is safe because at the moment, a TLS channel cannot be + * initialized without do_negotiation. + */ + assert(conn->do_negotiation); + return nbd_idle_tls_channel_is_closed(QIO_CHANNEL_TLS(conn->ioc)); + } + return nbd_channel_is_closed(QIO_CHANNEL(conn->sioc)); +} + /* * Get a new connection in context of @conn: * if the thread is running, wait for completion @@ -352,7 +404,7 @@ nbd_co_establish_connection(NBDClientConnection *conn, NBDExportInfo *info, /* discard if the socket got closed by its peer */ ioc = QIO_CHANNEL(conn->sioc); if (!qio_channel_set_blocking(ioc, false, NULL) || - nbd_channel_is_closed(ioc)) { + nbd_parked_channel_is_closed(conn)) { qio_channel_close(ioc, NULL); object_unref(OBJECT(conn->sioc)); -- 2.43.0 ^ permalink raw reply related [flat|nested] 14+ messages in thread
* Re: [PATCH v4 2/3] nbd/client-connection: Fix client returning a closed TLS channel 2026-11-30 12:44 ` [PATCH v4 2/3] nbd/client-connection: Fix client returning a closed TLS channel Guillaume Vincke @ 2026-12-01 16:23 ` Eric Blake 0 siblings, 0 replies; 14+ messages in thread From: Eric Blake @ 2026-12-01 16:23 UTC (permalink / raw) To: Guillaume Vincke Cc: qemu-devel, qemu-block, Vladimir Sementsov-Ogievskiy, Kevin Wolf, Hanna Reitz On Mon, Nov 30, 2026 at 01:44:43PM +0100, Guillaume Vincke wrote: > The previous patch adds a verification on the client connection parked > channel to reconnect it when closed instead of returning it. That patch > handles plain channels but fails TLS as a server may send a > close_notify, or TLS 1.3 records before closing, leaving bytes in the > socket and reporting the closed channel as alive. > > Add the nbd_idle_tls_channel_is_closed() function which is the TLS > counterpart of nbd_channel_is_closed(). As gnutls handles one record > per read, it reads until the socket is empty, to reach a close queued > behind other records. The fact that it needs to process the whole > content makes this function only safe when the channel is idle, which > is our case because the parked channel is negotiated and has not > carried any request yet. > > The nbd_parked_channel_is_closed() function is also added to switch > between the two cases. > > Signed-off-by: Guillaume Vincke <guillaume.vincke@ovhcloud.com> > --- > nbd/client-connection.c | 54 ++++++++++++++++++++++++++++++++++++++++- > 1 file changed, 53 insertions(+), 1 deletion(-) > > diff --git a/nbd/client-connection.c b/nbd/client-connection.c > index 78caea3c37..0a8a0d836d 100644 > --- a/nbd/client-connection.c > +++ b/nbd/client-connection.c > @@ -313,6 +313,58 @@ static bool nbd_channel_is_closed(QIOChannel *ioc) > return len == 0 || (len < 0 && len != QIO_CHANNEL_ERR_BLOCK); > } > > +/* > + * Only called on a non-blocking channel while the thread isn't running. > + * Only true when the peer closed the channel. Does not detect if dead. > + */ > +static bool nbd_idle_tls_channel_is_closed(QIOChannelTLS *tioc) > +{ > + char data; > + struct iovec iov = { .iov_base = &data, .iov_len = 1 }; > + QIOChannel *ioc = QIO_CHANNEL(tioc); > + ssize_t len; > + > + for (;;) { > + if (qio_channel_readv(ioc, &iov, 1, NULL) != QIO_CHANNEL_ERR_BLOCK) { > + /* Reached EOF, got an error or got unexpected data */ > + return true; > + } So if I understand correctly, this ignores whatever data byte was actually read, if any, on the grounds that if there WERE a data byte at this point in the protocol the server is not doing what we expect - during handshake, the server should not be sending us data bytes except in response to our queries, but we are idle so no query is outstanding. The reason we have to try a read, even though we will be ignoring any byte, is that the TLS code may be processing out-of-band data that was present on the line but does not show up as data bytes to this consumption endpoint (such as the out-of-band request to close the channel). Reviewed-by: Eric Blake <eblake@redhat.com> > + > + len = qio_channel_readv_full(tioc->master, > + &iov, > + 1, > + NULL, > + NULL, > + QIO_CHANNEL_READ_FLAG_MSG_PEEK, > + NULL); > + if (len == QIO_CHANNEL_ERR_BLOCK) { > + return false; > + } > + /* Channel is not empty. Continue with the next record */ > + } > +} > + > +/* > + * Called with a non-blocking channel, conn->mutex held and the thread not > + * running. > + * Only true when the peer closed the channel. Does not detect if dead. > + */ > +static bool nbd_parked_channel_is_closed(NBDClientConnection *conn) > +{ > + if (conn->ioc) { > + /* > + * To check if a TLS channel is closed, we need it to be idle. > + * If do_negotiation is false, the server already sent the greetings > + * but the client did not handle it. > + * An assert is safe because at the moment, a TLS channel cannot be > + * initialized without do_negotiation. > + */ > + assert(conn->do_negotiation); > + return nbd_idle_tls_channel_is_closed(QIO_CHANNEL_TLS(conn->ioc)); > + } > + return nbd_channel_is_closed(QIO_CHANNEL(conn->sioc)); > +} > + > /* > * Get a new connection in context of @conn: > * if the thread is running, wait for completion > @@ -352,7 +404,7 @@ nbd_co_establish_connection(NBDClientConnection *conn, NBDExportInfo *info, > /* discard if the socket got closed by its peer */ > ioc = QIO_CHANNEL(conn->sioc); > if (!qio_channel_set_blocking(ioc, false, NULL) || > - nbd_channel_is_closed(ioc)) { > + nbd_parked_channel_is_closed(conn)) { > > qio_channel_close(ioc, NULL); > object_unref(OBJECT(conn->sioc)); > -- > 2.43.0 > -- Eric Blake, Principal Software Engineer Red Hat, Inc. Virtualization: qemu.org | libguestfs.org ^ permalink raw reply [flat|nested] 14+ messages in thread
* [PATCH v4 3/3] iotests: Add coverage for NBD connect thread start delay 2026-11-30 12:44 [PATCH v4 0/3] nbd/client-connection: Fix client returning a closed channel Guillaume Vincke 2026-11-30 12:44 ` [PATCH v4 1/3] " Guillaume Vincke 2026-11-30 12:44 ` [PATCH v4 2/3] nbd/client-connection: Fix client returning a closed TLS channel Guillaume Vincke @ 2026-11-30 12:44 ` Guillaume Vincke 2026-12-01 17:05 ` Eric Blake 2 siblings, 1 reply; 14+ messages in thread From: Guillaume Vincke @ 2026-11-30 12:44 UTC (permalink / raw) To: qemu-devel Cc: qemu-block, Eric Blake, Vladimir Sementsov-Ogievskiy, Kevin Wolf, Hanna Reitz, Guillaume Vincke Test the connect thread starting condition with reconnect-delay=0 when the server disconnects after a successful handshake but before running operations. Prior to the change to nbd_co_establish_connection(), this test would demonstrate two I/O errors. The tests 264 and 277 covering reconnection do not use reconnect-delay=0 so this case is not exercised. Add a test that provokes multiple errors in order to put an NBD client in the above-mentioned situation and shows that the first operation starts the connect thread and leads to successful subsequent I/O. Add a second test that runs the same actions on a TLS-backed connection. When qemu-nbd closes, it leaves nothing in the socket, so the closed channel is already detected. As other NBD servers send a close_notify before closing, this test uses a minimal custom NBD server to mimic them. Before shutting it down, the server socket is set to non-blocking to avoid waiting for a close_notify response from the client, as it will never arrive from a parked channel. Signed-off-by: Guillaume Vincke <guillaume.vincke@ovhcloud.com> --- tests/qemu-iotests/tests/nbd-stale-connection | 70 ++++++ .../tests/nbd-stale-connection.out | 17 ++ .../tests/nbd-stale-tls-connection | 205 ++++++++++++++++++ .../tests/nbd-stale-tls-connection.out | 14 ++ 4 files changed, 306 insertions(+) create mode 100755 tests/qemu-iotests/tests/nbd-stale-connection create mode 100644 tests/qemu-iotests/tests/nbd-stale-connection.out create mode 100755 tests/qemu-iotests/tests/nbd-stale-tls-connection create mode 100644 tests/qemu-iotests/tests/nbd-stale-tls-connection.out diff --git a/tests/qemu-iotests/tests/nbd-stale-connection b/tests/qemu-iotests/tests/nbd-stale-connection new file mode 100755 index 0000000000..5f559fa22d --- /dev/null +++ b/tests/qemu-iotests/tests/nbd-stale-connection @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +# group: quick +# +# Test the NBD client stale channel discard +# +# Copyright (C) 2026 OVHcloud +# +# SPDX-License-Identifier: GPL-2.0-or-later + +import time +import iotests + + +iotests.script_initialize(supported_fmts=['qcow2']) +nbd_sock = iotests.file_path('nbd-sock', base_dir=iotests.sock_dir) +disk = iotests.file_path('disk') +iotests.qemu_img_create('-f', iotests.imgfmt, disk, '1M') + +def wait_for_parked_connection(virtm, node_name): + with iotests.Timeout(30, "connect-thread did not reach 'parked' state"): + while True: + client = virtm.qmp('x-debug-query-nbd-client', node_name=node_name) + if client['return'].get('connector', {}).get('state') == 'parked': + return + time.sleep(0.1) + + +with iotests.VM() as vm: + + vm.launch() + + with iotests.qemu_nbd_popen('-k', nbd_sock, '-f', iotests.imgfmt, disk): + vm.cmd('blockdev-add', { + 'driver': 'nbd', + 'node-name': 'nbd0', + 'server': {'type': 'unix', 'path': nbd_sock}, + }) + iotests.log('=== NBD Device connected ===') + iotests.log( + vm.qmp('x-qemu-io', device='nbd0', command='write -P 0x5a 0 64k')) + + iotests.log('=== NBD server down. Detect the break and start the connect ' + 'thread ===') + # client was in CONNECTED state a new operation updates to CONNECTING + iotests.log( + vm.qmp('x-qemu-io', device='nbd0', command='write -P 0x5a 0 64k')) + + with iotests.qemu_nbd_popen('-k', nbd_sock, '-f', iotests.imgfmt, disk): + iotests.log('=== NBD server up. Wait for the connect thread to park ' + 'the channel ===') + # in CONNECTING, the operation starts the connect thread + iotests.log( + vm.qmp('x-qemu-io', device='nbd0', command='write -P 0x5a 0 64k')) + # wait for the connect thread to get a new channel and stop + wait_for_parked_connection(vm, 'nbd0') + + iotests.log('=== NBD server down. The parked channel is closed ===') + + with iotests.qemu_nbd_popen('-k', nbd_sock, '-f', iotests.imgfmt, disk): + iotests.log('=== NBD server up. Restart the connect thread ===') + # operation will determine that the channel got closed and restart the + # connect thread + iotests.log( + vm.qmp('x-qemu-io', device='nbd0', command='write -P 0x5a 0 64k')) + # Wait for it to succeed + iotests.log('=== Wait for the connect thread to park the new channel. ' + 'Subsequent operations are successful ===') + wait_for_parked_connection(vm, 'nbd0') + iotests.log( + vm.qmp('x-qemu-io', device='nbd0', command='write -P 0x5a 0 64k')) diff --git a/tests/qemu-iotests/tests/nbd-stale-connection.out b/tests/qemu-iotests/tests/nbd-stale-connection.out new file mode 100644 index 0000000000..065ba329e9 --- /dev/null +++ b/tests/qemu-iotests/tests/nbd-stale-connection.out @@ -0,0 +1,17 @@ +Start NBD server +=== NBD Device connected === +{"return": {}} +Kill NBD server +=== NBD server down. Detect the break and start the connect thread === +{"error": {"class": "GenericError", "desc": "write failed: Input/output error"}} +Start NBD server +=== NBD server up. Wait for the connect thread to park the channel === +{"error": {"class": "GenericError", "desc": "write failed: Input/output error"}} +Kill NBD server +=== NBD server down. The parked channel is closed === +Start NBD server +=== NBD server up. Restart the connect thread === +{"error": {"class": "GenericError", "desc": "write failed: Input/output error"}} +=== Wait for the connect thread to park the new channel. Subsequent operations are successful === +{"return": {}} +Kill NBD server diff --git a/tests/qemu-iotests/tests/nbd-stale-tls-connection b/tests/qemu-iotests/tests/nbd-stale-tls-connection new file mode 100755 index 0000000000..88bfcd9560 --- /dev/null +++ b/tests/qemu-iotests/tests/nbd-stale-tls-connection @@ -0,0 +1,205 @@ +#!/usr/bin/env python3 +# group: quick +# +# Test the NBD client stale TLS-backed channel discard +# +# Copyright (C) 2026 OVHcloud +# +# SPDX-License-Identifier: GPL-2.0-or-later + +import atexit +import os +import shutil +import socket +import ssl +import struct +import subprocess +import threading +import time + +import iotests + + +iotests.script_initialize(supported_fmts=['qcow2']) +if shutil.which('openssl') is None: + iotests.notrun('openssl not found') +nbd_sock = iotests.file_path('nbd-sock', base_dir=iotests.sock_dir) +disk = iotests.file_path('disk') +iotests.qemu_img_create('-f', iotests.imgfmt, disk, '1M') +volume_size = 1 * 1024 * 1024 + +tls_dir = os.path.join(iotests.test_dir, 'tls') +os.mkdir(tls_dir) +atexit.register(shutil.rmtree, tls_dir, True) + + +def openssl_req(*args): + common = ['openssl', + 'req', '-x509', + '-newkey', 'ed25519', + '-nodes', + '-days', '1'] + cmd = common + list(args) + subprocess.run(cmd, check=True, cwd=tls_dir, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + + +openssl_req('-subj', '/CN=ca', + '-keyout', 'ca-key.pem', + '-out', 'ca-cert.pem') +openssl_req('-CA', 'ca-cert.pem', + '-CAkey', 'ca-key.pem', + '-subj', '/CN=localhost', + '-addext', 'basicConstraints=CA:FALSE', + '-keyout', 'server-key.pem', + '-out', 'server-cert.pem') +tls_object = ( + f'tls-creds-x509,id=tls0,endpoint=server,dir={tls_dir},verify-peer=off' +) + + +def recv_exact(conn, length): + buff = b'' + while len(buff) < length: + chunk = conn.recv(length - len(buff)) + if not chunk: + raise ConnectionError("Failed to read") + buff += chunk + return buff + + +class MockTLSNBDServer: + NBD_INIT_MAGIC = 0x4e42444d41474943 # "NBDMAGIC" + NBD_OPTS_MAGIC = 0x49484156454f5054 # "IHAVEOPT" + NBD_REP_MAGIC = 0x0003e889045565a9 + NBD_FLAG_FIXED_NEWSTYLE = 1 + NBD_FLAG_NO_ZEROES = 2 + NBD_OPT_STARTTLS = 5 + NBD_OPT_GO = 7 + NBD_REP_ACK = 1 + NBD_REP_INFO = 3 + NBD_REP_ERR_UNSUP = 0x80000001 # (1 << 31) | 1 + NBD_INFO_EXPORT = 0 + NBD_FLAG_HAS_FLAGS = 1 + + def __init__(self): + self._thread = threading.Thread(target=self.run) + self._close = threading.Event() + self._sock = socket.socket(socket.AF_UNIX) + self._ssl_ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + self._ssl_ctx.load_cert_chain(os.path.join(tls_dir, 'server-cert.pem'), + os.path.join(tls_dir, 'server-key.pem')) + + def __enter__(self): + if os.path.exists(nbd_sock): + os.remove(nbd_sock) + self._sock.bind(nbd_sock) + self._sock.listen(1) + self._thread.start() + return self + + def __exit__(self, exc_type, exc, tb): + self._close.set() + self._thread.join() + os.remove(nbd_sock) + + @staticmethod + def send_reply(conn, opt, resp, data=b''): + conn.sendall(struct.pack( + '>QIII', MockTLSNBDServer.NBD_REP_MAGIC, + opt, resp, len(data)) + data) + + def run(self): + conn, _ = self._sock.accept() + conn.sendall(struct.pack( + '>QQH', self.NBD_INIT_MAGIC, self.NBD_OPTS_MAGIC, + self.NBD_FLAG_FIXED_NEWSTYLE | self.NBD_FLAG_NO_ZEROES)) + recv_exact(conn, 4) + while True: + _, opt, length = struct.unpack('>QII', recv_exact(conn, 16)) + recv_exact(conn, length) + + if opt == self.NBD_OPT_STARTTLS: + self.send_reply(conn, opt, self.NBD_REP_ACK) + conn = self._ssl_ctx.wrap_socket(conn, server_side=True) + elif opt == self.NBD_OPT_GO: + data = struct.pack( + '>HQH', self.NBD_INFO_EXPORT, + volume_size, self.NBD_FLAG_HAS_FLAGS) + self.send_reply(conn, opt, self.NBD_REP_INFO, data) + self.send_reply(conn, opt, self.NBD_REP_ACK) + break + else: + self.send_reply(conn, opt, self.NBD_REP_ERR_UNSUP) + + conn.setblocking(False) # don't wait for the peer's close_notify + self._close.wait() + try: + conn.unwrap() + except ssl.SSLWantReadError: + # a parked channel does not reply + pass + conn.close() + self._sock.close() + + +def wait_for_parked_connection(virtm, node_name): + with iotests.Timeout(30, "connect-thread did not reach 'parked' state"): + while True: + client = virtm.qmp('x-debug-query-nbd-client', node_name=node_name) + if client['return'].get('connector', {}).get('state') == 'parked': + return + time.sleep(0.1) + + +with iotests.VM() as vm: + vm.add_object(f"tls-creds-x509,id=tls0,endpoint=client,dir={tls_dir}") + vm.launch() + + with iotests.qemu_nbd_popen('-k', nbd_sock, + '-f', iotests.imgfmt, + '--object', tls_object, + '--tls-creds', 'tls0', + disk): + vm.cmd('blockdev-add', { + 'driver': 'nbd', + 'node-name': 'nbd0', + 'server': {'type': 'unix', 'path': nbd_sock}, + 'tls-creds': 'tls0', + 'tls-hostname': 'localhost', + }) + iotests.log('=== NBD Device connected ===') + iotests.log( + vm.qmp('x-qemu-io', device='nbd0', command='write -P 0x5a 0 64k')) + + iotests.log('=== NBD server down. Detect the break and start the connect ' + 'thread ===') + # client was in CONNECTED state a new operation updates to CONNECTING + iotests.log( + vm.qmp('x-qemu-io', device='nbd0', command='write -P 0x5a 0 64k')) + + with MockTLSNBDServer(): + iotests.log('=== Mock NBD server up ===') + # in CONNECTING, the operation starts the connect thread + iotests.log( + vm.qmp('x-qemu-io', device='nbd0', command='write -P 0x5a 0 64k')) + # wait for the connect thread to get a new channel and stop + wait_for_parked_connection(vm, 'nbd0') + + iotests.log('=== Mock NBD server down. `close_notify` sent ===') + + # reconnect qemu nbd + with iotests.qemu_nbd_popen('-k', nbd_sock, + '-f', iotests.imgfmt, + '--object', tls_object, + '--tls-creds', 'tls0', + disk): + iotests.log('=== NBD server up ===') + # operation will determine that the channel got closed and restart the + # connect thread + iotests.log( + vm.qmp('x-qemu-io', device='nbd0', command='write -P 0x5a 0 64k')) + wait_for_parked_connection(vm, 'nbd0') + # next operation succeeds + iotests.log( + vm.qmp('x-qemu-io', device='nbd0', command='write -P 0x5a 0 64k')) diff --git a/tests/qemu-iotests/tests/nbd-stale-tls-connection.out b/tests/qemu-iotests/tests/nbd-stale-tls-connection.out new file mode 100644 index 0000000000..a900453519 --- /dev/null +++ b/tests/qemu-iotests/tests/nbd-stale-tls-connection.out @@ -0,0 +1,14 @@ +Start NBD server +=== NBD Device connected === +{"return": {}} +Kill NBD server +=== NBD server down. Detect the break and start the connect thread === +{"error": {"class": "GenericError", "desc": "write failed: Input/output error"}} +=== Mock NBD server up === +{"error": {"class": "GenericError", "desc": "write failed: Input/output error"}} +=== Mock NBD server down. `close_notify` sent === +Start NBD server +=== NBD server up === +{"error": {"class": "GenericError", "desc": "write failed: Input/output error"}} +{"return": {}} +Kill NBD server -- 2.43.0 ^ permalink raw reply related [flat|nested] 14+ messages in thread
* Re: [PATCH v4 3/3] iotests: Add coverage for NBD connect thread start delay 2026-11-30 12:44 ` [PATCH v4 3/3] iotests: Add coverage for NBD connect thread start delay Guillaume Vincke @ 2026-12-01 17:05 ` Eric Blake 2026-12-03 15:31 ` guillaume vincke 0 siblings, 1 reply; 14+ messages in thread From: Eric Blake @ 2026-12-01 17:05 UTC (permalink / raw) To: Guillaume Vincke Cc: qemu-devel, qemu-block, Vladimir Sementsov-Ogievskiy, Kevin Wolf, Hanna Reitz On Mon, Nov 30, 2026 at 01:44:44PM +0100, Guillaume Vincke wrote: > Test the connect thread starting condition with reconnect-delay=0 when > the server disconnects after a successful handshake but before running > operations. Prior to the change to nbd_co_establish_connection(), this > test would demonstrate two I/O errors. The tests 264 and 277 covering > reconnection do not use reconnect-delay=0 so this case is not exercised. > > Add a test that provokes multiple errors in order to put an NBD client > in the above-mentioned situation and shows that the first operation > starts the connect thread and leads to successful subsequent I/O. > > Add a second test that runs the same actions on a TLS-backed > connection. When qemu-nbd closes, it leaves nothing in the socket, so > the closed channel is already detected. As other NBD servers send a s/send/may send/ > close_notify before closing, this test uses a minimal custom NBD server > to mimic them. Before shutting it down, the server socket is set to > non-blocking to avoid waiting for a close_notify response from the > client, as it will never arrive from a parked channel. > > Signed-off-by: Guillaume Vincke <guillaume.vincke@ovhcloud.com> > --- > tests/qemu-iotests/tests/nbd-stale-connection | 70 ++++++ > .../tests/nbd-stale-connection.out | 17 ++ > .../tests/nbd-stale-tls-connection | 205 ++++++++++++++++++ > .../tests/nbd-stale-tls-connection.out | 14 ++ > 4 files changed, 306 insertions(+) > create mode 100755 tests/qemu-iotests/tests/nbd-stale-connection > create mode 100644 tests/qemu-iotests/tests/nbd-stale-connection.out > create mode 100755 tests/qemu-iotests/tests/nbd-stale-tls-connection > create mode 100644 tests/qemu-iotests/tests/nbd-stale-tls-connection.out Tested-by: Eric Blake <eblake@redhat.com> > > diff --git a/tests/qemu-iotests/tests/nbd-stale-connection b/tests/qemu-iotests/tests/nbd-stale-connection > new file mode 100755 > index 0000000000..5f559fa22d > --- /dev/null > +++ b/tests/qemu-iotests/tests/nbd-stale-connection > @@ -0,0 +1,70 @@ > +#!/usr/bin/env python3 > +# group: quick > +++ b/tests/qemu-iotests/tests/nbd-stale-tls-connection > @@ -0,0 +1,205 @@ > +#!/usr/bin/env python3 > +# group: quick For both tests, why not also in auto? > +# > +# Test the NBD client stale TLS-backed channel discard > +# > +# Copyright (C) 2026 OVHcloud > +# > +# SPDX-License-Identifier: GPL-2.0-or-later > + > +import atexit > +import os > +import shutil > +import socket > +import ssl > +import struct > +import subprocess > +import threading > +import time > + > +import iotests > + > + > +iotests.script_initialize(supported_fmts=['qcow2']) > +if shutil.which('openssl') is None: > + iotests.notrun('openssl not found') > +nbd_sock = iotests.file_path('nbd-sock', base_dir=iotests.sock_dir) > +disk = iotests.file_path('disk') > +iotests.qemu_img_create('-f', iotests.imgfmt, disk, '1M') > +volume_size = 1 * 1024 * 1024 > + > +tls_dir = os.path.join(iotests.test_dir, 'tls') > +os.mkdir(tls_dir) > +atexit.register(shutil.rmtree, tls_dir, True) > + > + > +def openssl_req(*args): > + common = ['openssl', > + 'req', '-x509', > + '-newkey', 'ed25519', > + '-nodes', > + '-days', '1'] > + cmd = common + list(args) > + subprocess.run(cmd, check=True, cwd=tls_dir, > + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) This creates a new throwaway certificate every time the test is run. Should we be trying to minimize the consumption of host entropy by reusing a (longer-lived) throwaway certificate that can be shared between multiple tests, instead of this one-shot approach? At least, that's what nbdkit does - its TLS tests reuse a common certificate with 1-year lifespan. I'm not opposed to your approach, just making sure we think about whether it has any drawbacks to CI testing. > + > + > +openssl_req('-subj', '/CN=ca', > + '-keyout', 'ca-key.pem', > + '-out', 'ca-cert.pem') > +openssl_req('-CA', 'ca-cert.pem', > + '-CAkey', 'ca-key.pem', > + '-subj', '/CN=localhost', > + '-addext', 'basicConstraints=CA:FALSE', > + '-keyout', 'server-key.pem', > + '-out', 'server-cert.pem') > +tls_object = ( > + f'tls-creds-x509,id=tls0,endpoint=server,dir={tls_dir},verify-peer=off' > +) > + > + > +def recv_exact(conn, length): > + buff = b'' > + while len(buff) < length: > + chunk = conn.recv(length - len(buff)) > + if not chunk: > + raise ConnectionError("Failed to read") > + buff += chunk > + return buff > + > + > +class MockTLSNBDServer: > + NBD_INIT_MAGIC = 0x4e42444d41474943 # "NBDMAGIC" > + NBD_OPTS_MAGIC = 0x49484156454f5054 # "IHAVEOPT" > + NBD_REP_MAGIC = 0x0003e889045565a9 > + NBD_FLAG_FIXED_NEWSTYLE = 1 > + NBD_FLAG_NO_ZEROES = 2 > + NBD_OPT_STARTTLS = 5 > + NBD_OPT_GO = 7 > + NBD_REP_ACK = 1 > + NBD_REP_INFO = 3 > + NBD_REP_ERR_UNSUP = 0x80000001 # (1 << 31) | 1 > + NBD_INFO_EXPORT = 0 > + NBD_FLAG_HAS_FLAGS = 1 I'm impressed that you went ahead and basically implemented a bare-bones TLS server just to test this. I don't know if it is worth merging some of this implementation with qemu-iotests/nbd-fault-injector.py to be more reusable across other NBD TLS tests. Still, './run tests/qemu-iotests/check 297' (our linter test) didn't complain about too much code repetition, so I'm not going to hold up this series by insisting on such refactoring. > + > + def __init__(self): > + self._thread = threading.Thread(target=self.run) > + self._close = threading.Event() > + self._sock = socket.socket(socket.AF_UNIX) > + self._ssl_ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) > + self._ssl_ctx.load_cert_chain(os.path.join(tls_dir, 'server-cert.pem'), > + os.path.join(tls_dir, 'server-key.pem')) > + > + def __enter__(self): > + if os.path.exists(nbd_sock): > + os.remove(nbd_sock) > + self._sock.bind(nbd_sock) > + self._sock.listen(1) > + self._thread.start() > + return self > + > + def __exit__(self, exc_type, exc, tb): > + self._close.set() > + self._thread.join() > + os.remove(nbd_sock) > + > + @staticmethod > + def send_reply(conn, opt, resp, data=b''): > + conn.sendall(struct.pack( > + '>QIII', MockTLSNBDServer.NBD_REP_MAGIC, > + opt, resp, len(data)) + data) > + > + def run(self): > + conn, _ = self._sock.accept() > + conn.sendall(struct.pack( > + '>QQH', self.NBD_INIT_MAGIC, self.NBD_OPTS_MAGIC, > + self.NBD_FLAG_FIXED_NEWSTYLE | self.NBD_FLAG_NO_ZEROES)) > + recv_exact(conn, 4) > + while True: > + _, opt, length = struct.unpack('>QII', recv_exact(conn, 16)) > + recv_exact(conn, length) > + > + if opt == self.NBD_OPT_STARTTLS: > + self.send_reply(conn, opt, self.NBD_REP_ACK) > + conn = self._ssl_ctx.wrap_socket(conn, server_side=True) > + elif opt == self.NBD_OPT_GO: > + data = struct.pack( > + '>HQH', self.NBD_INFO_EXPORT, > + volume_size, self.NBD_FLAG_HAS_FLAGS) > + self.send_reply(conn, opt, self.NBD_REP_INFO, data) > + self.send_reply(conn, opt, self.NBD_REP_ACK) > + break This server appears to accept NBD_OPT_GO even when NBD_OPT_STARTTLS was not attempted first. In the context of the test, this doesn't matter (the client is QEMU configured to request TLS), but it may cause oddities if this mock server is reused in more places with a client that does not want TLS. Again, not a show-stopper; our mock server does NOT need to aim for 100% NBD protocol compliance, just enough that it lets the test cover the client code we care about. > + else: > + self.send_reply(conn, opt, self.NBD_REP_ERR_UNSUP) > + > + conn.setblocking(False) # don't wait for the peer's close_notify > + self._close.wait() > + try: > + conn.unwrap() > + except ssl.SSLWantReadError: > + # a parked channel does not reply > + pass > + conn.close() > + self._sock.close() > + -- Eric Blake, Principal Software Engineer Red Hat, Inc. Virtualization: qemu.org | libguestfs.org ^ permalink raw reply [flat|nested] 14+ messages in thread
* Re: [PATCH v4 3/3] iotests: Add coverage for NBD connect thread start delay 2026-12-01 17:05 ` Eric Blake @ 2026-12-03 15:31 ` guillaume vincke 2026-12-03 15:53 ` Eric Blake 0 siblings, 1 reply; 14+ messages in thread From: guillaume vincke @ 2026-12-03 15:31 UTC (permalink / raw) To: eblake Cc: qemu-devel, qemu-block, Vladimir Sementsov-Ogievskiy, Kevin Wolf, Hanna Reitz On 12/1/26 18:05, Eric Blake wrote: > On Mon, Nov 30, 2026 at 01:44:44PM +0100, Guillaume Vincke wrote: >> Test the connect thread starting condition with reconnect-delay=0 when >> the server disconnects after a successful handshake but before running >> operations. Prior to the change to nbd_co_establish_connection(), this >> test would demonstrate two I/O errors. The tests 264 and 277 covering >> reconnection do not use reconnect-delay=0 so this case is not exercised. >> >> Add a test that provokes multiple errors in order to put an NBD client >> in the above-mentioned situation and shows that the first operation >> starts the connect thread and leads to successful subsequent I/O. >> >> Add a second test that runs the same actions on a TLS-backed >> connection. When qemu-nbd closes, it leaves nothing in the socket, so >> the closed channel is already detected. As other NBD servers send a > > s/send/may send/ > >> close_notify before closing, this test uses a minimal custom NBD server >> to mimic them. Before shutting it down, the server socket is set to >> non-blocking to avoid waiting for a close_notify response from the >> client, as it will never arrive from a parked channel. >> >> Signed-off-by: Guillaume Vincke <guillaume.vincke@ovhcloud.com> >> --- >> tests/qemu-iotests/tests/nbd-stale-connection | 70 ++++++ >> .../tests/nbd-stale-connection.out | 17 ++ >> .../tests/nbd-stale-tls-connection | 205 ++++++++++++++++++ >> .../tests/nbd-stale-tls-connection.out | 14 ++ >> 4 files changed, 306 insertions(+) >> create mode 100755 tests/qemu-iotests/tests/nbd-stale-connection >> create mode 100644 tests/qemu-iotests/tests/nbd-stale-connection.out >> create mode 100755 tests/qemu-iotests/tests/nbd-stale-tls-connection >> create mode 100644 tests/qemu-iotests/tests/nbd-stale-tls-connection.out > > Tested-by: Eric Blake <eblake@redhat.com> > >> >> diff --git a/tests/qemu-iotests/tests/nbd-stale-connection b/tests/qemu-iotests/tests/nbd-stale-connection >> new file mode 100755 >> index 0000000000..5f559fa22d >> --- /dev/null >> +++ b/tests/qemu-iotests/tests/nbd-stale-connection >> @@ -0,0 +1,70 @@ >> +#!/usr/bin/env python3 >> +# group: quick > >> +++ b/tests/qemu-iotests/tests/nbd-stale-tls-connection >> @@ -0,0 +1,205 @@ >> +#!/usr/bin/env python3 >> +# group: quick > > For both tests, why not also in auto? That is true for the non-tls version. Will update in v5. For the TLS one, on a build without gnutls the test would fail. That is probably why nbd-tls-iothread is not in auto either. > > >> +# >> +# Test the NBD client stale TLS-backed channel discard >> +# >> +# Copyright (C) 2026 OVHcloud >> +# >> +# SPDX-License-Identifier: GPL-2.0-or-later >> + >> +import atexit >> +import os >> +import shutil >> +import socket >> +import ssl >> +import struct >> +import subprocess >> +import threading >> +import time >> + >> +import iotests >> + >> + >> +iotests.script_initialize(supported_fmts=['qcow2']) >> +if shutil.which('openssl') is None: >> + iotests.notrun('openssl not found') >> +nbd_sock = iotests.file_path('nbd-sock', base_dir=iotests.sock_dir) >> +disk = iotests.file_path('disk') >> +iotests.qemu_img_create('-f', iotests.imgfmt, disk, '1M') >> +volume_size = 1 * 1024 * 1024 >> + >> +tls_dir = os.path.join(iotests.test_dir, 'tls') >> +os.mkdir(tls_dir) >> +atexit.register(shutil.rmtree, tls_dir, True) >> + >> + >> +def openssl_req(*args): >> + common = ['openssl', >> + 'req', '-x509', >> + '-newkey', 'ed25519', >> + '-nodes', >> + '-days', '1'] >> + cmd = common + list(args) >> + subprocess.run(cmd, check=True, cwd=tls_dir, >> + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) > > This creates a new throwaway certificate every time the test is > run. Should we be trying to minimize the consumption of host entropy > by reusing a (longer-lived) throwaway certificate that can be shared > between multiple tests, instead of this one-shot approach? At least, > that's what nbdkit does - its TLS tests reuse a common certificate > with 1-year lifespan. I'm not opposed to your approach, just making > sure we think about whether it has any drawbacks to CI testing. I did not consider it. I found that qemu-iotests/common.tls actually uses a fixed key and generates the certificates at each run. I will do the same in v5. > >> + >> + >> +openssl_req('-subj', '/CN=ca', >> + '-keyout', 'ca-key.pem', >> + '-out', 'ca-cert.pem') >> +openssl_req('-CA', 'ca-cert.pem', >> + '-CAkey', 'ca-key.pem', >> + '-subj', '/CN=localhost', >> + '-addext', 'basicConstraints=CA:FALSE', >> + '-keyout', 'server-key.pem', >> + '-out', 'server-cert.pem') >> +tls_object = ( >> + f'tls-creds-x509,id=tls0,endpoint=server,dir={tls_dir},verify-peer=off' >> +) >> + >> + >> +def recv_exact(conn, length): >> + buff = b'' >> + while len(buff) < length: >> + chunk = conn.recv(length - len(buff)) >> + if not chunk: >> + raise ConnectionError("Failed to read") >> + buff += chunk >> + return buff >> + >> + >> +class MockTLSNBDServer: >> + NBD_INIT_MAGIC = 0x4e42444d41474943 # "NBDMAGIC" >> + NBD_OPTS_MAGIC = 0x49484156454f5054 # "IHAVEOPT" >> + NBD_REP_MAGIC = 0x0003e889045565a9 >> + NBD_FLAG_FIXED_NEWSTYLE = 1 >> + NBD_FLAG_NO_ZEROES = 2 >> + NBD_OPT_STARTTLS = 5 >> + NBD_OPT_GO = 7 >> + NBD_REP_ACK = 1 >> + NBD_REP_INFO = 3 >> + NBD_REP_ERR_UNSUP = 0x80000001 # (1 << 31) | 1 >> + NBD_INFO_EXPORT = 0 >> + NBD_FLAG_HAS_FLAGS = 1 > > I'm impressed that you went ahead and basically implemented a > bare-bones TLS server just to test this. I don't know if it is worth > merging some of this implementation with > qemu-iotests/nbd-fault-injector.py to be more reusable across other > NBD TLS tests. Still, './run tests/qemu-iotests/check 297' (our > linter test) didn't complain about too much code repetition, so I'm > not going to hold up this series by insisting on such refactoring. I did not realize there was already an NBD server implementation in tests. Changing it to support TLS will be quite a refactor though. Would it be fine to implement that as a follow up? It could also address your next point. > >> + >> + def __init__(self): >> + self._thread = threading.Thread(target=self.run) >> + self._close = threading.Event() >> + self._sock = socket.socket(socket.AF_UNIX) >> + self._ssl_ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) >> + self._ssl_ctx.load_cert_chain(os.path.join(tls_dir, 'server-cert.pem'), >> + os.path.join(tls_dir, 'server-key.pem')) >> + >> + def __enter__(self): >> + if os.path.exists(nbd_sock): >> + os.remove(nbd_sock) >> + self._sock.bind(nbd_sock) >> + self._sock.listen(1) >> + self._thread.start() >> + return self >> + >> + def __exit__(self, exc_type, exc, tb): >> + self._close.set() >> + self._thread.join() >> + os.remove(nbd_sock) >> + >> + @staticmethod >> + def send_reply(conn, opt, resp, data=b''): >> + conn.sendall(struct.pack( >> + '>QIII', MockTLSNBDServer.NBD_REP_MAGIC, >> + opt, resp, len(data)) + data) >> + >> + def run(self): >> + conn, _ = self._sock.accept() >> + conn.sendall(struct.pack( >> + '>QQH', self.NBD_INIT_MAGIC, self.NBD_OPTS_MAGIC, >> + self.NBD_FLAG_FIXED_NEWSTYLE | self.NBD_FLAG_NO_ZEROES)) >> + recv_exact(conn, 4) >> + while True: >> + _, opt, length = struct.unpack('>QII', recv_exact(conn, 16)) >> + recv_exact(conn, length) >> + >> + if opt == self.NBD_OPT_STARTTLS: >> + self.send_reply(conn, opt, self.NBD_REP_ACK) >> + conn = self._ssl_ctx.wrap_socket(conn, server_side=True) >> + elif opt == self.NBD_OPT_GO: >> + data = struct.pack( >> + '>HQH', self.NBD_INFO_EXPORT, >> + volume_size, self.NBD_FLAG_HAS_FLAGS) >> + self.send_reply(conn, opt, self.NBD_REP_INFO, data) >> + self.send_reply(conn, opt, self.NBD_REP_ACK) >> + break > > This server appears to accept NBD_OPT_GO even when NBD_OPT_STARTTLS > was not attempted first. In the context of the test, this doesn't > matter (the client is QEMU configured to request TLS), but it may > cause oddities if this mock server is reused in more places with a > client that does not want TLS. Again, not a show-stopper; our mock > server does NOT need to aim for 100% NBD protocol compliance, just > enough that it lets the test cover the client code we care about. > >> + else: >> + self.send_reply(conn, opt, self.NBD_REP_ERR_UNSUP) >> + >> + conn.setblocking(False) # don't wait for the peer's close_notify >> + self._close.wait() >> + try: >> + conn.unwrap() >> + except ssl.SSLWantReadError: >> + # a parked channel does not reply >> + pass >> + conn.close() >> + self._sock.close() >> + > ^ permalink raw reply [flat|nested] 14+ messages in thread
* Re: [PATCH v4 3/3] iotests: Add coverage for NBD connect thread start delay 2026-12-03 15:31 ` guillaume vincke @ 2026-12-03 15:53 ` Eric Blake 0 siblings, 0 replies; 14+ messages in thread From: Eric Blake @ 2026-12-03 15:53 UTC (permalink / raw) To: guillaume vincke Cc: qemu-devel, qemu-block, Vladimir Sementsov-Ogievskiy, Kevin Wolf, Hanna Reitz On Thu, Dec 03, 2026 at 04:31:08PM +0100, guillaume vincke wrote: > > > > I'm impressed that you went ahead and basically implemented a > > bare-bones TLS server just to test this. I don't know if it is worth > > merging some of this implementation with > > qemu-iotests/nbd-fault-injector.py to be more reusable across other > > NBD TLS tests. Still, './run tests/qemu-iotests/check 297' (our > > linter test) didn't complain about too much code repetition, so I'm > > not going to hold up this series by insisting on such refactoring. > > I did not realize there was already an NBD server implementation in > tests. Changing it to support TLS will be quite a refactor though. Would > it be fine to implement that as a follow up? It could also address your > next point. No rush on refactoring nbd-fault-injector.py. I've had some of my recent NBD CVE patches where I also looked at whether it was worth refactoring the existing server or just implementing a bare-bones one-shot second server for the bug in question (although with plaintext, rather than with the additional complication of TLS). And so far my answer has also been that a one-shot server per test (as you did in this patch) is good enough. True, we may be building up technical debt, where consolidating things into a more parameterized single server that can meet the needs of multiple tests would avoid duplication. But that refactoring costs more engineering effort, and that is effort spent on a unit test rather than on QEMU proper. So delaying to a later follow up series, or not ever doing the refactoring, are both viable answers - I already am at the point where I don't want to hold up THIS series by insisting on such a refactoring, and I'm also trying to be explicit that I am not demanding you volunteer for that as a follow up task (but if you DO volunteer, I won't ignore the effort). I am a bit worried that doing such a refactor (if we choose to) will be easier with LLM tooling - but until the QEMU policy on LLM contributions is more permissive, kicking the can of whether to refactor to a point down the road is not hurting us. -- Eric Blake, Principal Software Engineer Red Hat, Inc. Virtualization: qemu.org | libguestfs.org ^ permalink raw reply [flat|nested] 14+ messages in thread
end of thread, other threads:[~2026-12-03 17:32 UTC | newest] Thread overview: 14+ messages (download: mbox.gz follow: Atom feed -- links below jump to the message on this page -- 2026-11-30 12:44 [PATCH v4 0/3] nbd/client-connection: Fix client returning a closed channel Guillaume Vincke 2026-11-30 12:44 ` [PATCH v4 1/3] " Guillaume Vincke 2026-12-01 17:14 ` Daniel P. Berrangé 2026-12-03 12:57 ` guillaume vincke 2026-12-03 16:02 ` Daniel P. Berrangé 2026-12-03 17:17 ` guillaume vincke 2026-12-03 17:29 ` Daniel P. Berrangé 2026-12-03 17:31 ` Eric Blake 2026-11-30 12:44 ` [PATCH v4 2/3] nbd/client-connection: Fix client returning a closed TLS channel Guillaume Vincke 2026-12-01 16:23 ` Eric Blake 2026-11-30 12:44 ` [PATCH v4 3/3] iotests: Add coverage for NBD connect thread start delay Guillaume Vincke 2026-12-01 17:05 ` Eric Blake 2026-12-03 15:31 ` guillaume vincke 2026-12-03 15:53 ` Eric Blake
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.