From f54248d3cafe7a3493df5957d1a026b23f6a8a2c Mon Sep 17 00:00:00 2001 From: Jon Shallow Date: Fri, 15 Feb 2019 18:08:34 +0000 Subject: [PATCH] coap-server: GnuTLS does not correctly detect closure by a client using TCP To reproduce:- Run a GnuTLS-based coap-server with option `-n` and connect with `openssl s_client` to port 5684. The handshake works and see binary data (the CoAP/TCP CSM signaling). Now, then interrupt the openssl s_client process with SIGINT, This generates a lot of these messages: Feb 14 19:22:39 DEBG ASSERT: ../../lib/record.c[_gnutls_recv_int]:1766 Feb 14 19:22:39 DEBG ASSERT: ../../lib/buffers.c[_gnutls_io_read_buffered]:589 Feb 14 19:22:39 DEBG ASSERT: ../../lib/record.c[_gnutls_recv_int]:1766 Feb 14 19:22:39 DEBG ASSERT: ../../lib/buffers.c[_gnutls_io_read_buffered]:589 Feb 14 19:22:39 DEBG ASSERT: ../../lib/record.c[_gnutls_recv_int]:1766 Feb 14 19:22:39 DEBG ASSERT: ../../lib/buffers.c[_gnutls_io_read_buffered]:589 Feb 14 19:22:39 DEBG ASSERT: ../../lib/record.c[_gnutls_recv_int]:1766 Feb 14 19:22:39 DEBG ASSERT: ../../lib/buffers.c[_gnutls_io_read_buffered]:589 An OpenSSL-based coap-server gets a clean disconnect and closes the session as expected. src/coap_gnutls.c: Return correct response when coap_sock_read() is called by GnuTLS internal Pull and the TCP session is closed so that the coap session is closed correctly --- src/coap_gnutls.c | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/src/coap_gnutls.c b/src/coap_gnutls.c index dc5b08c3..2ac0a494 100644 --- a/src/coap_gnutls.c +++ b/src/coap_gnutls.c @@ -1504,11 +1504,20 @@ coap_sock_read(gnutls_transport_ptr_t context, void *out, size_t outl) { coap_session_t *c_session = (struct coap_session_t *)context; if (out != NULL) { - ret = (int)coap_socket_read(&c_session->sock, out, outl); +#ifdef _WIN32 + ret = recv(c_session->sock.fd, (char *)out, (int)outl, 0); +#else + ret = recv(c_session->sock.fd, out, outl, 0); +#endif if (ret == 0) { - errno = EAGAIN; - ret = -1; - } + /* graceful shutdown */ + c_session->sock.flags &= ~COAP_SOCKET_CAN_READ; + return 0; + } else if (ret == COAP_SOCKET_ERROR) + c_session->sock.flags &= ~COAP_SOCKET_CAN_READ; + else if (ret < (ssize_t)outl) + c_session->sock.flags &= ~COAP_SOCKET_CAN_READ; + return ret; } return ret; } @@ -1713,11 +1722,14 @@ ssize_t coap_tls_read(coap_session_t *c_session, errno = EAGAIN; ret = 0; break; + case GNUTLS_E_PULL_ERROR: + c_session->dtls_event = COAP_EVENT_DTLS_ERROR; + break; default: - coap_log(LOG_WARNING, - "coap_tls_read: gnutls_record_recv " - "returned %d: '%s'\n", - ret, gnutls_strerror(ret)); + coap_log(LOG_WARNING, + "coap_tls_read: gnutls_record_recv " + "returned %d: '%s'\n", + ret, gnutls_strerror(ret)); ret = -1; break; }