ws_client: fix ping-pong mechanism to use mask, support reception of zero-payload PONG and sending non-zero-payload PING

Closes https://github.com/espressif/esp-idf/issues/3890
Closes https://github.com/espressif/esp-idf/issues/4138
This commit is contained in:
David Cermak 2019-08-22 17:39:20 +02:00
parent 87fb025b97
commit ea955e1efc
2 changed files with 10 additions and 12 deletions

View file

@ -43,7 +43,6 @@ void esp_transport_ws_set_path(esp_transport_handle_t t, const char *path);
*/ */
esp_err_t esp_transport_ws_set_subprotocol(esp_transport_handle_t t, const char *sub_protocol); esp_err_t esp_transport_ws_set_subprotocol(esp_transport_handle_t t, const char *sub_protocol);
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif

View file

@ -188,18 +188,17 @@ static int _ws_write(esp_transport_handle_t t, int opcode, int mask_flag, const
ws_header[header_len++] = (uint8_t)((len >> 8) & 0xFF); ws_header[header_len++] = (uint8_t)((len >> 8) & 0xFF);
ws_header[header_len++] = (uint8_t)((len >> 0) & 0xFF); ws_header[header_len++] = (uint8_t)((len >> 0) & 0xFF);
} }
if (len) {
if (mask_flag) {
mask = &ws_header[header_len];
getrandom(ws_header + header_len, 4, 0);
header_len += 4;
for (i = 0; i < len; ++i) { if (mask_flag) {
buffer[i] = (buffer[i] ^ mask[i % 4]); mask = &ws_header[header_len];
} getrandom(ws_header + header_len, 4, 0);
header_len += 4;
for (i = 0; i < len; ++i) {
buffer[i] = (buffer[i] ^ mask[i % 4]);
} }
} }
if (esp_transport_write(ws->parent, ws_header, header_len, timeout_ms) != header_len) { if (esp_transport_write(ws->parent, ws_header, header_len, timeout_ms) != header_len) {
ESP_LOGE(TAG, "Error write header"); ESP_LOGE(TAG, "Error write header");
return -1; return -1;
@ -224,7 +223,7 @@ static int ws_write(esp_transport_handle_t t, const char *b, int len, int timeou
{ {
if (len == 0) { if (len == 0) {
ESP_LOGD(TAG, "Write PING message"); ESP_LOGD(TAG, "Write PING message");
return _ws_write(t, WS_OPCODE_PING | WS_FIN, 0, NULL, 0, timeout_ms); return _ws_write(t, WS_OPCODE_PING | WS_FIN, WS_MASK, NULL, 0, timeout_ms);
} }
return _ws_write(t, WS_OPCODE_BINARY | WS_FIN, WS_MASK, b, len, timeout_ms); return _ws_write(t, WS_OPCODE_BINARY | WS_FIN, WS_MASK, b, len, timeout_ms);
} }
@ -282,7 +281,7 @@ static int ws_read(esp_transport_handle_t t, char *buffer, int len, int timeout_
} }
// Then receive and process payload // Then receive and process payload
if ((rlen = esp_transport_read(ws->parent, buffer, payload_len, timeout_ms)) <= 0) { if (payload_len != 0 && (rlen = esp_transport_read(ws->parent, buffer, payload_len, timeout_ms)) <= 0) {
ESP_LOGE(TAG, "Error read data"); ESP_LOGE(TAG, "Error read data");
return rlen; return rlen;
} }