web_socket_frame.c
Go to the documentation of this file.
1 /**
2  * @file web_socket_frame.c
3  * @brief WebSocket frame parsing and formatting
4  *
5  * @section License
6  *
7  * SPDX-License-Identifier: GPL-2.0-or-later
8  *
9  * Copyright (C) 2010-2026 Oryx Embedded SARL. All rights reserved.
10  *
11  * This file is part of CycloneTCP Open.
12  *
13  * This program is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU General Public License
15  * as published by the Free Software Foundation; either version 2
16  * of the License, or (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software Foundation,
25  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26  *
27  * @author Oryx Embedded SARL (www.oryx-embedded.com)
28  * @version 2.6.8
29  **/
30 
31 //Switch to the appropriate trace level
32 #define TRACE_LEVEL WEB_SOCKET_TRACE_LEVEL
33 
34 //Dependencies
35 #include "core/net.h"
36 #include "web_socket/web_socket.h"
40 #include "debug.h"
41 
42 //Check TCP/IP stack configuration
43 #if (WEB_SOCKET_SUPPORT == ENABLED)
44 
45 
46 /**
47  * @brief Format WebSocket frame header
48  * @param[in] webSocket Handle to a WebSocket
49  * @param[in] fin FIN flag
50  * @param[in] type Frame type
51  * @param[in] payloadLen Length of the payload data
52  * @return Error code
53  **/
54 
57 {
58  error_t error;
59  WebSocketFrameContext *txContext;
60  WebSocketFrame *frame;
61 
62  //Point to the TX context
63  txContext = &webSocket->txContext;
64 
65  //Flush the transmit buffer
66  txContext->bufferPos = 0;
67  txContext->bufferLen = 0;
68 
69  //The endpoint must encapsulate the data in a WebSocket frame
70  frame = (WebSocketFrame *) txContext->buffer;
71 
72  //The frame needs to be formatted according to the WebSocket framing
73  //format
74  frame->fin = fin;
75  frame->reserved = 0;
76  frame->opcode = type;
77 
78  //All frames sent from the client to the server are masked by a 32-bit
79  //value that is contained within the frame
80  if(webSocket->endpoint == WS_ENDPOINT_CLIENT)
81  {
82  //All frames sent from client to server have the Mask bit set to 1
83  frame->mask = TRUE;
84 
85  //Make sure that the RNG callback function has been registered
86  if(webSockRandCallback != NULL)
87  {
88  //Generate a random masking key
89  error = webSockRandCallback(txContext->maskingKey, sizeof(uint32_t));
90  //Any error to report?
91  if(error)
92  {
93  return error;
94  }
95  }
96  else
97  {
98  //A cryptographically strong random number generator
99  //must be used to generate the masking key
100  return ERROR_PRNG_NOT_READY;
101  }
102  }
103  else
104  {
105  //Clear the Mask bit
106  frame->mask = FALSE;
107  }
108 
109  //Size of the frame header
110  txContext->bufferLen = sizeof(WebSocketFrame);
111 
112  //Compute the number of application data to be transmitted
113  txContext->payloadLen = payloadLen;
114 
115  //Check the length of the payload
116  if(payloadLen <= 125)
117  {
118  //Payload length
119  frame->payloadLen = payloadLen;
120  }
121  else if(payloadLen <= 65535)
122  {
123  //If the Payload Length field is set to 126, then the following
124  //2 bytes are interpreted as a 16-bit unsigned integer
125  frame->payloadLen = 126;
126 
127  //Save the length of the payload data
128  STORE16BE(payloadLen, frame->extPayloadLen);
129 
130  //Adjust the length of the frame header
131  txContext->bufferLen += sizeof(uint16_t);
132  }
133  else
134  {
135  //If the Payload Length field is set to 127, then the following
136  //8 bytes are interpreted as a 64-bit unsigned integer
137  frame->payloadLen = 127;
138 
139  //Save the length of the payload data
140  STORE64BE(payloadLen, frame->extPayloadLen);
141 
142  //Adjust the length of the frame header
143  txContext->bufferLen += sizeof(uint64_t);
144  }
145 
146  //Debug message
147  TRACE_DEBUG("WebSocket: Sending frame\r\n");
148  TRACE_DEBUG(" FIN = %u\r\n", frame->fin);
149  TRACE_DEBUG(" Reserved = %u\r\n", frame->reserved);
150  TRACE_DEBUG(" Opcode = %u\r\n", frame->opcode);
151  TRACE_DEBUG(" Mask = %u\r\n", frame->mask);
152  TRACE_DEBUG(" Payload Length = %u\r\n", txContext->payloadLen);
153 
154  //The Masking Key field is present the mask bit is set to 1
155  if(frame->mask)
156  {
157  //Debug message
158  TRACE_DEBUG_ARRAY(" Masking Key = ", txContext->maskingKey, sizeof(uint32_t));
159 
160  //Copy the masking key
161  osMemcpy(txContext->buffer + txContext->bufferLen,
162  txContext->maskingKey, sizeof(uint32_t));
163 
164  //Adjust the length of the frame header
165  txContext->bufferLen += sizeof(uint32_t);
166  }
167 
168  //Successful processing
169  return NO_ERROR;
170 }
171 
172 
173 /**
174  * @brief Parse WebSocket frame header
175  * @param[in] webSocket Handle to a WebSocket
176  * @param[in] frame Pointer to the WebSocket frame header
177  * @param[out] type Frame type
178  * @return Error code
179  **/
180 
182  const WebSocketFrame *frame, WebSocketFrameType *type)
183 {
184  size_t j;
185  size_t k;
186  size_t n;
187  uint16_t statusCode;
188  WebSocketFrameContext *rxContext;
189 
190  //Point to the RX context
191  rxContext = &webSocket->rxContext;
192 
193  //Point to the Extended Payload Length
194  n = sizeof(WebSocketFrame);
195 
196  //Check frame type
197  if(type != NULL)
198  {
200  {
201  if(frame->opcode != WS_FRAME_TYPE_CONTINUATION &&
202  frame->opcode != *type)
203  {
205  }
206  }
207  }
208 
209  //Check the Payload Length field
210  if(frame->payloadLen == 126)
211  {
212  //If the Payload Length field is set to 126, then the following
213  //2 bytes are interpreted as a 16-bit unsigned integer
214  rxContext->payloadLen = LOAD16BE(frame->extPayloadLen);
215 
216  //Point to the next field
217  n += sizeof(uint16_t);
218  }
219  else if(frame->payloadLen == 127)
220  {
221  //If the Payload Length field is set to 127, then the following
222  //8 bytes are interpreted as a 64-bit unsigned integer
223  rxContext->payloadLen = LOAD64BE(frame->extPayloadLen);
224 
225  //Point to the next field
226  n += sizeof(uint64_t);
227  }
228  else
229  {
230  //Retrieve the length of the payload data
231  rxContext->payloadLen = frame->payloadLen;
232  }
233 
234  //Debug message
235  TRACE_DEBUG("WebSocket: frame received...\r\n");
236  TRACE_DEBUG(" FIN = %u\r\n", frame->fin);
237  TRACE_DEBUG(" Reserved = %u\r\n", frame->reserved);
238  TRACE_DEBUG(" Opcode = %u\r\n", frame->opcode);
239  TRACE_DEBUG(" Mask = %u\r\n", frame->mask);
240  TRACE_DEBUG(" Payload Length = %u\r\n", rxContext->payloadLen);
241 
242  //Check whether the payload data is masked
243  if(frame->mask)
244  {
245  //Save the masking key
246  osMemcpy(rxContext->maskingKey, (uint8_t *) frame + n, sizeof(uint32_t));
247  //Debug message
248  TRACE_DEBUG_ARRAY(" Masking Key = ", rxContext->maskingKey, sizeof(uint32_t));
249 
250  //Point to the payload data
251  n += sizeof(uint32_t);
252  }
253 
254  //Text or Close frame received?
255  if(frame->opcode == WS_FRAME_TYPE_TEXT ||
256  frame->opcode == WS_FRAME_TYPE_CLOSE)
257  {
258  //Reinitialize UTF-8 decoding context
259  webSocket->utf8Context.utf8CharSize = 0;
260  webSocket->utf8Context.utf8CharIndex = 0;
261  webSocket->utf8Context.utf8CodePoint = 0;
262  }
263 
264  //If the RSV field is a nonzero value and none of the negotiated extensions
265  //defines the meaning of such a nonzero value, the receiving endpoint must
266  //fail the WebSocket connection
267  if(frame->reserved != 0)
268  {
269  //Report a protocol error
270  webSocket->statusCode = WS_STATUS_CODE_PROTOCOL_ERROR;
271  //Terminate the WebSocket connection
272  return ERROR_INVALID_FRAME;
273  }
274 
275  //A client must mask all frames that it sends to the server. The server
276  //must close the connection upon receiving a frame that is not masked
277  //(refer to RFC 6455, section 5.1)
278  if(webSocket->endpoint == WS_ENDPOINT_SERVER && !frame->mask)
279  {
280  //Report a protocol error
281  webSocket->statusCode = WS_STATUS_CODE_PROTOCOL_ERROR;
282  //Terminate the WebSocket connection
283  return ERROR_INVALID_FRAME;
284  }
285 
286  //The Opcode field defines the interpretation of the payload data
287  if(frame->opcode == WS_FRAME_TYPE_CONTINUATION)
288  {
289  //A Continuation frame cannot be the first frame of a fragmented message
290  if(rxContext->fin)
291  {
292  webSocket->statusCode = WS_STATUS_CODE_PROTOCOL_ERROR;
293  }
294 
296  }
297  else if(frame->opcode == WS_FRAME_TYPE_TEXT)
298  {
299  //The Opcode must be 0 in subsequent fragmented frames
300  if(!rxContext->fin)
301  {
302  webSocket->statusCode = WS_STATUS_CODE_PROTOCOL_ERROR;
303  }
304 
305  //Save the Opcode field
306  rxContext->dataFrameType = WS_FRAME_TYPE_TEXT;
308  }
309  else if(frame->opcode == WS_FRAME_TYPE_BINARY)
310  {
311  //The Opcode must be 0 in subsequent fragmented frames
312  if(!rxContext->fin)
313  {
314  webSocket->statusCode = WS_STATUS_CODE_PROTOCOL_ERROR;
315  }
316 
317  //Save the Opcode field
318  rxContext->dataFrameType = WS_FRAME_TYPE_BINARY;
320  }
321  else if(frame->opcode == WS_FRAME_TYPE_CLOSE)
322  {
323  //Check the length of the payload data
324  if(rxContext->payloadLen == 0)
325  {
326  //The Close frame does not contain any body
327  webSocket->statusCode = WS_STATUS_CODE_NORMAL_CLOSURE;
328  }
329  else if(rxContext->payloadLen == 1)
330  {
331  //Report a protocol error
332  webSocket->statusCode = WS_STATUS_CODE_PROTOCOL_ERROR;
333  }
334  else
335  {
336  //All frames sent from the client to the server are masked
337  if(frame->mask)
338  {
339  //Unmask the data
340  for(j = 0; j < rxContext->payloadLen; j++)
341  {
342  //Index of the masking key to be applied
343  k = j % 4;
344  //Convert masked data into unmasked data
345  *((uint8_t *) frame + n + j) ^= rxContext->maskingKey[k];
346  }
347  }
348 
349  //If there is a body, the first two bytes of the body must be
350  //a 2-byte unsigned integer representing a status code
351  statusCode = LOAD16BE((uint8_t *) frame + n);
352 
353  //Debug message
354  TRACE_DEBUG(" Status Code = %u\r\n", statusCode);
355 
356  //When sending a Close frame in response, the endpoint typically
357  //echos the status code it received
358  if(webSocketCheckStatusCode(statusCode))
359  {
360  webSocket->statusCode = statusCode;
361  }
362  else
363  {
364  webSocket->statusCode = WS_STATUS_CODE_PROTOCOL_ERROR;
365  }
366 
367  //The body may contain UTF-8-encoded data
368  if(rxContext->payloadLen > 2)
369  {
370  //Compute the length of the data
371  k = rxContext->payloadLen - 2;
372 
373  //Invalid UTF-8 sequence?
374  if(!webSocketCheckUtf8Stream(&webSocket->utf8Context,
375  (uint8_t *) frame + n + 2, k, k))
376  {
377  //The received data is not consistent with the type of the message
378  webSocket->statusCode = WS_STATUS_CODE_INVALID_PAYLOAD_DATA;
379  }
380  }
381  }
382 
383  //A Close frame has been received
384  webSocket->handshakeContext.closingFrameReceived = TRUE;
385  //Exit immediately
386  return ERROR_END_OF_STREAM;
387  }
388  else if(frame->opcode == WS_FRAME_TYPE_PING)
389  {
390  //Save the Opcode field
392 
393  //Control frames must not be fragmented
394  if(!frame->fin)
395  {
396  webSocket->statusCode = WS_STATUS_CODE_PROTOCOL_ERROR;
397  }
398 
399  //All control frames must have a payload length of 125 bytes or less
400  if(frame->payloadLen > 125)
401  {
402  webSocket->statusCode = WS_STATUS_CODE_PROTOCOL_ERROR;
403  }
404  }
405  else if(frame->opcode == WS_FRAME_TYPE_PONG)
406  {
407  //Save the Opcode field
409 
410  //Control frames must not be fragmented
411  if(!frame->fin)
412  {
413  webSocket->statusCode = WS_STATUS_CODE_PROTOCOL_ERROR;
414  }
415 
416  //All control frames must have a payload length of 125 bytes or less
417  if(frame->payloadLen > 125)
418  {
419  webSocket->statusCode = WS_STATUS_CODE_PROTOCOL_ERROR;
420  }
421  }
422  else
423  {
424  //If an unknown opcode is received, the receiving endpoint must fail
425  //the WebSocket connection
426  webSocket->statusCode = WS_STATUS_CODE_PROTOCOL_ERROR;
427  }
428 
429  //Save the Mask flag
430  rxContext->mask = frame->mask;
431 
432  //Control frame?
434  {
435  //Return frame type
436  if(type != NULL)
437  {
438  *type = rxContext->controlFrameType;
439  }
440  }
441  else
442  {
443  //Save the FIN flag
444  rxContext->fin = frame->fin;
445 
446  //Return frame type
447  if(type != NULL)
448  {
449  *type = rxContext->dataFrameType;
450  }
451  }
452 
453  //Check status code
454  if(webSocket->statusCode == WS_STATUS_CODE_NO_STATUS_RCVD)
455  {
456  return NO_ERROR;
457  }
458  else if(webSocket->statusCode == WS_STATUS_CODE_NORMAL_CLOSURE)
459  {
460  return ERROR_END_OF_STREAM;
461  }
462  else if(webSocket->statusCode == WS_STATUS_CODE_PROTOCOL_ERROR)
463  {
464  return ERROR_INVALID_FRAME;
465  }
466  else
467  {
468  return ERROR_FAILURE;
469  }
470 }
471 
472 
473 /**
474  * @brief Format a Close frame
475  * @param[in] webSocket Handle to a WebSocket
476  * @return Error code
477  **/
478 
480 {
481  error_t error;
482  uint8_t *p;
483 
484  //Format Close frame
485  error = webSocketFormatFrameHeader(webSocket,
486  TRUE, WS_FRAME_TYPE_CLOSE, sizeof(uint16_t));
487 
488  //Check status code
489  if(!error)
490  {
491  //1005 is a reserved value and must not be set as a status code in
492  //a Close control frame by an endpoint
493  if(webSocket->statusCode == WS_STATUS_CODE_NO_STATUS_RCVD)
494  {
495  webSocket->statusCode = WS_STATUS_CODE_NORMAL_CLOSURE;
496  }
497 
498  //Debug message
499  TRACE_DEBUG(" Status Code = %u\r\n", webSocket->statusCode);
500 
501  //Point to end of the WebSocket frame header
502  p = webSocket->txContext.buffer + webSocket->txContext.bufferLen;
503 
504  //Write status code
505  p[0] = MSB(webSocket->statusCode);
506  p[1] = LSB(webSocket->statusCode);
507 
508  //All frames sent from the client to the server are masked
509  if(webSocket->endpoint == WS_ENDPOINT_CLIENT)
510  {
511  //Apply masking
512  p[0] ^= webSocket->txContext.maskingKey[0];
513  p[1] ^= webSocket->txContext.maskingKey[1];
514  }
515 
516  //Adjust the length of the frame
517  webSocket->txContext.bufferLen += sizeof(uint16_t);
518  }
519 
520  //Return status code
521  return error;
522 }
523 
524 #endif
error_t webSocketFormatFrameHeader(WebSocket *webSocket, bool_t fin, WebSocketFrameType type, size_t payloadLen)
Format WebSocket frame header.
int bool_t
Definition: compiler_port.h:63
error_t webSocketFormatCloseFrame(WebSocket *webSocket)
Format a Close frame.
bool_t mask
Defines whether the payload data is masked.
Definition: web_socket.h:404
uint8_t maskingKey[4]
Masking key.
Definition: web_socket.h:405
@ ERROR_UNEXPECTED_MESSAGE
Definition: error.h:196
uint8_t p
Definition: ndp.h:300
WebSocket API (client and server)
#define TRUE
Definition: os_port.h:50
bool_t webSocketCheckUtf8Stream(WebSocketUtf8Context *context, const uint8_t *data, size_t length, size_t remaining)
Check whether a an UTF-8 stream is valid.
Helper functions for WebSockets.
uint8_t type
Definition: coap_common.h:176
@ WS_STATUS_CODE_NO_STATUS_RCVD
Definition: web_socket.h:283
@ ERROR_END_OF_STREAM
Definition: error.h:212
@ ERROR_PRNG_NOT_READY
Definition: error.h:253
WebSocketFrameType controlFrameType
Control frame type.
Definition: web_socket.h:402
WebSocket frame parsing and formatting.
#define LOAD64BE(p)
Definition: cpu_endian.h:246
#define FALSE
Definition: os_port.h:46
#define osMemcpy(dest, src, length)
Definition: os_port.h:147
@ ERROR_INVALID_FRAME
Definition: error.h:86
size_t bufferLen
Length of the data buffer.
Definition: web_socket.h:409
error_t
Error codes.
Definition: error.h:43
Frame encoding/decoding context.
Definition: web_socket.h:399
bool_t webSocketCheckStatusCode(uint16_t statusCode)
Check whether a status code is valid.
WebSocketFrameType
WebSocket frame types.
Definition: web_socket.h:263
@ ERROR_FAILURE
Generic error code.
Definition: error.h:45
#define STORE16BE(a, p)
Definition: cpu_endian.h:262
@ WS_FRAME_TYPE_PING
Definition: web_socket.h:268
WebSocketRandCallback webSockRandCallback
Definition: web_socket.c:52
@ WS_FRAME_TYPE_TEXT
Definition: web_socket.h:265
@ WS_ENDPOINT_SERVER
Definition: web_socket.h:192
WebSocketFrameType dataFrameType
FSM state.
Definition: web_socket.h:401
size_t payloadLen
Payload length.
Definition: web_socket.h:406
#define MSB(x)
Definition: os_port.h:59
@ WS_FRAME_TYPE_PONG
Definition: web_socket.h:269
#define LSB(x)
Definition: os_port.h:55
@ WS_ENDPOINT_CLIENT
Definition: web_socket.h:191
#define WebSocket
Definition: web_socket.h:177
error_t webSocketParseFrameHeader(WebSocket *webSocket, const WebSocketFrame *frame, WebSocketFrameType *type)
Parse WebSocket frame header.
@ WS_FRAME_TYPE_CLOSE
Definition: web_socket.h:267
#define TRACE_DEBUG(...)
Definition: debug.h:119
#define STORE64BE(a, p)
Definition: cpu_endian.h:322
#define TRACE_DEBUG_ARRAY(p, a, n)
Definition: debug.h:120
WebSocketFrame
Definition: web_socket.h:322
@ WS_STATUS_CODE_INVALID_PAYLOAD_DATA
Definition: web_socket.h:285
uint8_t n
uint8_t buffer[WEB_SOCKET_BUFFER_SIZE]
Data buffer.
Definition: web_socket.h:408
@ WS_FRAME_TYPE_CONTINUATION
Definition: web_socket.h:264
bool_t fin
Final fragment in a message.
Definition: web_socket.h:403
@ WS_STATUS_CODE_PROTOCOL_ERROR
Definition: web_socket.h:281
WebSocket transport layer.
size_t bufferPos
Current position.
Definition: web_socket.h:410
uint8_t fin
Definition: web_socket.h:317
uint16_t payloadLen
Definition: ipv6.h:303
#define LOAD16BE(p)
Definition: cpu_endian.h:186
TCP/IP stack core.
@ WS_STATUS_CODE_NORMAL_CLOSURE
Definition: web_socket.h:279
@ WS_FRAME_TYPE_BINARY
Definition: web_socket.h:266
@ NO_ERROR
Success.
Definition: error.h:44
Debugging facilities.