fix(esp_tls): check tls connection finished before read/write operation

This commit is contained in:
Ashish Sharma
2026-03-27 13:25:43 +08:00
parent 4457821b9a
commit 25c0c9da24
3 changed files with 30 additions and 4 deletions
+20 -2
View File
@@ -145,6 +145,15 @@ ssize_t esp_tls_conn_read(esp_tls_t *tls, void *data, size_t datalen)
if (!tls) {
return -1;
}
if (!tls->read) {
return -1;
}
#if CONFIG_MBEDTLS_DYNAMIC_BUFFER
if (tls->is_tls && tls->conn_state != ESP_TLS_DONE) {
ESP_LOGE(TAG, "TLS handshake has not completed, read operation not permitted");
return -1;
}
#endif
return tls->read(tls, (char *)data, datalen);
}
@@ -153,6 +162,15 @@ ssize_t esp_tls_conn_write(esp_tls_t *tls, const void *data, size_t datalen)
if (!tls || !data) {
return -1;
}
if (!tls->write) {
return -1;
}
#if CONFIG_MBEDTLS_DYNAMIC_BUFFER
if (tls->is_tls && tls->conn_state != ESP_TLS_DONE) {
ESP_LOGE(TAG, "TLS handshake has not completed, write operation not permitted");
return -1;
}
#endif
return tls->write(tls, (char *)data, datalen);
}
@@ -574,12 +592,12 @@ int esp_tls_conn_new_sync(const char *hostname, int hostlen, int port, const esp
} else if (ret == -1) {
ESP_LOGE(TAG, "Failed to open new connection");
return -1;
} else if (ret == 0 && cfg->timeout_ms >= 0) {
} else if (ret == 0 && cfg->timeout_ms > 0) {
uint64_t elapsed_time_us = esp_tls_get_platform_time() - start_time_us;
if ((elapsed_time_us / 1000) >= cfg->timeout_ms) {
ESP_LOGW(TAG, "Failed to open new connection in specified timeout");
ESP_INT_EVENT_TRACKER_CAPTURE(tls->error_handle, ESP_TLS_ERR_TYPE_ESP, ESP_ERR_ESP_TLS_CONNECTION_TIMEOUT);
return 0;
return -1;
}
}
}
+9 -2
View File
@@ -420,10 +420,17 @@ esp_tls_t *esp_tls_init(void);
* structure should be zero-initialized
* @param[in] tls Pointer to esp-tls as esp-tls handle.
*
* @note The cfg->timeout_ms parameter controls the connection timeout:
* - timeout_ms > 0: The connection attempt will be aborted if it does not
* complete within the specified duration.
* - timeout_ms <= 0: No application-level timeout is applied. The connection
* relies on the underlying socket timeout (ESP_TLS_DEFAULT_CONN_TIMEOUT).
* On timeout, the function returns -1 and records
* ESP_ERR_ESP_TLS_CONNECTION_TIMEOUT in the error handle.
*
* @return
* - -1 If connection establishment fails.
* - -1 If connection establishment fails (including timeout).
* - 1 If connection establishment is successful.
* - 0 If connection state is in progress.
*/
int esp_tls_conn_new_sync(const char *hostname, int hostlen, int port, const esp_tls_cfg_t *cfg, esp_tls_t *tls);
+1
View File
@@ -1196,6 +1196,7 @@ int esp_mbedtls_server_session_create(esp_tls_cfg_server_t *cfg, int sockfd, esp
return ESP_ERR_ESP_TLS_SERVER_HANDSHAKE_TIMEOUT;
}
}
tls->conn_state = ESP_TLS_DONE;
return ret;
}