From 13e0a9344172562cca16068050070c5c051d4af8 Mon Sep 17 00:00:00 2001 From: Alex Hultman Date: Sat, 27 Jun 2020 00:44:20 +0200 Subject: [PATCH] Never emit 0 as close code; use 1005 instead --- src/WebSocket.h | 5 +++-- src/WebSocketProtocol.h | 9 ++++++--- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/WebSocket.h b/src/WebSocket.h index fd518c3..270fb6c 100644 --- a/src/WebSocket.h +++ b/src/WebSocket.h @@ -124,8 +124,9 @@ public: return true; } - /* Send websocket close frame, emit close event, send FIN if successful */ - void end(int code, std::string_view message = {}) { + /* Send websocket close frame, emit close event, send FIN if successful. + * Will not append a close reason if code is 0 or 1005. */ + void end(int code = 0, std::string_view message = {}) { /* Check if we already called this one */ WebSocketData *webSocketData = (WebSocketData *) us_socket_ext(SSL, (us_socket_t *) this); if (webSocketData->isShuttingDown) { diff --git a/src/WebSocketProtocol.h b/src/WebSocketProtocol.h index 1dfb8f1..d396c3a 100644 --- a/src/WebSocketProtocol.h +++ b/src/WebSocketProtocol.h @@ -151,20 +151,23 @@ struct CloseFrame { }; static inline CloseFrame parseClosePayload(char *src, size_t length) { - CloseFrame cf = {}; + /* If we get no code or message, default to reporting 1005 no status code present */ + CloseFrame cf = {1005}; if (length >= 2) { memcpy(&cf.code, src, 2); cf = {cond_byte_swap(cf.code), src + 2, length - 2}; if (cf.code < 1000 || cf.code > 4999 || (cf.code > 1011 && cf.code < 4000) || (cf.code >= 1004 && cf.code <= 1006) || !isValidUtf8((unsigned char *) cf.message, cf.length)) { - return {}; + /* Even though we got a WebSocket close frame, it in itself is abnormal */ + return {1006}; } } return cf; } static inline size_t formatClosePayload(char *dst, uint16_t code, const char *message, size_t length) { - if (code) { + /* We could have more strict checks here, but never append code 0 or 1005 or 1006 */ + if (code && code != 1005 && code != 1006) { code = cond_byte_swap(code); memcpy(dst, &code, 2); /* It is invalid to pass nullptr to memcpy, even though length is 0 */