Subject: bug#43625: Calling write may close the program silently

From: [email-masked] (Rolf)
Date: Fri, 25 Sep 2020 21:50:35 +0200

Greetings,

I am experiencing some difficulties writing a TCP server in Guile. It is
a simple server where every connection gets its own thread. I have
discovered that if a client force closes the connection for any reason
(the client program crashing, for instance), the server program will
silently exit with a status code 141, without rasing any
exceptions, if it attempts to write to the port of that
connection. Below is some sample code:

(define listening-socket (socket PF_INET SOCK_STREAM 0))
(setsockopt listening-socket SOL_SOCKET SO_REUSEADDR 1)
(bind listening-socket AF_INET (inet-pton AF_INET "127.0.0.1") 60000)
(listen listening-socket 1)
(define accepted (car (accept listening-socket)))
(sleep 5) ;; make some time for the client to force close
;(close accepted) ;; if a graceful close happens before the write, a
                  ;; wrong type argument error is raised, as expected
(write "I will never arrive" accepted) ;; program exits w/ 141 here
                                       ;; when the client forces the
                                       ;; connection closed
(display "Unreachable call")
(newline)

Given that the example code is saved to the file "test-write-fail.scm", it
may be reproduced by running

guile test-write-fail.scm; echo "Exit code: $?"

and connecting to it using netcat (nc 127.0.0.1 60000), then immediately
closing the connection by doing a CTRL+C and waiting 5 seconds. The
server will terminate without displaying "Unreachable call" and you
should see an exit code of 141. In such an event, port-closed? will also
return #f, so checking it does not seem to be of any use.

I have tested the same using read, but it does nothing instead of
exiting prematurely:

(define listening-socket (socket PF_INET SOCK_STREAM 0))
(setsockopt listening-socket SOL_SOCKET SO_REUSEADDR 1)
(bind listening-socket AF_INET (inet-pton AF_INET "127.0.0.1") 60000)
(listen listening-socket 1)
(define accepted (car (accept listening-socket)))
(sleep 5)
(read accepted) ;; does nothing, exits with 0
(display "You should see this")
(newline)

I have produced the same results using Guile 3.0.2 and 2.2.6 on Linux,
as well as 2.2.6 on OpenBSD, all x86_64 builds.

Regards,
Rolf