web_socket_misc.c
Go to the documentation of this file.
1 /**
2  * @file web_socket_misc.c
3  * @brief Helper functions for WebSockets
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 <stdlib.h>
36 #include "core/net.h"
37 #include "web_socket/web_socket.h"
42 #include "encoding/base64.h"
43 #include "hash/sha1.h"
44 #include "str.h"
45 #include "debug.h"
46 
47 //Check TCP/IP stack configuration
48 #if (WEB_SOCKET_SUPPORT == ENABLED)
49 
50 //WebSocket GUID
51 const char_t webSocketGuid[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
52 
53 
54 /**
55  * @brief HTTP status codes
56  **/
57 
58 static const WebSocketStatusCodeDesc statusCodeList[] =
59 {
60  //Success
61  {200, "OK"},
62  {201, "Created"},
63  {202, "Accepted"},
64  {204, "No Content"},
65  //Redirection
66  {301, "Moved Permanently"},
67  {302, "Found"},
68  {304, "Not Modified"},
69  //Client error
70  {400, "Bad Request"},
71  {401, "Unauthorized"},
72  {403, "Forbidden"},
73  {404, "Not Found"},
74  //Server error
75  {500, "Internal Server Error"},
76  {501, "Not Implemented"},
77  {502, "Bad Gateway"},
78  {503, "Service Unavailable"}
79 };
80 
81 
82 /**
83  * @brief Update WebSocket state
84  * @param[in] webSocket Handle to a WebSocket
85  * @param[in] newState New state to switch to
86  **/
87 
88 void webSocketChangeState(WebSocket *webSocket, WebSocketState newState)
89 {
90  //Switch to the new state
91  webSocket->state = newState;
92  //Save current time;
93  webSocket->timestamp = osGetSystemTime();
94 
95  //Reset sub-state
96  webSocket->txContext.state = WS_SUB_STATE_INIT;
97  webSocket->rxContext.state = WS_SUB_STATE_INIT;
98 }
99 
100 
101 /**
102  * @brief Parse client or server handshake
103  * @param[in] webSocket Handle to a WebSocket
104  * @return Error code
105  **/
106 
108 {
109  error_t error;
110  size_t n;
111  WebSocketFrameContext *rxContext;
112 
113  //Point to the RX context
114  rxContext = &webSocket->rxContext;
115 
116  //Initialize status code
117  error = NO_ERROR;
118 
119  //Wait for the handshake to complete
120  while(1)
121  {
122  //Client or server operation?
123  if(webSocket->endpoint == WS_ENDPOINT_CLIENT)
124  {
125  if(webSocket->state == WS_STATE_OPEN)
126  {
127  break;
128  }
129  }
130  else
131  {
132  if(webSocket->state == WS_STATE_SERVER_HANDSHAKE)
133  {
134  break;
135  }
136  }
137 
138  //Check current sub-state
139  if(rxContext->state == WS_SUB_STATE_INIT)
140  {
141  //Initialize status code
142  webSocket->statusCode = WS_STATUS_CODE_NO_STATUS_RCVD;
143 
144  //Initialize FIN flag
145  rxContext->fin = TRUE;
146 
147  //Flush the receive buffer
148  rxContext->bufferPos = 0;
149  rxContext->bufferLen = 0;
150 
151  //Initialize variables
152  webSocket->handshakeContext.statusCode = 0;
153  webSocket->handshakeContext.upgradeWebSocket = FALSE;
154  webSocket->handshakeContext.connectionUpgrade = FALSE;
155  webSocket->handshakeContext.connectionClose = FALSE;
156  webSocket->handshakeContext.contentLength = 0;
157  webSocket->handshakeContext.closingFrameSent = FALSE;
158  webSocket->handshakeContext.closingFrameReceived = FALSE;
159 
160 #if (WEB_SOCKET_BASIC_AUTH_SUPPORT == ENABLED || WEB_SOCKET_DIGEST_AUTH_SUPPORT == ENABLED)
161  webSocket->authContext.requiredAuthMode = WS_AUTH_MODE_NONE;
162 #endif
163 
164 #if (WEB_SOCKET_DIGEST_AUTH_SUPPORT == ENABLED)
165  osStrcpy(webSocket->authContext.nonce, "");
166  osStrcpy(webSocket->authContext.opaque, "");
167  webSocket->authContext.stale = FALSE;
168 #endif
169 
170  //Client or server operation?
171  if(webSocket->endpoint == WS_ENDPOINT_CLIENT)
172  {
173  //Clear server key
174  osStrcpy(webSocket->handshakeContext.serverKey, "");
175 
176  //Debug message
177  TRACE_DEBUG("WebSocket: server handshake\r\n");
178  }
179  else
180  {
181  //Clear client key
182  osStrcpy(webSocket->handshakeContext.clientKey, "");
183 
184  //Debug message
185  TRACE_DEBUG("WebSocket: client handshake\r\n");
186  }
187 
188  //Decode the leading line
190  }
191  else if(rxContext->state == WS_SUB_STATE_HANDSHAKE_LEADING_LINE)
192  {
193  //Check whether more data is required
194  if(rxContext->bufferLen < 2)
195  {
196  //Limit the number of characters to read at a time
197  n = WEB_SOCKET_BUFFER_SIZE - 1 - rxContext->bufferLen;
198 
199  //Read data until a CLRF character is encountered
200  error = webSocketReceiveData(webSocket, rxContext->buffer +
201  rxContext->bufferLen, n, &n, SOCKET_FLAG_BREAK_CRLF);
202 
203  //Update the length of the buffer
204  rxContext->bufferLen += n;
205  }
206  else if(rxContext->bufferLen >= (WEB_SOCKET_BUFFER_SIZE - 1))
207  {
208  //Report an error
209  error = ERROR_INVALID_REQUEST;
210  }
211  else if(osStrncmp((char_t *) rxContext->buffer + rxContext->bufferLen - 2,
212  "\r\n", 2) != 0)
213  {
214  //Limit the number of characters to read at a time
215  n = WEB_SOCKET_BUFFER_SIZE - 1 - rxContext->bufferLen;
216 
217  //Read data until a CLRF character is encountered
218  error = webSocketReceiveData(webSocket, rxContext->buffer +
219  rxContext->bufferLen, n, &n, SOCKET_FLAG_BREAK_CRLF);
220 
221  //Update the length of the buffer
222  rxContext->bufferLen += n;
223  }
224  else
225  {
226  //Properly terminate the string with a NULL character
227  rxContext->buffer[rxContext->bufferLen] = '\0';
228 
229  //Client or server operation?
230  if(webSocket->endpoint == WS_ENDPOINT_CLIENT)
231  {
232  //The leading line from the server follows the Status-Line format
233  error = webSocketParseStatusLine(webSocket, (char_t *) rxContext->buffer);
234  }
235  else
236  {
237  //The leading line from the client follows the Request-Line format
238  error = webSocketParseRequestLine(webSocket, (char_t *) rxContext->buffer);
239  }
240 
241  //Flush the receive buffer
242  rxContext->bufferPos = 0;
243  rxContext->bufferLen = 0;
244 
245  //Parse the header fields of the handshake
247  }
248  }
249  else if(rxContext->state == WS_SUB_STATE_HANDSHAKE_HEADER_FIELD)
250  {
251  //Check whether more data is required
252  if(rxContext->bufferLen < 2)
253  {
254  //Limit the number of characters to read at a time
255  n = WEB_SOCKET_BUFFER_SIZE - 1 - rxContext->bufferLen;
256 
257  //Read data until a CLRF character is encountered
258  error = webSocketReceiveData(webSocket, rxContext->buffer +
259  rxContext->bufferLen, n, &n, SOCKET_FLAG_BREAK_CRLF);
260 
261  //Update the length of the buffer
262  rxContext->bufferLen += n;
263  }
264  else if(rxContext->bufferLen >= (WEB_SOCKET_BUFFER_SIZE - 1))
265  {
266  //Report an error
267  error = ERROR_INVALID_REQUEST;
268  }
269  else if(osStrncmp((char_t *) rxContext->buffer + rxContext->bufferLen - 2,
270  "\r\n", 2) != 0)
271  {
272  //Limit the number of characters to read at a time
273  n = WEB_SOCKET_BUFFER_SIZE - 1 - rxContext->bufferLen;
274 
275  //Read data until a CLRF character is encountered
276  error = webSocketReceiveData(webSocket, rxContext->buffer +
277  rxContext->bufferLen, n, &n, SOCKET_FLAG_BREAK_CRLF);
278 
279  //Update the length of the buffer
280  rxContext->bufferLen += n;
281  }
282  else
283  {
284  //Properly terminate the string with a NULL character
285  rxContext->buffer[rxContext->bufferLen] = '\0';
286 
287  //An empty line indicates the end of the header fields
288  if(osStrcmp((char_t *) rxContext->buffer, "\r\n") == 0)
289  {
290  //Client or server operation?
291  if(webSocket->endpoint == WS_ENDPOINT_CLIENT)
292  {
293  //Verify server's handshake
294  error = webSocketVerifyServerHandshake(webSocket);
295  }
296  else
297  {
298  //Verify client's handshake
299  error = webSocketVerifyClientHandshake(webSocket);
300  }
301  }
302  else
303  {
304  //Read the next character to detect if the CRLF is immediately
305  //followed by a LWSP character
306  rxContext->state = WS_SUB_STATE_HANDSHAKE_LWSP;
307  }
308  }
309  }
310  else if(rxContext->state == WS_SUB_STATE_HANDSHAKE_LWSP)
311  {
312  char_t nextChar;
313 
314  //Read the next character
315  error = webSocketReceiveData(webSocket, &nextChar, sizeof(char_t), &n, 0);
316 
317  //Successful read operation?
318  if(!error && n == sizeof(char_t))
319  {
320  //LWSP character found?
321  if(nextChar == ' ' || nextChar == '\t')
322  {
323  //Unfolding is accomplished by regarding CRLF immediately
324  //followed by a LWSP as equivalent to the LWSP character
325  if(rxContext->bufferLen >= 2)
326  {
327  //Remove trailing CRLF sequence
328  rxContext->bufferLen -= 2;
329  }
330 
331  //The header field spans multiple line
333  }
334  else
335  {
336  //Parse header field
337  error = webSocketParseHeaderField(webSocket, (char_t *) rxContext->buffer);
338 
339  //Restore the very first character of the header field
340  rxContext->buffer[0] = nextChar;
341  //Adjust the length of the receive buffer
342  rxContext->bufferLen = sizeof(char_t);
343 
344  //Decode the next header field
346  }
347  }
348  }
349  else
350  {
351  //Invalid state
352  error = ERROR_WRONG_STATE;
353  }
354 
355  //Any error to report?
356  if(error)
357  {
358  break;
359  }
360  }
361 
362  //Return status code
363  return error;
364 }
365 
366 
367 /**
368  * @brief Parse the Request-Line of the client's handshake
369  * @param[in] webSocket Handle to a WebSocket
370  * @param[in] line NULL-terminated string that contains the Request-Line
371  * @return Error code
372  **/
373 
375 {
376  error_t error;
377  char_t *token;
378  char_t *p;
379  char_t *s;
380 
381  //Debug message
382  TRACE_DEBUG("%s", line);
383 
384  //The Request-Line begins with a method token
385  token = osStrtok_r(line, " \r\n", &p);
386  //Unable to retrieve the method?
387  if(token == NULL)
388  {
389  return ERROR_INVALID_REQUEST;
390  }
391 
392  //The method of the request must be GET
393  if(osStrcasecmp(token, "GET") != 0)
394  {
395  return ERROR_INVALID_REQUEST;
396  }
397 
398  //The Request-URI is following the method token
399  token = osStrtok_r(NULL, " \r\n", &p);
400  //Unable to retrieve the Request-URI?
401  if(token == NULL)
402  {
403  return ERROR_INVALID_REQUEST;
404  }
405 
406  //Check whether a query string is present
407  s = osStrchr(token, '?');
408 
409  //Query string found?
410  if(s != NULL)
411  {
412  //Split the string
413  *s = '\0';
414 
415  //Save the Request-URI
417  webSocket->uri, WEB_SOCKET_URI_MAX_LEN);
418  //Any error to report?
419  if(error)
420  {
421  return ERROR_INVALID_REQUEST;
422  }
423 
424  //Check the length of the query string
426  {
427  return ERROR_INVALID_REQUEST;
428  }
429 
430  //Save the query string
431  osStrcpy(webSocket->queryString, s + 1);
432  }
433  else
434  {
435  //Save the Request-URI
437  webSocket->uri, WEB_SOCKET_URI_MAX_LEN);
438  //Any error to report?
439  if(error)
440  {
441  return ERROR_INVALID_REQUEST;
442  }
443 
444  //No query string
445  webSocket->queryString[0] = '\0';
446  }
447 
448  //The protocol version is following the Request-URI
449  token = osStrtok_r(NULL, " \r\n", &p);
450 
451  //HTTP version 0.9?
452  if(token == NULL)
453  {
454  //Save version number
455  webSocket->handshakeContext.version = WS_HTTP_VERSION_0_9;
456  //Persistent connections are not supported
457  webSocket->handshakeContext.connectionClose = TRUE;
458  }
459  //HTTP version 1.0?
460  else if(osStrcasecmp(token, "HTTP/1.0") == 0)
461  {
462  //Save version number
463  webSocket->handshakeContext.version = WS_HTTP_VERSION_1_0;
464  //By default connections are not persistent
465  webSocket->handshakeContext.connectionClose = TRUE;
466  }
467  //HTTP version 1.1?
468  else if(osStrcasecmp(token, "HTTP/1.1") == 0)
469  {
470  //Save version number
471  webSocket->handshakeContext.version = WS_HTTP_VERSION_1_1;
472  //HTTP 1.1 makes persistent connections the default
473  webSocket->handshakeContext.connectionClose = FALSE;
474  }
475  //HTTP version not supported?
476  else
477  {
478  //Report an error
479  return ERROR_INVALID_REQUEST;
480  }
481 
482  //Successful processing
483  return NO_ERROR;
484 }
485 
486 
487 /**
488  * @brief Parse the Status-Line of the server's handshake
489  * @param[in] webSocket Handle to a WebSocket
490  * @param[in] line NULL-terminated string that contains the Status-Line
491  * @return Error code
492  **/
493 
495 {
496  char_t *p;
497  char_t *token;
498 
499  //Debug message
500  TRACE_DEBUG("%s", line);
501 
502  //Retrieve the HTTP-Version field
503  token = osStrtok_r(line, " ", &p);
504  //Any parsing error?
505  if(token == NULL)
506  {
507  return ERROR_INVALID_SYNTAX;
508  }
509 
510  //Retrieve the Status-Code field
511  token = osStrtok_r(NULL, " ", &p);
512  //Any parsing error?
513  if(token == NULL)
514  {
515  return ERROR_INVALID_SYNTAX;
516  }
517 
518  //Convert the status code
519  webSocket->handshakeContext.statusCode = osStrtoul(token, &p, 10);
520  //Any parsing error?
521  if(*p != '\0')
522  {
523  return ERROR_INVALID_SYNTAX;
524  }
525 
526  //Successful processing
527  return NO_ERROR;
528 }
529 
530 
531 /**
532  * @brief Parse a header field
533  * @param[in] webSocket Handle to a WebSocket
534  * @param[in] line NULL-terminated string that contains the header field
535  * @return Error code
536  **/
537 
539 {
540  char_t *separator;
541  char_t *name;
542  char_t *value;
543  WebSocketHandshakeContext *handshakeContext;
544 
545  //Point to the handshake context
546  handshakeContext = &webSocket->handshakeContext;
547 
548  //Debug message
549  TRACE_DEBUG("%s", line);
550 
551  //Check whether a separator is present
552  separator = osStrchr(line, ':');
553 
554  //Separator found?
555  if(separator != NULL)
556  {
557  //Split the line
558  *separator = '\0';
559 
560  //Get field name and value
561  name = strTrimWhitespace(line);
562  value = strTrimWhitespace(separator + 1);
563 
564  //Upgrade header field found?
565  if(osStrcasecmp(name, "Upgrade") == 0)
566  {
567  if(osStrcasecmp(value, "websocket") == 0)
568  {
569  handshakeContext->upgradeWebSocket = TRUE;
570  }
571 
572  }
573  //Connection header field found?
574  else if(osStrcasecmp(name, "Connection") == 0)
575  {
576  //Parse Connection header field
578  }
579  //Sec-WebSocket-Key header field found?
580  else if(osStrcasecmp(name, "Sec-WebSocket-Key") == 0)
581  {
582  //Server operation?
583  if(webSocket->endpoint == WS_ENDPOINT_SERVER)
584  {
585  //Save the contents of the Sec-WebSocket-Key header field
586  strSafeCopy(handshakeContext->clientKey, value,
588  }
589  }
590  //Sec-WebSocket-Accept header field found?
591  else if(osStrcasecmp(name, "Sec-WebSocket-Accept") == 0)
592  {
593  //Client operation?
594  if(webSocket->endpoint == WS_ENDPOINT_CLIENT)
595  {
596  //Save the contents of the Sec-WebSocket-Accept header field
597  strSafeCopy(handshakeContext->serverKey, value,
599  }
600  }
601 #if (WEB_SOCKET_BASIC_AUTH_SUPPORT == ENABLED || WEB_SOCKET_DIGEST_AUTH_SUPPORT == ENABLED)
602  //WWW-Authenticate header field found?
603  else if(osStrcasecmp(name, "WWW-Authenticate") == 0)
604  {
605  //Parse WWW-Authenticate header field
607  }
608 #endif
609  //Content-Length header field found?
610  else if(osStrcasecmp(name, "Content-Length") == 0)
611  {
612  handshakeContext->contentLength = osStrtoul(value, NULL, 10);
613  }
614  }
615 
616  //Successful processing
617  return NO_ERROR;
618 }
619 
620 
621 /**
622  * @brief Parse Connection header field
623  * @param[in] webSocket Handle to a WebSocket
624  * @param[in] value NULL-terminated string that contains the value of header field
625  **/
626 
628 {
629  char_t *p;
630  char_t *token;
631 
632  //Get the first value of the list
633  token = osStrtok_r(value, ",", &p);
634 
635  //Parse the comma-separated list
636  while(token != NULL)
637  {
638  //Trim whitespace characters
640 
641  //Check current value
642  if(osStrcasecmp(value, "keep-alive") == 0)
643  {
644  //The connection is persistent
645  webSocket->handshakeContext.connectionClose = FALSE;
646  }
647  else if(osStrcasecmp(value, "close") == 0)
648  {
649  //The connection will be closed after completion of the response
650  webSocket->handshakeContext.connectionClose = TRUE;
651  }
652  else if(osStrcasecmp(value, "upgrade") == 0)
653  {
654  //Upgrade the connection
655  webSocket->handshakeContext.connectionUpgrade = TRUE;
656  }
657 
658  //Get next value
659  token = osStrtok_r(NULL, ",", &p);
660  }
661 }
662 
663 
664 /**
665  * @brief Format client's handshake
666  * @param[in] webSocket Handle to a WebSocket
667  * @param[in] serverPort TCP port number used to establish the connection
668  * @return Error code
669  **/
670 
671 error_t webSocketFormatClientHandshake(WebSocket *webSocket, uint16_t serverPort)
672 {
673  char_t *p;
674  WebSocketFrameContext *txContext;
675 
676  //Point to the TX context
677  txContext = &webSocket->txContext;
678  //Point to the buffer where to format the client's handshake
679  p = (char_t *) txContext->buffer;
680 
681  //The Request-Line begins with a method token, followed by the
682  //Request-URI and the protocol version, and ending with CRLF
683  p += osSprintf(p, "GET %s HTTP/1.1\r\n", webSocket->uri);
684 
685  //Add Host header field
686  if(webSocket->host[0] != '\0')
687  {
688  //The Host header field specifies the Internet host and port number of
689  //the resource being requested
690  p += osSprintf(p, "Host: %s:%d\r\n", webSocket->host, serverPort);
691  }
692  else
693  {
694  //If the requested URI does not include a host name for the service being
695  //requested, then the Host header field must be given with an empty value
696  p += osSprintf(p, "Host:\r\n");
697  }
698 
699 #if (WEB_SOCKET_BASIC_AUTH_SUPPORT == ENABLED || WEB_SOCKET_DIGEST_AUTH_SUPPORT == ENABLED)
700  //Check whether authentication is required
701  if(webSocket->authContext.selectedAuthMode != WS_AUTH_MODE_NONE)
702  {
703  //Add Authorization header field
704  p += webSocketAddAuthorizationField(webSocket, p);
705  }
706 #endif
707 
708  //Add Origin header field
709  if(webSocket->origin[0] != '\0')
710  {
711  p += osSprintf(p, "Origin: %s\r\n", webSocket->origin);
712  }
713  else
714  {
715  p += osSprintf(p, "Origin: null\r\n");
716  }
717 
718  //Add Upgrade header field
719  p += osSprintf(p, "Upgrade: websocket\r\n");
720  //Add Connection header field
721  p += osSprintf(p, "Connection: Upgrade\r\n");
722 
723  //Add Sec-WebSocket-Protocol header field
724  if(webSocket->subProtocol[0] != '\0')
725  {
726  p += osSprintf(p, "Sec-WebSocket-Protocol: %s\r\n", webSocket->subProtocol);
727  }
728 
729  //Add Sec-WebSocket-Key header field
730  p += osSprintf(p, "Sec-WebSocket-Key: %s\r\n",
731  webSocket->handshakeContext.clientKey);
732 
733  //Add Sec-WebSocket-Version header field
734  p += osSprintf(p, "Sec-WebSocket-Version: 13\r\n");
735  //An empty line indicates the end of the header fields
736  p += osSprintf(p, "\r\n");
737 
738  //Debug message
739  TRACE_DEBUG("\r\n");
740  TRACE_DEBUG("WebSocket: client handshake\r\n");
741  TRACE_DEBUG("%s", txContext->buffer);
742 
743  //Rewind to the beginning of the buffer
744  txContext->bufferPos = 0;
745  //Update the number of data buffered but not yet sent
746  txContext->bufferLen = osStrlen((char_t *) txContext->buffer);
747 
748  //Successful processing
749  return NO_ERROR;
750 }
751 
752 
753 /**
754  * @brief Format server's handshake
755  * @param[in] webSocket Handle to a WebSocket
756  * @return Error code
757  **/
758 
760 {
761  char_t *p;
762  WebSocketFrameContext *txContext;
763 
764  //Point to the TX context
765  txContext = &webSocket->txContext;
766  //Point to the buffer where to format the client's handshake
767  p = (char_t *) txContext->buffer;
768 
769  //The first line is an HTTP Status-Line, with the status code 101
770  p += osSprintf(p, "HTTP/1.1 101 Switching Protocols\r\n");
771 
772  //Add Upgrade header field
773  p += osSprintf(p, "Upgrade: websocket\r\n");
774  //Add Connection header field
775  p += osSprintf(p, "Connection: Upgrade\r\n");
776 
777  //Add Sec-WebSocket-Protocol header field
778  if(webSocket->subProtocol[0] != '\0')
779  {
780  p += osSprintf(p, "Sec-WebSocket-Protocol: %s\r\n", webSocket->subProtocol);
781  }
782 
783  //Add Sec-WebSocket-Accept header field
784  p += osSprintf(p, "Sec-WebSocket-Accept: %s\r\n",
785  webSocket->handshakeContext.serverKey);
786 
787  //An empty line indicates the end of the header fields
788  p += osSprintf(p, "\r\n");
789 
790  //Debug message
791  TRACE_DEBUG("\r\n");
792  TRACE_DEBUG("WebSocket: server handshake\r\n");
793  TRACE_DEBUG("%s", txContext->buffer);
794 
795  //Rewind to the beginning of the buffer
796  txContext->bufferPos = 0;
797  //Update the number of data buffered but not yet sent
798  txContext->bufferLen = osStrlen((char_t *) txContext->buffer);
799 
800  //Successful processing
801  return NO_ERROR;
802 }
803 
804 
805 /**
806  * @brief Format HTTP error response
807  * @param[in] webSocket Handle to a WebSocket
808  * @param[in] statusCode HTTP status code
809  * @param[in] message User message
810  * @return Error code
811  **/
812 
814  uint_t statusCode, const char_t *message)
815 {
816  uint_t i;
817  size_t length;
818  char_t *p;
819  WebSocketFrameContext *txContext;
820 
821  //HTML response template
822  static const char_t template[] =
823  "<!doctype html>\r\n"
824  "<html>\r\n"
825  "<head><title>Error %03d</title></head>\r\n"
826  "<body>\r\n"
827  "<h2>Error %03d</h2>\r\n"
828  "<p>%s</p>\r\n"
829  "</body>\r\n"
830  "</html>\r\n";
831 
832  //Point to the TX context
833  txContext = &webSocket->txContext;
834  //Point to the buffer where to format the client's handshake
835  p = (char_t *) txContext->buffer;
836 
837  //The first line of a response message is the Status-Line, consisting
838  //of the protocol version followed by a numeric status code and its
839  //associated textual phrase
840  p += osSprintf(p, "HTTP/%u.%u %u ", MSB(webSocket->handshakeContext.version),
841  LSB(webSocket->handshakeContext.version), statusCode);
842 
843  //Retrieve the Reason-Phrase that corresponds to the Status-Code
844  for(i = 0; i < arraysize(statusCodeList); i++)
845  {
846  //Check the status code
847  if(statusCodeList[i].value == statusCode)
848  {
849  //Append the textual phrase to the Status-Line
850  p += osSprintf(p, "%s", statusCodeList[i].message);
851  //Break the loop and continue processing
852  break;
853  }
854  }
855 
856  //Properly terminate the Status-Line
857  p += osSprintf(p, "\r\n");
858 
859  //Content type
860  p += osSprintf(p, "Content-Type: %s\r\n", "text/html");
861 
862  //Compute the length of the response
863  length = osStrlen(template) + osStrlen(message) - 4;
864  //Set Content-Length field
865  p += osSprintf(p, "Content-Length: %" PRIuSIZE "\r\n", length);
866 
867  //Terminate the header with an empty line
868  p += osSprintf(p, "\r\n");
869 
870  //Format HTML response
871  p += osSprintf(p, template, statusCode, statusCode, message);
872 
873  //Rewind to the beginning of the buffer
874  txContext->bufferPos = 0;
875  //Update the number of data buffered but not yet sent
876  txContext->bufferLen = osStrlen((char_t *) txContext->buffer);
877 
878  //Successful processing
879  return NO_ERROR;
880 }
881 
882 
883 /**
884  * @brief Verify client's handshake
885  * @param[in] webSocket Handle to a WebSocket
886  * @return Error code
887  **/
888 
890 {
891  error_t error;
892  WebSocketHandshakeContext *handshakeContext;
893 
894  //Debug message
895  TRACE_DEBUG("WebSocket: verifying client handshake\r\n");
896 
897  //Point to the handshake context
898  handshakeContext = &webSocket->handshakeContext;
899 
900  //The HTTP version must be at least 1.1
901  if(handshakeContext->version < WS_HTTP_VERSION_1_1)
902  {
903  return ERROR_INVALID_REQUEST;
904  }
905 
906  //The request must contain an Upgrade header field whose value
907  //must include the "websocket" keyword
908  if(!handshakeContext->upgradeWebSocket)
909  {
910  return ERROR_INVALID_REQUEST;
911  }
912 
913  //The request must contain a Connection header field whose value
914  //must include the "Upgrade" token
915  if(!handshakeContext->connectionUpgrade)
916  {
917  return ERROR_INVALID_REQUEST;
918  }
919 
920  //The request must include a header field with the name Sec-WebSocket-Key
921  if(handshakeContext->clientKey[0] == 0)
922  {
923  return ERROR_INVALID_REQUEST;
924  }
925 
926  //Check the Sec-WebSocket-Key header field
927  error = webSocketVerifyClientKey(webSocket);
928  //Verification failed?
929  if(error)
930  {
931  return error;
932  }
933 
934  //Generate the server part of the handshake
936 
937  //Successful processing
938  return NO_ERROR;
939 }
940 
941 
942 /**
943  * @brief Verify server's handshake
944  * @param[in] webSocket Handle to a WebSocket
945  * @return Error code
946  **/
947 
949 {
950  error_t error;
951  WebSocketHandshakeContext *handshakeContext;
952 
953  //Debug message
954  TRACE_DEBUG("WebSocket: verifying server handshake\r\n");
955 
956  //Point to the handshake context
957  handshakeContext = &webSocket->handshakeContext;
958 
959  //If the status code received from the server is not 101, the client
960  //handles the response per HTTP procedures
961  if(handshakeContext->statusCode == 401)
962  {
963  //Authorization required
964  return ERROR_AUTH_REQUIRED;
965  }
966  else if(handshakeContext->statusCode != 101)
967  {
968  //Unknown status code
969  return ERROR_INVALID_STATUS;
970  }
971 
972  //If the response lacks an Upgrade header field or the Upgrade header field
973  //contains a value that is not an ASCII case-insensitive match for the
974  //value "websocket", the client must fail the WebSocket connection
975  if(!handshakeContext->upgradeWebSocket)
976  {
977  return ERROR_INVALID_SYNTAX;
978  }
979 
980  //If the response lacks a Connection header field or the Connection header
981  //field doesn't contain a token that is an ASCII case-insensitive match for
982  //the value "Upgrade", the client must fail the WebSocket connection
983  if(!handshakeContext->connectionUpgrade)
984  {
985  return ERROR_INVALID_SYNTAX;
986  }
987 
988  //If the response lacks a Sec-WebSocket-Accept header field, the client
989  //must fail the WebSocket connection
990  if(osStrlen(handshakeContext->serverKey) == 0)
991  {
992  return ERROR_INVALID_SYNTAX;
993  }
994 
995  //Check the Sec-WebSocket-Accept header field
996  error = webSocketVerifyServerKey(webSocket);
997  //Verification failed?
998  if(error)
999  {
1000  return error;
1001  }
1002 
1003  //If the server's response is validated as provided for above, it is
1004  //said that the WebSocket connection is established and that the
1005  //WebSocket connection is in the OPEN state
1006  webSocketChangeState(webSocket, WS_STATE_OPEN);
1007 
1008  //Successful processing
1009  return NO_ERROR;
1010 }
1011 
1012 
1013 /**
1014  * @brief Generate client's key
1015  * @param[in] webSocket Handle to a WebSocket
1016  * @return Error code
1017  **/
1018 
1020 {
1021  error_t error;
1022  size_t n;
1023  uint8_t nonce[16];
1024  WebSocketHandshakeContext *handshakeContext;
1025 
1026  //Debug message
1027  TRACE_DEBUG("WebSocket: Generating client's key...\r\n");
1028 
1029  //Point to the handshake context
1030  handshakeContext = &webSocket->handshakeContext;
1031 
1032  //Make sure that the RNG callback function has been registered
1033  if(webSockRandCallback == NULL)
1034  {
1035  //A cryptographically strong random number generator
1036  //must be used to generate the nonce
1037  return ERROR_PRNG_NOT_READY;
1038  }
1039 
1040  //A nonce must be selected randomly for each connection
1041  error = webSockRandCallback(nonce, sizeof(nonce));
1042  //Any error to report?
1043  if(error)
1044  {
1045  return error;
1046  }
1047 
1048  //Encode the client's key
1049  base64Encode(nonce, sizeof(nonce), handshakeContext->clientKey, &n);
1050 
1051  //Debug message
1052  TRACE_DEBUG(" Client key: %s\r\n", handshakeContext->clientKey);
1053 
1054  //Successful processing
1055  return NO_ERROR;
1056 }
1057 
1058 
1059 /**
1060  * @brief Generate server's key
1061  * @param[in] webSocket Handle to a WebSocket
1062  * @return Error code
1063  **/
1064 
1066 {
1067  size_t n;
1068  WebSocketHandshakeContext *handshakeContext;
1069  Sha1Context sha1Context;
1070  uint8_t digest[SHA1_DIGEST_SIZE];
1071 
1072  //Debug message
1073  TRACE_DEBUG("WebSocket: Generating server's key...\r\n");
1074 
1075  //Point to the handshake context
1076  handshakeContext = &webSocket->handshakeContext;
1077 
1078  //Retrieve the length of the client key
1079  n = osStrlen(handshakeContext->clientKey);
1080 
1081  //Concatenate the Sec-WebSocket-Key with the GUID string and digest
1082  //the resulting string using SHA-1
1083  sha1Init(&sha1Context);
1084  sha1Update(&sha1Context, handshakeContext->clientKey, n);
1086  sha1Final(&sha1Context, digest);
1087 
1088  //Encode the result using Base64
1089  base64Encode(digest, SHA1_DIGEST_SIZE, handshakeContext->serverKey, &n);
1090 
1091  //Debug message
1092  TRACE_DEBUG(" Server key: %s\r\n", handshakeContext->serverKey);
1093 
1094  //Successful processing
1095  return NO_ERROR;
1096 }
1097 
1098 
1099 /**
1100  * @brief Verify client's key
1101  * @param[in] webSocket Handle to a WebSocket
1102  * @return Error code
1103  **/
1104 
1106 {
1107  error_t error;
1108  size_t n;
1109  char_t *buffer;
1110  WebSocketHandshakeContext *handshakeContext;
1111 
1112  //Debug message
1113  TRACE_DEBUG("WebSocket: Verifying client's key...\r\n");
1114 
1115  //Temporary buffer
1116  buffer = (char_t *) webSocket->txContext.buffer;
1117 
1118  //Point to the handshake context
1119  handshakeContext = &webSocket->handshakeContext;
1120 
1121  //Retrieve the length of the client's key
1122  n = osStrlen(handshakeContext->clientKey);
1123 
1124  //The value of the Sec-WebSocket-Key header field must be a 16-byte
1125  //value that has been Base64-encoded
1126  error = base64Decode(handshakeContext->clientKey, n, buffer, &n);
1127  //Decoding failed?
1128  if(error)
1129  {
1130  return ERROR_INVALID_KEY;
1131  }
1132 
1133  //Check the length of the resulting value
1134  if(n != 16)
1135  {
1136  return ERROR_INVALID_KEY;
1137  }
1138 
1139  //Successful verification
1140  return NO_ERROR;
1141 }
1142 
1143 
1144 /**
1145  * @brief Verify server's key
1146  * @param[in] webSocket Handle to a WebSocket
1147  * @return Error code
1148  **/
1149 
1151 {
1152  size_t n;
1153  char_t *buffer;
1154  WebSocketHandshakeContext *handshakeContext;
1155  Sha1Context sha1Context;
1156  uint8_t digest[SHA1_DIGEST_SIZE];
1157 
1158  //Debug message
1159  TRACE_DEBUG("WebSocket: Verifying server's key...\r\n");
1160 
1161  //Temporary buffer
1162  buffer = (char_t *) webSocket->txContext.buffer;
1163 
1164  //Point to the handshake context
1165  handshakeContext = &webSocket->handshakeContext;
1166 
1167  //Retrieve the length of the client's key
1168  n = osStrlen(handshakeContext->clientKey);
1169 
1170  //Concatenate the Sec-WebSocket-Key with the GUID string and digest
1171  //the resulting string using SHA-1
1172  sha1Init(&sha1Context);
1173  sha1Update(&sha1Context, handshakeContext->clientKey, n);
1175  sha1Final(&sha1Context, digest);
1176 
1177  //Encode the result using Base64
1178  base64Encode(digest, SHA1_DIGEST_SIZE, buffer, &n);
1179 
1180  //Debug message
1181  TRACE_DEBUG(" Client key: %s\r\n", handshakeContext->clientKey);
1182  TRACE_DEBUG(" Server key: %s\r\n", handshakeContext->serverKey);
1183  TRACE_DEBUG(" Calculated key: %s\r\n", webSocket->txContext.buffer);
1184 
1185  //Check whether the server's key is valid
1186  if(osStrcmp(handshakeContext->serverKey, buffer) != 0)
1187  {
1188  return ERROR_INVALID_KEY;
1189  }
1190 
1191  //Successful verification
1192  return NO_ERROR;
1193 }
1194 
1195 
1196 /**
1197  * @brief Check whether a status code is valid
1198  * @param[in] statusCode Status code
1199  * @return The function returns TRUE is the specified status code is
1200  * valid. Otherwise, FALSE is returned
1201  **/
1202 
1203 bool_t webSocketCheckStatusCode(uint16_t statusCode)
1204 {
1205  bool_t valid;
1206 
1207  //Check status code
1208  if(statusCode == WS_STATUS_CODE_NORMAL_CLOSURE ||
1209  statusCode == WS_STATUS_CODE_GOING_AWAY ||
1210  statusCode == WS_STATUS_CODE_PROTOCOL_ERROR ||
1211  statusCode == WS_STATUS_CODE_UNSUPPORTED_DATA ||
1212  statusCode == WS_STATUS_CODE_INVALID_PAYLOAD_DATA ||
1213  statusCode == WS_STATUS_CODE_POLICY_VIOLATION ||
1214  statusCode == WS_STATUS_CODE_MESSAGE_TOO_BIG ||
1215  statusCode == WS_STATUS_CODE_MANDATORY_EXT ||
1216  statusCode == WS_STATUS_CODE_INTERNAL_ERROR)
1217  {
1218  valid = TRUE;
1219  }
1220  else if(statusCode >= 3000)
1221  {
1222  valid = TRUE;
1223  }
1224  else
1225  {
1226  valid = FALSE;
1227  }
1228 
1229  //The function returns TRUE is the specified status code is valid
1230  return valid;
1231 }
1232 
1233 
1234 /**
1235  * @brief Decode a percent-encoded string
1236  * @param[in] input NULL-terminated string to be decoded
1237  * @param[out] output NULL-terminated string resulting from the decoding process
1238  * @param[in] outputSize Size of the output buffer in bytes
1239  * @return Error code
1240  **/
1241 
1243  char_t *output, size_t outputSize)
1244 {
1245  size_t i;
1246  char_t buffer[3];
1247 
1248  //Check parameters
1249  if(input == NULL || output == NULL)
1250  {
1251  return ERROR_INVALID_PARAMETER;
1252  }
1253 
1254  //Decode the percent-encoded string
1255  for(i = 0; *input != '\0' && i < outputSize; i++)
1256  {
1257  //Check current character
1258  if(*input == '+')
1259  {
1260  //Replace '+' characters with spaces
1261  output[i] = ' ';
1262  //Advance data pointer
1263  input++;
1264  }
1265  else if(input[0] == '%' && input[1] != '\0' && input[2] != '\0')
1266  {
1267  //Process percent-encoded characters
1268  buffer[0] = input[1];
1269  buffer[1] = input[2];
1270  buffer[2] = '\0';
1271  //String to integer conversion
1272  output[i] = (uint8_t) osStrtoul(buffer, NULL, 16);
1273  //Advance data pointer
1274  input += 3;
1275  }
1276  else
1277  {
1278  //Copy any other characters
1279  output[i] = *input;
1280  //Advance data pointer
1281  input++;
1282  }
1283  }
1284 
1285  //Check whether the output buffer runs out of space
1286  if(i >= outputSize)
1287  {
1288  return ERROR_FAILURE;
1289  }
1290 
1291  //Properly terminate the resulting string
1292  output[i] = '\0';
1293  //Successful processing
1294  return NO_ERROR;
1295 }
1296 
1297 
1298 /**
1299  * @brief Check whether a an UTF-8 stream is valid
1300  * @param[in] context UTF-8 decoding context
1301  * @param[in] data Pointer to the chunk of data to be processed
1302  * @param[in] length Data chunk length
1303  * @param[in] remaining number of remaining bytes in the UTF-8 stream
1304  * @return The function returns TRUE is the specified UTF-8 stream is
1305  * valid. Otherwise, FALSE is returned
1306  **/
1307 
1309  const uint8_t *data, size_t length, size_t remaining)
1310 {
1311  size_t i;
1312  bool_t valid;
1313 
1314  //Initialize flag
1315  valid = TRUE;
1316 
1317  //Interpret the byte stream as UTF-8
1318  for(i = 0; i < length && valid; i++)
1319  {
1320  //Leading or continuation byte?
1321  if(context->utf8CharIndex == 0)
1322  {
1323  //7-bit code point?
1324  if((data[i] & 0x80) == 0x00)
1325  {
1326  //The code point consist of a single byte
1327  context->utf8CharSize = 1;
1328  //Decode the first byte of the sequence
1329  context->utf8CodePoint = data[i] & 0x7F;
1330  }
1331  //11-bit code point?
1332  else if((data[i] & 0xE0) == 0xC0)
1333  {
1334  //The code point consist of a 2 bytes
1335  context->utf8CharSize = 2;
1336  //Decode the first byte of the sequence
1337  context->utf8CodePoint = (data[i] & 0x1F) << 6;
1338  }
1339  //16-bit code point?
1340  else if((data[i] & 0xF0) == 0xE0)
1341  {
1342  //The code point consist of a 3 bytes
1343  context->utf8CharSize = 3;
1344  //Decode the first byte of the sequence
1345  context->utf8CodePoint = (data[i] & 0x0F) << 12;
1346  }
1347  //21-bit code point?
1348  else if((data[i] & 0xF8) == 0xF0)
1349  {
1350  //The code point consist of a 3 bytes
1351  context->utf8CharSize = 4;
1352  //Decode the first byte of the sequence
1353  context->utf8CodePoint = (data[i] & 0x07) << 18;
1354  }
1355  else
1356  {
1357  //The UTF-8 stream is not valid
1358  valid = FALSE;
1359  }
1360 
1361  //This test only applies to frames that are not fragmented
1362  if(length <= remaining)
1363  {
1364  //Make sure the UTF-8 stream is properly terminated
1365  if((i + context->utf8CharSize) > remaining)
1366  {
1367  //The UTF-8 stream is not valid
1368  valid = FALSE;
1369  }
1370  }
1371 
1372  //Decode the next byte of the sequence
1373  context->utf8CharIndex = context->utf8CharSize - 1;
1374  }
1375  else
1376  {
1377  //Continuation bytes all have 10 in the high-order position
1378  if((data[i] & 0xC0) == 0x80)
1379  {
1380  //Decode the multi-byte sequence
1381  context->utf8CharIndex--;
1382  //All continuation bytes contain exactly 6 bits from the code point
1383  context->utf8CodePoint |= (data[i] & 0x3F) << (context->utf8CharIndex * 6);
1384 
1385  //The correct encoding of a code point use only the minimum number
1386  //of bytes required to hold the significant bits of the code point
1387  if(context->utf8CharSize == 2)
1388  {
1389  //Overlong encoding is not supported
1390  if((context->utf8CodePoint & ~0x7F) == 0)
1391  {
1392  valid = FALSE;
1393  }
1394  }
1395 
1396  if(context->utf8CharSize == 3 && context->utf8CharIndex < 2)
1397  {
1398  //Overlong encoding is not supported
1399  if((context->utf8CodePoint & ~0x7FF) == 0)
1400  {
1401  valid = FALSE;
1402  }
1403  }
1404 
1405  if(context->utf8CharSize == 4 && context->utf8CharIndex < 3)
1406  {
1407  //Overlong encoding is not supported
1408  if((context->utf8CodePoint & ~0xFFFF) == 0)
1409  {
1410  valid = FALSE;
1411  }
1412  }
1413 
1414  //According to the UTF-8 definition (RFC 3629) the high and low
1415  //surrogate halves used by UTF-16 (U+D800 through U+DFFF) are not
1416  //legal Unicode values, and their UTF-8 encoding should be treated
1417  //as an invalid byte sequence
1418  if(context->utf8CodePoint >= 0xD800 && context->utf8CodePoint < 0xE000)
1419  {
1420  valid = FALSE;
1421  }
1422 
1423  //Code points greater than U+10FFFF are not valid
1424  if(context->utf8CodePoint >= 0x110000)
1425  {
1426  valid = FALSE;
1427  }
1428  }
1429  else
1430  {
1431  //The start byte is not followed by enough continuation bytes
1432  valid = FALSE;
1433  }
1434  }
1435  }
1436 
1437  //The function returns TRUE is the specified UTF-8 stream is valid
1438  return valid;
1439 }
1440 
1441 #endif
#define WEB_SOCKET_BUFFER_SIZE
Definition: web_socket.h:82
@ WS_STATUS_CODE_GOING_AWAY
Definition: web_socket.h:280
@ WS_STATUS_CODE_UNSUPPORTED_DATA
Definition: web_socket.h:282
char_t name[]
#define osStrchr(s, c)
Definition: os_port.h:201
String manipulation helper functions.
HTTP status code.
int bool_t
Definition: compiler_port.h:63
@ WS_AUTH_MODE_NONE
Definition: web_socket.h:214
void sha1Update(Sha1Context *context, const void *data, size_t length)
Update the SHA-1 context with a portion of the message being hashed.
#define WEB_SOCKET_CLIENT_KEY_SIZE
Definition: web_socket.h:171
SHA-1 (Secure Hash Algorithm 1)
uint8_t p
Definition: ndp.h:300
char_t * strTrimWhitespace(char_t *s)
Removes all leading and trailing whitespace from a string.
Definition: str.c:78
error_t webSocketFormatErrorResponse(WebSocket *webSocket, uint_t statusCode, const char_t *message)
Format HTTP error response.
WebSocket API (client and server)
@ WS_HTTP_VERSION_1_0
Definition: web_socket.h:203
uint8_t message[]
Definition: chap.h:154
HTTP authentication for WebSockets.
#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.
uint8_t data[]
Definition: ethernet.h:224
void base64Encode(const void *input, size_t inputLen, char_t *output, size_t *outputLen)
Base64 encoding algorithm.
Definition: base64.c:142
Helper functions for WebSockets.
@ WS_STATUS_CODE_NO_STATUS_RCVD
Definition: web_socket.h:283
@ ERROR_INVALID_STATUS
Definition: error.h:102
error_t webSocketParseHeaderField(WebSocket *webSocket, char_t *line)
Parse a header field.
#define osStrcmp(s1, s2)
Definition: os_port.h:177
@ ERROR_AUTH_REQUIRED
Definition: error.h:151
#define osStrlen(s)
Definition: os_port.h:171
@ ERROR_PRNG_NOT_READY
Definition: error.h:253
@ WS_HTTP_VERSION_0_9
Definition: web_socket.h:202
void webSocketParseConnectionField(WebSocket *webSocket, char_t *value)
Parse Connection header field.
WebSocket frame parsing and formatting.
const char_t webSocketGuid[]
@ ERROR_WRONG_STATE
Definition: error.h:211
@ WS_SUB_STATE_HANDSHAKE_HEADER_FIELD
Definition: web_socket.h:249
error_t base64Decode(const char_t *input, size_t inputLen, void *output, size_t *outputLen)
Base64 decoding algorithm.
Definition: base64.c:258
#define FALSE
Definition: os_port.h:46
char_t serverKey[WEB_SOCKET_SERVER_KEY_SIZE+1]
Definition: web_socket.h:388
@ ERROR_INVALID_PARAMETER
Invalid parameter.
Definition: error.h:47
void sha1Init(Sha1Context *context)
Initialize SHA-1 message digest context.
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
#define osSprintf(dest,...)
Definition: os_port.h:237
#define osStrtok_r(s, delim, last)
Definition: os_port.h:231
error_t webSocketGenerateClientKey(WebSocket *webSocket)
Generate client's key.
bool_t webSocketCheckStatusCode(uint16_t statusCode)
Check whether a status code is valid.
uint32_t utf8CodePoint
Definition: web_socket.h:422
@ ERROR_FAILURE
Generic error code.
Definition: error.h:45
error_t webSocketVerifyServerKey(WebSocket *webSocket)
Verify server's key.
error_t webSocketReceiveData(WebSocket *webSocket, void *data, size_t size, size_t *received, uint_t flags)
Receive data using the relevant transport protocol.
char_t clientKey[WEB_SOCKET_CLIENT_KEY_SIZE+1]
Definition: web_socket.h:387
Handshake context.
Definition: web_socket.h:380
WebSocketRandCallback webSockRandCallback
Definition: web_socket.c:52
@ WS_ENDPOINT_SERVER
Definition: web_socket.h:192
UTF-8 decoding context.
Definition: web_socket.h:419
#define osStrcasecmp(s1, s2)
Definition: os_port.h:189
error_t webSocketParseStatusLine(WebSocket *webSocket, char_t *line)
Parse the Status-Line of the server's handshake.
Base64 encoding scheme.
@ WS_STATUS_CODE_MESSAGE_TOO_BIG
Definition: web_socket.h:287
#define MSB(x)
Definition: os_port.h:59
uint8_t length
Definition: tcp.h:375
#define LSB(x)
Definition: os_port.h:55
@ WS_STATUS_CODE_INTERNAL_ERROR
Definition: web_socket.h:289
WebSocketState
WebSocket states.
Definition: web_socket.h:225
@ WS_ENDPOINT_CLIENT
Definition: web_socket.h:191
#define WebSocket
Definition: web_socket.h:177
@ WS_SUB_STATE_HANDSHAKE_LEADING_LINE
Definition: web_socket.h:248
error_t webSocketFormatClientHandshake(WebSocket *webSocket, uint16_t serverPort)
Format client's handshake.
error_t webSocketVerifyServerHandshake(WebSocket *webSocket)
Verify server's handshake.
@ WS_STATUS_CODE_POLICY_VIOLATION
Definition: web_socket.h:286
WebSocketSubState state
Definition: web_socket.h:400
#define osStrtoul(s, endptr, base)
Definition: os_port.h:261
@ WS_SUB_STATE_INIT
Definition: web_socket.h:246
#define TRACE_DEBUG(...)
Definition: debug.h:119
char char_t
Definition: compiler_port.h:55
#define SHA1_DIGEST_SIZE
Definition: sha1.h:45
error_t webSocketFormatServerHandshake(WebSocket *webSocket)
Format server's handshake.
error_t strSafeCopy(char_t *dest, const char_t *src, size_t destSize)
Copy string.
Definition: str.c:178
@ 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
error_t webSocketVerifyClientHandshake(WebSocket *webSocket)
Verify client's handshake.
error_t webSocketParseRequestLine(WebSocket *webSocket, char_t *line)
Parse the Request-Line of the client's handshake.
error_t webSocketDecodePercentEncodedString(const char_t *input, char_t *output, size_t outputSize)
Decode a percent-encoded string.
bool_t fin
Final fragment in a message.
Definition: web_socket.h:403
uint8_t value[]
Definition: tcp.h:376
@ ERROR_INVALID_SYNTAX
Definition: error.h:68
@ WS_STATUS_CODE_MANDATORY_EXT
Definition: web_socket.h:288
SHA-1 algorithm context.
Definition: sha1.h:62
uint8_t s
Definition: igmp_common.h:234
@ WS_SUB_STATE_HANDSHAKE_LWSP
Definition: web_socket.h:250
#define WEB_SOCKET_QUERY_STRING_MAX_LEN
Definition: web_socket.h:117
@ WS_STATE_SERVER_HANDSHAKE
Definition: web_socket.h:231
#define WEB_SOCKET_SERVER_KEY_SIZE
Definition: web_socket.h:173
#define osStrncmp(s1, s2, length)
Definition: os_port.h:183
@ WS_STATUS_CODE_PROTOCOL_ERROR
Definition: web_socket.h:281
error_t webSocketParseHandshake(WebSocket *webSocket)
Parse client or server handshake.
WebSocket transport layer.
size_t bufferPos
Current position.
Definition: web_socket.h:410
size_t webSocketAddAuthorizationField(WebSocket *webSocket, char_t *output)
Format Authorization header field.
error_t webSocketVerifyClientKey(WebSocket *webSocket)
Verify client's key.
#define PRIuSIZE
unsigned int uint_t
Definition: compiler_port.h:57
TCP/IP stack core.
@ WS_HTTP_VERSION_1_1
Definition: web_socket.h:204
#define WEB_SOCKET_URI_MAX_LEN
Definition: web_socket.h:110
error_t webSocketGenerateServerKey(WebSocket *webSocket)
Generate server's key.
void sha1Final(Sha1Context *context, uint8_t *digest)
Finish the SHA-1 message digest.
error_t webSocketParseAuthenticateField(WebSocket *webSocket, char_t *value)
Parse WWW-Authenticate header field.
@ WS_STATUS_CODE_NORMAL_CLOSURE
Definition: web_socket.h:279
#define osStrcpy(s1, s2)
Definition: os_port.h:213
@ SOCKET_FLAG_BREAK_CRLF
Definition: socket.h:141
@ ERROR_INVALID_REQUEST
Definition: error.h:65
uint8_t nonce[]
Definition: ntp_common.h:239
@ ERROR_INVALID_KEY
Definition: error.h:106
@ NO_ERROR
Success.
Definition: error.h:44
Debugging facilities.
@ WS_STATE_OPEN
Definition: web_socket.h:233
uint8_t token[]
Definition: coap_common.h:181
void webSocketChangeState(WebSocket *webSocket, WebSocketState newState)
Update WebSocket state.
#define arraysize(a)
Definition: os_port.h:71
systime_t osGetSystemTime(void)
Retrieve system time.