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 authored and Willieodwyer committed Mar 8, 2022
1 parent 48aca5e commit dd4bb78
Showing 1 changed file with 23 additions and 10 deletions.
33 changes: 23 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,37 @@ 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;
}
/*
* Note: rv can be 0 here eg. when mbedtls just flushed
* the previous incomplete record.
*
* Note: we never send an empty TLS record.
*/
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 +111,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 dd4bb78

Please sign in to comment.