Skip to content

Commit

Permalink
mqtt_pal.c: Tweak mbedtls implementation
Browse files Browse the repository at this point in the history
To follow the protocol suggested in
LiamBindle#110
  • Loading branch information
yamt committed Feb 4, 2022
1 parent 8089a36 commit 0d1185d
Showing 1 changed file with 25 additions and 10 deletions.
35 changes: 25 additions & 10 deletions src/mqtt_pal.c
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ int _mqtt_pal_dummy;
#include <mbedtls/ssl.h>

ssize_t mqtt_pal_sendall(mqtt_pal_socket_handle fd, const void* buf, size_t len, int flags) {
enum MQTTErrors error = 0;
size_t sent = 0;
while(sent < len) {
int rv = mbedtls_ssl_write(fd, buf + sent, len - sent);
Expand All @@ -64,29 +65,39 @@ ssize_t mqtt_pal_sendall(mqtt_pal_socket_handle fd, const void* buf, size_t len,
/* should call mbedtls_ssl_write later again */
break;
}
return MQTT_ERROR_SOCKET_ERROR;
error = MQTT_ERROR_SOCKET_ERROR;
break;
}
if (rv == 0) {
/*
* is this possible?
* Note: we never send an empty TLS record.
*/
error = MQTT_ERROR_SOCKET_ERROR;
break;
}
sent += (size_t) rv;
}
if (sent == 0) {
return error;
}
return sent;
}

ssize_t mqtt_pal_recvall(mqtt_pal_socket_handle fd, void* buf, size_t bufsz, int flags) {
const void *const start = buf;
enum MQTTErrors error = 0;
int rv;
do {
rv = mbedtls_ssl_read(fd, buf, bufsz);
if (rv == 0) {
/*
* Note: mbedtls_ssl_read returns 0 when the underlying
* transport was closed without CloseNotify.
*
* Raise an error to trigger a reconnect.
*/
if (buf == start) {
/*
* Raise an error to trigger a reconnect.
*/
return MQTT_ERROR_SOCKET_ERROR;
}
error = MQTT_ERROR_SOCKET_ERROR;
break;
}
if (rv < 0) {
Expand All @@ -102,12 +113,16 @@ ssize_t mqtt_pal_recvall(mqtt_pal_socket_handle fd, void* buf, size_t bufsz, int
/* should call mbedtls_ssl_read later again */
break;
}
return MQTT_ERROR_SOCKET_ERROR;
/* Note: MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY is handled here. */
error = MQTT_ERROR_SOCKET_ERROR;
break;
}
buf = (char*)buf + rv;
bufsz -= rv;
} while (rv > 0 && bufsz > 0);

} while (bufsz > 0);
if (buf == start) {
return error;
}
return buf - start;
}

Expand Down

0 comments on commit 0d1185d

Please sign in to comment.