WebSocket.c 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506
  1. /*******************************************************************************
  2. * Copyright (c) 2018, 2024 Wind River Systems, Inc., Ian Craggs and others
  3. *
  4. * All rights reserved. This program and the accompanying materials
  5. * are made available under the terms of the Eclipse Public License v2.0
  6. * and Eclipse Distribution License v1.0 which accompany this distribution.
  7. *
  8. * The Eclipse Public License is available at
  9. * https://www.eclipse.org/legal/epl-2.0/
  10. * and the Eclipse Distribution License is available at
  11. * http://www.eclipse.org/org/documents/edl-v10.php.
  12. *
  13. * Contributors:
  14. * Keith Holman - initial implementation and documentation
  15. * Ian Craggs - use memory tracking
  16. * Ian Craggs - fix for one MQTT packet spread over >1 ws frame
  17. * Sven Gambel - move WebSocket proxy support to generic proxy support
  18. *******************************************************************************/
  19. #include <stdint.h>
  20. #include <stdio.h>
  21. #include <string.h>
  22. #include "WebSocket.h"
  23. #include "Base64.h"
  24. #include "Log.h"
  25. #if defined(OPENSSL) && OPENSSL_VERSION_NUMBER >= 0x030000000
  26. #include "openssl/evp.h"
  27. #else
  28. #include "SHA1.h"
  29. #endif
  30. #include "LinkedList.h"
  31. #include "MQTTProtocolOut.h"
  32. #include "SocketBuffer.h"
  33. #include "StackTrace.h"
  34. #if defined(__linux__)
  35. # include <endian.h>
  36. #elif defined(__APPLE__)
  37. # include <libkern/OSByteOrder.h>
  38. # define htobe16(x) OSSwapHostToBigInt16(x)
  39. # define htobe32(x) OSSwapHostToBigInt32(x)
  40. # define htobe64(x) OSSwapHostToBigInt64(x)
  41. # define be16toh(x) OSSwapBigToHostInt16(x)
  42. # define be32toh(x) OSSwapBigToHostInt32(x)
  43. # define be64toh(x) OSSwapBigToHostInt64(x)
  44. #elif defined(__FreeBSD__) || defined(__NetBSD__)
  45. # include <sys/endian.h>
  46. #elif defined(_WIN32) || defined(_WIN64)
  47. # pragma comment(lib, "rpcrt4.lib")
  48. # include <rpc.h>
  49. # if !(defined(__MINGW32__))
  50. # define strncasecmp(s1,s2,c) _strnicmp(s1,s2,c)
  51. # endif
  52. # if defined(__MINGW32__)
  53. # define htonll __builtin_bswap64
  54. # define ntohll __builtin_bswap64
  55. # else
  56. # define htonll(x) _byteswap_uint64(x)
  57. # define ntohll(x) _byteswap_uint64(x)
  58. # endif
  59. # if BYTE_ORDER == LITTLE_ENDIAN
  60. # define htobe16(x) htons(x)
  61. # define htobe32(x) htonl(x)
  62. # define htobe64(x) htonll(x)
  63. # define be16toh(x) ntohs(x)
  64. # define be32toh(x) ntohl(x)
  65. # define be64toh(x) ntohll(x)
  66. # elif BYTE_ORDER == BIG_ENDIAN
  67. # define htobe16(x) (x)
  68. # define htobe32(x) (x)
  69. # define htobe64(x) (x)
  70. # define be16toh(x) (x)
  71. # define be32toh(x) (x)
  72. # define be64toh(x) (x)
  73. # else
  74. # error "unknown endian"
  75. # endif
  76. /* For Microsoft Visual Studio < 2015 */
  77. # if defined(_MSC_VER) && _MSC_VER < 1900
  78. # define snprintf _snprintf
  79. # endif
  80. #endif
  81. #if defined(OPENSSL)
  82. #include "SSLSocket.h"
  83. #include <openssl/rand.h>
  84. #endif /* defined(OPENSSL) */
  85. #include "Socket.h"
  86. #define HTTP_PROTOCOL(x) x ? "https" : "http"
  87. #if !(defined(_WIN32) || defined(_WIN64))
  88. #if defined(USE_LIBUUID)
  89. #include <uuid/uuid.h>
  90. #else /* if defined(USE_LIBUUID) */
  91. #include <limits.h>
  92. #include <stdlib.h>
  93. #include <time.h>
  94. /** @brief raw uuid type */
  95. typedef unsigned char uuid_t[16];
  96. /**
  97. * @brief generates a uuid, compatible with RFC 4122, version 4 (random)
  98. * @note Uses a very insecure algorithm but no external dependencies
  99. */
  100. static void uuid_generate( uuid_t out )
  101. {
  102. #if defined(OPENSSL)
  103. int rc = RAND_bytes( out, sizeof(uuid_t));
  104. if ( !rc )
  105. #endif /* defined (OPENSSL) */
  106. {
  107. /* very insecure, but generates a random uuid */
  108. int i;
  109. srand(time(NULL));
  110. for ( i = 0; i < 16; ++i )
  111. out[i] = (unsigned char)(rand() % UCHAR_MAX);
  112. out[6] = (out[6] & 0x0f) | 0x40;
  113. out[8] = (out[8] & 0x3F) | 0x80;
  114. }
  115. }
  116. /** @brief converts a uuid to a string */
  117. #if 0
  118. static void uuid_unparse( uuid_t uu, char *out )
  119. {
  120. int i;
  121. for ( i = 0; i < 16; ++i )
  122. {
  123. if ( i == 4 || i == 6 || i == 8 || i == 10 )
  124. {
  125. *out = '-';
  126. ++out;
  127. }
  128. out += sprintf( out, "%02x", uu[i] );
  129. }
  130. *out = '\0';
  131. }
  132. #endif
  133. #endif /* else if defined(USE_LIBUUID) */
  134. #endif /* if !(defined(_WIN32) || defined(_WIN64)) */
  135. #include "Heap.h"
  136. /** raw websocket frame data */
  137. struct ws_frame
  138. {
  139. size_t len; /**< length of frame */
  140. size_t pos; /**< current position within the buffer */
  141. };
  142. /** Current frame being processed */
  143. struct ws_frame *last_frame = NULL;
  144. /** Holds any received websocket frames, to be process */
  145. static List* in_frames = NULL;
  146. static char * frame_buffer = NULL;
  147. static size_t frame_buffer_len = 0;
  148. static size_t frame_buffer_index = 0;
  149. static size_t frame_buffer_data_len = 0;
  150. /* static function declarations */
  151. static const char *WebSocket_strcasefind(
  152. const char *buf, const char *str, size_t len);
  153. static char *WebSocket_getRawSocketData(
  154. networkHandles *net, size_t bytes, size_t* actual_len, int* rc);
  155. static void WebSocket_rewindData( void );
  156. static void WebSocket_pong(
  157. networkHandles *net, char *app_data, size_t app_data_len);
  158. static int WebSocket_receiveFrame(networkHandles *net, size_t *actual_len);
  159. /**
  160. * calculates the amount of data required for the websocket header
  161. *
  162. * this function is used to calculate how much offset is required before calling
  163. * @p WebSocket_putdatas, as that function will write data before the passed in
  164. * buffer
  165. *
  166. * @param[in,out] net network connection
  167. * @param[in] mask_data whether to mask the data
  168. * @param[in] data_len amount of data in the payload
  169. *
  170. * @return the size in bytes of the websocket header required
  171. *
  172. * @see WebSocket_putdatas
  173. */
  174. size_t WebSocket_calculateFrameHeaderSize(networkHandles *net, int mask_data, size_t data_len)
  175. {
  176. int ret = 0;
  177. if ( net && net->websocket )
  178. {
  179. if ( data_len < 126u)
  180. ret = 2; /* header 2 bytes */
  181. else if ( data_len < 65536u )
  182. ret = 4; /* for extra 2-bytes for payload length */
  183. else if ( data_len < 0xFFFFFFFFFFFFFFFF )
  184. ret = 10; /* for extra 8-bytes for payload length */
  185. if ( mask_data & 0x1 )
  186. ret += sizeof(uint32_t); /* for mask */
  187. }
  188. return ret;
  189. }
  190. /**
  191. * @brief builds a websocket frame for data transmission
  192. *
  193. * write a websocket header and will mask the payload in all the passed in
  194. * buffers
  195. *
  196. * @param[in,out] net network connection
  197. * @param[in] opcode websocket opcode for the packet
  198. * @param[in] mask_data whether to mask the data
  199. * @param[in,out] buf0 first buffer, will write before this
  200. * @param[in] buf0len size of first buffer
  201. * @param[in] count number of payload buffers
  202. * @param[in,out] buffers array of payload buffers
  203. * @param[in] buflens array of payload buffer sizes
  204. * @param[in] freeData array indicating to free payload buffers
  205. *
  206. * @return amount of data to write to socket
  207. */
  208. struct frameData {
  209. char* wsbuf0;
  210. size_t wsbuf0len;
  211. };
  212. static struct frameData WebSocket_buildFrame(networkHandles* net, int opcode, int mask_data,
  213. char** pbuf0, size_t* pbuf0len, PacketBuffers* bufs)
  214. {
  215. int buf_len = 0u;
  216. struct frameData rc;
  217. int new_mask = 0;
  218. FUNC_ENTRY;
  219. memset(&rc, '\0', sizeof(rc));
  220. if ( net->websocket )
  221. {
  222. size_t ws_header_size = 0u;
  223. size_t data_len = 0L;
  224. int i;
  225. /* Calculate total length of MQTT buffers */
  226. data_len = *pbuf0len;
  227. for (i = 0; i < bufs->count; ++i)
  228. data_len += bufs->buflens[i];
  229. /* add space for websocket frame header */
  230. ws_header_size = WebSocket_calculateFrameHeaderSize(net, mask_data, data_len);
  231. if (*pbuf0)
  232. {
  233. rc.wsbuf0len = *pbuf0len + ws_header_size;
  234. rc.wsbuf0 = malloc(rc.wsbuf0len);
  235. if (rc.wsbuf0 == NULL)
  236. goto exit;
  237. memcpy(&rc.wsbuf0[ws_header_size], *pbuf0, *pbuf0len);
  238. }
  239. else
  240. {
  241. rc.wsbuf0 = malloc(ws_header_size);
  242. if (rc.wsbuf0 == NULL)
  243. goto exit;
  244. rc.wsbuf0len = ws_header_size;
  245. }
  246. if (mask_data && (bufs->mask[0] == 0))
  247. {
  248. /* generate mask, since we are a client */
  249. #if defined(OPENSSL)
  250. RAND_bytes(&bufs->mask[0], sizeof(bufs->mask));
  251. #else /* if defined(OPENSSL) */
  252. bufs->mask[0] = (rand() % UINT8_MAX);
  253. bufs->mask[1] = (rand() % UINT8_MAX);
  254. bufs->mask[2] = (rand() % UINT8_MAX);
  255. bufs->mask[3] = (rand() % UINT8_MAX);
  256. #endif /* else if defined(OPENSSL) */
  257. new_mask = 1;
  258. }
  259. /* 1st byte */
  260. rc.wsbuf0[buf_len] = (char)(1 << 7); /* final flag */
  261. /* 3 bits reserved for negotiation of protocol */
  262. rc.wsbuf0[buf_len] |= (char)(opcode & 0x0F); /* op code */
  263. ++buf_len;
  264. /* 2nd byte */
  265. rc.wsbuf0[buf_len] = (char)((mask_data & 0x1) << 7); /* masking bit */
  266. /* payload length */
  267. if ( data_len < 126u )
  268. rc.wsbuf0[buf_len++] |= data_len & 0x7F;
  269. /* 3rd byte & 4th bytes - extended payload length */
  270. else if ( data_len < 65536u )
  271. {
  272. uint16_t len = htobe16((uint16_t)data_len);
  273. rc.wsbuf0[buf_len++] |= (126u & 0x7F);
  274. memcpy( &rc.wsbuf0[buf_len], &len, 2u );
  275. buf_len += 2;
  276. }
  277. else if ( data_len < 0xFFFFFFFFFFFFFFFF )
  278. {
  279. uint64_t len = htobe64((uint64_t)data_len);
  280. rc.wsbuf0[buf_len++] |= (127u & 0x7F);
  281. memcpy( &rc.wsbuf0[buf_len], &len, 8 );
  282. buf_len += 8;
  283. }
  284. else
  285. {
  286. Log(TRACE_PROTOCOL, 1, "Data too large for websocket frame" );
  287. buf_len = -1;
  288. }
  289. if (mask_data)
  290. {
  291. size_t idx = 0u;
  292. /* copy masking key into ws header */
  293. memcpy( &rc.wsbuf0[buf_len], &bufs->mask, sizeof(uint32_t));
  294. buf_len += sizeof(uint32_t);
  295. /* mask packet fixed header */
  296. for (i = (int)ws_header_size; i < (int)rc.wsbuf0len; ++i, ++idx)
  297. rc.wsbuf0[i] ^= bufs->mask[idx % 4];
  298. /* variable data buffers */
  299. for (i = 0; i < bufs->count; ++i)
  300. {
  301. size_t j;
  302. if (new_mask == 0 && (i == 2 || i == bufs->count-1))
  303. /* topic (2) and payload (last) buffers are already masked */
  304. break;
  305. for ( j = 0u; j < bufs->buflens[i]; ++j, ++idx )
  306. {
  307. bufs->buffers[i][j] ^= bufs->mask[idx % 4];
  308. }
  309. }
  310. }
  311. }
  312. exit:
  313. FUNC_EXIT_RC(buf_len);
  314. return rc;
  315. }
  316. static void WebSocket_unmaskData(size_t idx, PacketBuffers* bufs)
  317. {
  318. int i;
  319. FUNC_ENTRY;
  320. for (i = 0; i < bufs->count; ++i)
  321. {
  322. size_t j;
  323. for (j = 0u; j < bufs->buflens[i]; ++j, ++idx)
  324. bufs->buffers[i][j] ^= bufs->mask[idx % 4];
  325. }
  326. /* show that the mask has been removed */
  327. bufs->mask[0] = bufs->mask[1] = bufs->mask[2] = bufs->mask[3] = 0;
  328. FUNC_EXIT;
  329. }
  330. /**
  331. * sends out a websocket request on the given uri
  332. *
  333. * @param[in] net network connection
  334. * @param[in] ssl ssl flag
  335. * @param[in] uri uri to connect to
  336. *
  337. * @retval SOCKET_ERROR on failure
  338. * @retval 1 on success
  339. *
  340. * @see WebSocket_upgrade
  341. */
  342. int WebSocket_connect( networkHandles *net, int ssl, const char *uri)
  343. {
  344. int rc;
  345. char *buf = NULL;
  346. char *headers_buf = NULL;
  347. const MQTTClient_nameValue *headers = net->httpHeaders;
  348. int i, buf_len = 0;
  349. int headers_buf_len = 0;
  350. size_t hostname_len;
  351. int port = 80;
  352. const char *topic = NULL;
  353. #if defined(_WIN32) || defined(_WIN64)
  354. UUID uuid;
  355. #else /* if defined(_WIN32) || defined(_WIN64) */
  356. uuid_t uuid;
  357. #endif /* else if defined(_WIN32) || defined(_WIN64) */
  358. FUNC_ENTRY;
  359. /* Generate UUID */
  360. if (net->websocket_key == NULL)
  361. net->websocket_key = malloc(25u);
  362. else
  363. {
  364. void* newPtr = realloc(net->websocket_key, 25u);
  365. if (newPtr == NULL)
  366. {
  367. free(net->websocket_key);
  368. net->websocket_key = NULL;
  369. }
  370. else
  371. {
  372. net->websocket_key = newPtr;
  373. }
  374. }
  375. if (net->websocket_key == NULL)
  376. {
  377. rc = PAHO_MEMORY_ERROR;
  378. goto exit;
  379. }
  380. #if defined(_WIN32) || defined(_WIN64)
  381. ZeroMemory( &uuid, sizeof(UUID) );
  382. UuidCreate( &uuid );
  383. Base64_encode( net->websocket_key, 25u, (const b64_data_t*)&uuid, sizeof(UUID) );
  384. #else /* if defined(_WIN32) || defined(_WIN64) */
  385. uuid_generate( uuid );
  386. Base64_encode( net->websocket_key, 25u, uuid, sizeof(uuid_t) );
  387. #endif /* else if defined(_WIN32) || defined(_WIN64) */
  388. hostname_len = MQTTProtocol_addressPort(uri, &port, &topic, ssl ? WSS_DEFAULT_PORT : WS_DEFAULT_PORT);
  389. /* if no topic, use default */
  390. if ( !topic )
  391. topic = "/mqtt";
  392. if ( headers )
  393. {
  394. char *headers_buf_cur = NULL;
  395. while ( headers->name != NULL && headers->value != NULL )
  396. {
  397. headers_buf_len += (int)(strlen(headers->name) + strlen(headers->value) + 4);
  398. headers++;
  399. }
  400. headers_buf_len++;
  401. if ((headers_buf = malloc(headers_buf_len)) == NULL)
  402. {
  403. rc = PAHO_MEMORY_ERROR;
  404. goto exit;
  405. }
  406. headers = net->httpHeaders;
  407. headers_buf_cur = headers_buf;
  408. while ( headers->name != NULL && headers->value != NULL )
  409. {
  410. headers_buf_cur += snprintf(headers_buf_cur, headers_buf_len - (headers_buf_cur - headers_buf),
  411. "%s: %s\r\n", headers->name, headers->value);
  412. headers++;
  413. }
  414. *headers_buf_cur = '\0';
  415. }
  416. for ( i = 0; i < 2; ++i )
  417. {
  418. buf_len = snprintf( buf, (size_t)buf_len,
  419. "GET %s HTTP/1.1\r\n"
  420. "Host: %.*s:%d\r\n"
  421. "Upgrade: websocket\r\n"
  422. "Connection: Upgrade\r\n"
  423. "Origin: %s://%.*s:%d\r\n"
  424. "Sec-WebSocket-Key: %s\r\n"
  425. "Sec-WebSocket-Version: 13\r\n"
  426. "Sec-WebSocket-Protocol: mqtt\r\n"
  427. "%s"
  428. "\r\n", topic,
  429. (int)hostname_len, uri, port,
  430. #if defined(OPENSSL)
  431. HTTP_PROTOCOL(net->ssl),
  432. #else
  433. HTTP_PROTOCOL(0),
  434. #endif
  435. (int)hostname_len, uri, port,
  436. net->websocket_key,
  437. headers_buf ? headers_buf : "");
  438. if ( i == 0 && buf_len > 0 )
  439. {
  440. ++buf_len; /* need 1 extra byte for ending '\0' */
  441. if ((buf = malloc( buf_len )) == NULL)
  442. {
  443. rc = PAHO_MEMORY_ERROR;
  444. goto exit;
  445. }
  446. }
  447. }
  448. if (headers_buf)
  449. free( headers_buf );
  450. if ( buf )
  451. {
  452. PacketBuffers nulbufs = {0, NULL, NULL, NULL, {0, 0, 0, 0}};
  453. #if defined(OPENSSL)
  454. if (net->ssl)
  455. SSLSocket_putdatas(net->ssl, net->socket, buf, buf_len, nulbufs);
  456. else
  457. #endif
  458. Socket_putdatas(net->socket, buf, buf_len, nulbufs);
  459. free( buf );
  460. rc = 1;
  461. }
  462. else
  463. {
  464. free(net->websocket_key);
  465. net->websocket_key = NULL;
  466. rc = SOCKET_ERROR;
  467. }
  468. exit:
  469. FUNC_EXIT_RC(rc);
  470. return rc;
  471. }
  472. /**
  473. * closes a websocket connection
  474. *
  475. * @param[in,out] net structure containing network connection
  476. * @param[in] status_code websocket close status code
  477. * @param[in] reason reason for closing connection (optional)
  478. */
  479. void WebSocket_close(networkHandles *net, int status_code, const char *reason)
  480. {
  481. struct frameData fd;
  482. PacketBuffers nulbufs = {0, NULL, NULL, NULL, {0, 0, 0, 0}};
  483. FUNC_ENTRY;
  484. if ( net->websocket )
  485. {
  486. char *buf0;
  487. size_t buf0len = sizeof(uint16_t);
  488. uint16_t status_code_be;
  489. const int mask_data = 1; /* all frames from client must be masked */
  490. if ( status_code < WebSocket_CLOSE_NORMAL ||
  491. status_code > WebSocket_CLOSE_TLS_FAIL )
  492. status_code = WebSocket_CLOSE_GOING_AWAY;
  493. if ( reason )
  494. buf0len += strlen(reason);
  495. buf0 = malloc(buf0len);
  496. if ( !buf0 )
  497. goto exit;
  498. /* encode status code */
  499. status_code_be = htobe16((uint16_t)status_code);
  500. memcpy(buf0, &status_code_be, sizeof(uint16_t));
  501. /* encode reason, if provided */
  502. if ( reason )
  503. strcpy( &buf0[sizeof(uint16_t)], reason );
  504. fd = WebSocket_buildFrame( net, WebSocket_OP_CLOSE, mask_data, &buf0, &buf0len, &nulbufs);
  505. #if defined(OPENSSL)
  506. if (net->ssl)
  507. SSLSocket_putdatas(net->ssl, net->socket, fd.wsbuf0, fd.wsbuf0len, nulbufs);
  508. else
  509. #endif
  510. Socket_putdatas(net->socket, fd.wsbuf0, fd.wsbuf0len, nulbufs);
  511. free(fd.wsbuf0); /* free temporary ws header */
  512. /* websocket connection is now closed */
  513. net->websocket = 0;
  514. free( buf0 );
  515. }
  516. if ( net->websocket_key )
  517. {
  518. free( net->websocket_key );
  519. net->websocket_key = NULL;
  520. }
  521. exit:
  522. FUNC_EXIT;
  523. }
  524. /**
  525. * @brief receives 1 byte from a socket
  526. *
  527. * @param[in,out] net network connection
  528. * @param[out] c byte that was read
  529. *
  530. * @retval SOCKET_ERROR on error
  531. * @retval TCPSOCKET_INTERRUPTED no data available
  532. * @retval TCPSOCKET_COMPLETE on success
  533. *
  534. * @see WebSocket_getdata
  535. */
  536. int WebSocket_getch(networkHandles *net, char* c)
  537. {
  538. int rc = SOCKET_ERROR;
  539. FUNC_ENTRY;
  540. if ( net->websocket )
  541. {
  542. struct ws_frame *frame = NULL;
  543. if ( in_frames && in_frames->first )
  544. frame = in_frames->first->content;
  545. if ( !frame || frame->len == frame->pos )
  546. {
  547. size_t actual_len = 0u;
  548. rc = WebSocket_receiveFrame( net, &actual_len);
  549. if ( rc != TCPSOCKET_COMPLETE )
  550. goto exit;
  551. /* we got a frame, let take off the top of queue */
  552. if ( in_frames->first )
  553. frame = in_frames->first->content;
  554. }
  555. /* set current working frame */
  556. if (frame && frame->len > frame->pos)
  557. {
  558. unsigned char *buf =
  559. (unsigned char *)frame + sizeof(struct ws_frame);
  560. *c = buf[frame->pos++];
  561. rc = TCPSOCKET_COMPLETE;
  562. }
  563. }
  564. #if defined(OPENSSL)
  565. else if ( net->ssl )
  566. rc = SSLSocket_getch(net->ssl, net->socket, c);
  567. #endif
  568. else
  569. rc = Socket_getch(net->socket, c);
  570. exit:
  571. FUNC_EXIT_RC(rc);
  572. return rc;
  573. }
  574. size_t WebSocket_framePos()
  575. {
  576. if ( in_frames && in_frames->first )
  577. {
  578. struct ws_frame *frame = in_frames->first->content;
  579. return frame->pos;
  580. }
  581. else
  582. {
  583. return 0;
  584. }
  585. }
  586. void WebSocket_framePosSeekTo(size_t pos)
  587. {
  588. if ( in_frames && in_frames->first )
  589. {
  590. struct ws_frame *frame = in_frames->first->content;
  591. frame->pos = pos;
  592. }
  593. }
  594. /**
  595. * @brief receives data from a socket.
  596. * It should receive all data from the socket that is immediately available.
  597. * Because it is encapsulated in websocket frames which cannot be
  598. *
  599. * @param[in,out] net network connection
  600. * @param[in] bytes amount of data to get (0 if last packet)
  601. * @param[out] actual_len amount of data read
  602. *
  603. * @return a pointer to the read data
  604. *
  605. * @see WebSocket_getch
  606. */
  607. char *WebSocket_getdata(networkHandles *net, size_t bytes, size_t* actual_len)
  608. {
  609. char *rv = NULL;
  610. int rc;
  611. FUNC_ENTRY;
  612. if ( net->websocket )
  613. {
  614. struct ws_frame *frame = NULL;
  615. if ( bytes == 0u )
  616. {
  617. /* done with current frame, move it to last frame */
  618. if ( in_frames && in_frames->first )
  619. frame = in_frames->first->content;
  620. /* return the data from the next frame, if we have one */
  621. if ( frame && frame->pos == frame->len )
  622. {
  623. rv = (char *)frame +
  624. sizeof(struct ws_frame) + frame->pos;
  625. *actual_len = frame->len - frame->pos;
  626. if ( last_frame )
  627. free( last_frame );
  628. last_frame = ListDetachHead(in_frames);
  629. }
  630. goto exit;
  631. }
  632. /* look at the first websocket frame */
  633. if ( in_frames && in_frames->first )
  634. frame = in_frames->first->content;
  635. /* no current frame, so let's go receive one for the network */
  636. if ( !frame )
  637. {
  638. rc = WebSocket_receiveFrame( net, actual_len );
  639. if ( rc == TCPSOCKET_COMPLETE && in_frames && in_frames->first)
  640. frame = in_frames->first->content;
  641. }
  642. if ( frame )
  643. {
  644. rv = (char *)frame + sizeof(struct ws_frame) + frame->pos;
  645. *actual_len = frame->len - frame->pos; /* use the rest of the frame */
  646. while (*actual_len < bytes) {
  647. rc = WebSocket_receiveFrame(net, actual_len);
  648. if (rc != TCPSOCKET_COMPLETE) {
  649. goto exit;
  650. }
  651. /* refresh pointers */
  652. frame = in_frames->first->content;
  653. rv = (char *)frame + sizeof(struct ws_frame) + frame->pos;
  654. *actual_len = frame->len - frame->pos; /* use the rest of the frame */
  655. } /* end while */
  656. if (*actual_len > bytes)
  657. {
  658. frame->pos += bytes;
  659. }
  660. else if (*actual_len == bytes && in_frames)
  661. {
  662. if ( last_frame )
  663. free( last_frame );
  664. last_frame = ListDetachHead(in_frames);
  665. }
  666. }
  667. }
  668. #if defined(OPENSSL)
  669. else if ( net->ssl )
  670. rv = SSLSocket_getdata(net->ssl, net->socket, bytes, actual_len, &rc);
  671. #endif
  672. else
  673. rv = Socket_getdata(net->socket, bytes, actual_len, &rc);
  674. exit:
  675. FUNC_EXIT_RC(rv);
  676. return rv;
  677. }
  678. void WebSocket_rewindData( void )
  679. {
  680. frame_buffer_index = 0;
  681. }
  682. /**
  683. * reads raw socket data for underlying layers
  684. *
  685. * @param[in] net network connection
  686. * @param[in] bytes number of bytes to read, 0 to complete packet
  687. * @param[in] actual_len amount of data read
  688. *
  689. * @return a buffer containing raw data
  690. */
  691. char *WebSocket_getRawSocketData(networkHandles *net, size_t bytes, size_t* actual_len, int* rc)
  692. {
  693. char *rv = NULL;
  694. size_t bytes_requested = bytes;
  695. FUNC_ENTRY;
  696. if (bytes > 0)
  697. {
  698. if (frame_buffer_data_len - frame_buffer_index >= bytes)
  699. {
  700. *actual_len = bytes;
  701. rv = frame_buffer + frame_buffer_index;
  702. frame_buffer_index += bytes;
  703. *rc = (int)bytes;
  704. goto exit;
  705. }
  706. else
  707. {
  708. bytes = bytes - (frame_buffer_data_len - frame_buffer_index);
  709. }
  710. }
  711. *actual_len = 0;
  712. // not enough data in the buffer, get data from socket
  713. #if defined(OPENSSL)
  714. if ( net->ssl )
  715. rv = SSLSocket_getdata(net->ssl, net->socket, bytes, actual_len, rc);
  716. else
  717. #endif
  718. rv = Socket_getdata(net->socket, bytes, actual_len, rc);
  719. if (*rc == 0)
  720. {
  721. *rc = SOCKET_ERROR;
  722. goto exit;
  723. }
  724. // clear buffer
  725. if (bytes == 0)
  726. {
  727. frame_buffer_index = 0;
  728. frame_buffer_data_len = 0;
  729. frame_buffer_len = 0;
  730. if (frame_buffer)
  731. {
  732. free (frame_buffer);
  733. frame_buffer = NULL;
  734. }
  735. }
  736. // append data to the buffer
  737. else if (rv != NULL && *actual_len != 0U)
  738. {
  739. // no buffer allocated
  740. if (!frame_buffer)
  741. {
  742. if ((frame_buffer = (char *)malloc(*actual_len)) == NULL)
  743. {
  744. rv = NULL;
  745. goto exit;
  746. }
  747. memcpy(frame_buffer, rv, *actual_len);
  748. frame_buffer_index = 0;
  749. frame_buffer_data_len = *actual_len;
  750. frame_buffer_len = *actual_len;
  751. }
  752. // buffer size is big enough
  753. else if (frame_buffer_data_len + *actual_len < frame_buffer_len)
  754. {
  755. memcpy(frame_buffer + frame_buffer_data_len, rv, *actual_len);
  756. frame_buffer_data_len += *actual_len;
  757. }
  758. // resize buffer
  759. else
  760. {
  761. void* newPtr = realloc(frame_buffer, frame_buffer_data_len + *actual_len);
  762. if (newPtr == NULL)
  763. {
  764. free(frame_buffer);
  765. frame_buffer = NULL;
  766. rv = NULL;
  767. goto exit;
  768. }
  769. else
  770. {
  771. frame_buffer = newPtr;
  772. }
  773. frame_buffer_len = frame_buffer_data_len + *actual_len;
  774. memcpy(frame_buffer + frame_buffer_data_len, rv, *actual_len);
  775. frame_buffer_data_len += *actual_len;
  776. }
  777. SocketBuffer_complete(net->socket);
  778. }
  779. else
  780. goto exit;
  781. bytes = bytes_requested;
  782. // if possible, return data from the buffer
  783. if (bytes > 0)
  784. {
  785. if (frame_buffer_data_len - frame_buffer_index >= bytes)
  786. {
  787. *actual_len = bytes;
  788. rv = frame_buffer + frame_buffer_index;
  789. frame_buffer_index += bytes;
  790. }
  791. else
  792. {
  793. *actual_len = frame_buffer_data_len - frame_buffer_index;
  794. rv = frame_buffer + frame_buffer_index;
  795. frame_buffer_index += *actual_len;
  796. }
  797. }
  798. exit:
  799. FUNC_EXIT;
  800. return rv;
  801. }
  802. /**
  803. * sends a "websocket pong" message
  804. *
  805. * @param[in] net network connection
  806. * @param[in] app_data application data to put in payload
  807. * @param[in] app_data_len application data length
  808. */
  809. void WebSocket_pong(networkHandles *net, char *app_data, size_t app_data_len)
  810. {
  811. FUNC_ENTRY;
  812. if ( net->websocket )
  813. {
  814. char *buf0 = NULL;
  815. size_t buf0len = 0;
  816. int freeData = 0;
  817. struct frameData fd;
  818. const int mask_data = 1; /* all frames from client must be masked */
  819. PacketBuffers appbuf = {1, &app_data, &app_data_len, &freeData, {0, 0, 0, 0}};
  820. fd = WebSocket_buildFrame( net, WebSocket_OP_PONG, mask_data, &buf0, &buf0len, &appbuf);
  821. Log(TRACE_PROTOCOL, 1, "Sending WebSocket PONG" );
  822. #if defined(OPENSSL)
  823. if (net->ssl)
  824. SSLSocket_putdatas(net->ssl, net->socket, fd.wsbuf0, fd.wsbuf0len /*header_len + app_data_len*/, appbuf);
  825. else
  826. #endif
  827. Socket_putdatas(net->socket, fd.wsbuf0, fd.wsbuf0len /*header_len + app_data_len*/, appbuf);
  828. free(fd.wsbuf0);
  829. free(buf0);
  830. }
  831. FUNC_EXIT;
  832. }
  833. /**
  834. * writes data to a socket (websocket header will be prepended if required)
  835. *
  836. * @warning buf0 will be expanded (backwords before @p buf0 buffer, to add a
  837. * websocket frame header to the data if required). So use
  838. * @p WebSocket_calculateFrameHeader, to determine if extra space is needed
  839. * before the @p buf0 pointer.
  840. *
  841. * @param[in,out] net network connection
  842. * @param[in,out] buf0 first buffer
  843. * @param[in] buf0len size of first buffer
  844. * @param[in] count number of payload buffers
  845. * @param[in,out] buffers array of paylaod buffers
  846. * @param[in] buflens array of payload buffer sizes
  847. * @param[in] freeData array indicating to free payload buffers
  848. *
  849. * @return amount of data wrote to socket
  850. *
  851. * @see WebSocket_calculateFrameHeaderSize
  852. */
  853. int WebSocket_putdatas(networkHandles* net, char** buf0, size_t* buf0len, PacketBuffers* bufs)
  854. {
  855. const int mask_data = 1; /* must mask websocket data from client */
  856. int rc;
  857. FUNC_ENTRY;
  858. if (net->websocket)
  859. {
  860. struct frameData wsdata;
  861. wsdata = WebSocket_buildFrame(net, WebSocket_OP_BINARY, mask_data, buf0, buf0len, bufs);
  862. #if defined(OPENSSL)
  863. if (net->ssl)
  864. rc = SSLSocket_putdatas(net->ssl, net->socket, wsdata.wsbuf0, wsdata.wsbuf0len, *bufs);
  865. else
  866. #endif
  867. rc = Socket_putdatas(net->socket, wsdata.wsbuf0, wsdata.wsbuf0len, *bufs);
  868. if (rc != TCPSOCKET_INTERRUPTED)
  869. {
  870. if (mask_data)
  871. WebSocket_unmaskData(*buf0len, bufs);
  872. free(wsdata.wsbuf0); /* free temporary ws header */
  873. }
  874. }
  875. else
  876. {
  877. #if defined(OPENSSL)
  878. if (net->ssl)
  879. rc = SSLSocket_putdatas(net->ssl, net->socket, *buf0, *buf0len, *bufs);
  880. else
  881. #endif
  882. rc = Socket_putdatas(net->socket, *buf0, *buf0len, *bufs);
  883. }
  884. FUNC_EXIT_RC(rc);
  885. return rc;
  886. }
  887. /**
  888. * receives incoming socket data and parses websocket frames
  889. * Copes with socket reads returning partial websocket frames by using the
  890. * SocketBuffer mechanism.
  891. *
  892. * @param[in] net network connection
  893. * @param[out] actual_len amount of data actually read
  894. *
  895. * @retval TCPSOCKET_COMPLETE packet received
  896. * @retval TCPSOCKET_INTERRUPTED incomplete packet received
  897. * @retval SOCKET_ERROR an error was encountered
  898. */
  899. int WebSocket_receiveFrame(networkHandles *net, size_t *actual_len)
  900. {
  901. struct ws_frame *res = NULL;
  902. int rc = TCPSOCKET_COMPLETE;
  903. int opcode = 0;
  904. FUNC_ENTRY;
  905. if ( !in_frames )
  906. in_frames = ListInitialize();
  907. /* see if there is frame currently on queue */
  908. if ( in_frames->first )
  909. res = in_frames->first->content;
  910. //while( !res )
  911. //{
  912. opcode = WebSocket_OP_BINARY;
  913. do
  914. {
  915. /* obtain all frames in the sequence */
  916. int is_final = 0;
  917. while ( is_final == 0 )
  918. {
  919. char *b;
  920. size_t len = 0u;
  921. int tmp_opcode;
  922. int has_mask;
  923. size_t cur_len = 0u;
  924. uint8_t mask[4] = { 0u, 0u, 0u, 0u };
  925. size_t payload_len;
  926. int rcs; /* socket return code */
  927. b = WebSocket_getRawSocketData(net, 2u, &len, &rcs);
  928. if (rcs == SOCKET_ERROR)
  929. {
  930. rc = rcs;
  931. goto exit;
  932. }
  933. if ( !b )
  934. {
  935. rc = TCPSOCKET_INTERRUPTED;
  936. goto exit;
  937. }
  938. else if (len < 2u )
  939. {
  940. rc = TCPSOCKET_INTERRUPTED;
  941. goto exit;
  942. }
  943. /* 1st byte */
  944. is_final = (b[0] & 0xFF) >> 7;
  945. tmp_opcode = (b[0] & 0x0F);
  946. if ( tmp_opcode ) /* not a continuation frame */
  947. opcode = tmp_opcode;
  948. /* invalid websocket packet must return error */
  949. if ( opcode < WebSocket_OP_CONTINUE ||
  950. opcode > WebSocket_OP_PONG ||
  951. ( opcode > WebSocket_OP_BINARY &&
  952. opcode < WebSocket_OP_CLOSE ) )
  953. {
  954. rc = SOCKET_ERROR;
  955. goto exit;
  956. }
  957. /* 2nd byte */
  958. has_mask = (b[1] & 0xFF) >> 7;
  959. payload_len = (b[1] & 0x7F);
  960. /* determine payload length */
  961. if ( payload_len == 126 )
  962. {
  963. /* If 126, the following 2 bytes interpreted as a
  964. 16-bit unsigned integer are the payload length. */
  965. b = WebSocket_getRawSocketData(net, 2u, &len, &rcs);
  966. if (rcs == SOCKET_ERROR)
  967. {
  968. rc = rcs;
  969. goto exit;
  970. }
  971. if ( !b )
  972. {
  973. rc = SOCKET_ERROR;
  974. goto exit;
  975. }
  976. else if (len < 2u )
  977. {
  978. rc = TCPSOCKET_INTERRUPTED;
  979. goto exit;
  980. }
  981. /* convert from big endian 16 to host */
  982. payload_len = be16toh(*(uint16_t*)b);
  983. }
  984. else if ( payload_len == 127 )
  985. {
  986. /* If 127, the following 8 bytes interpreted as a 64-bit unsigned integer (the
  987. most significant bit MUST be 0) are the payload length */
  988. b = WebSocket_getRawSocketData(net, 8u, &len, &rcs);
  989. if (rcs == SOCKET_ERROR)
  990. {
  991. rc = rcs;
  992. goto exit;
  993. }
  994. if ( !b )
  995. {
  996. rc = SOCKET_ERROR;
  997. goto exit;
  998. }
  999. else if (len < 8u )
  1000. {
  1001. rc = TCPSOCKET_INTERRUPTED;
  1002. goto exit;
  1003. }
  1004. /* convert from big-endian 64 to host */
  1005. payload_len = (size_t)be64toh(*(uint64_t*)b);
  1006. }
  1007. if ( has_mask )
  1008. {
  1009. uint8_t mask[4];
  1010. b = WebSocket_getRawSocketData(net, 4u, &len, &rcs);
  1011. if (rcs == SOCKET_ERROR)
  1012. {
  1013. rc = rcs;
  1014. goto exit;
  1015. }
  1016. if ( !b )
  1017. {
  1018. rc = SOCKET_ERROR;
  1019. goto exit;
  1020. }
  1021. if (len < 4u )
  1022. {
  1023. rc = TCPSOCKET_INTERRUPTED;
  1024. goto exit;
  1025. }
  1026. memcpy( &mask[0], b, sizeof(uint32_t));
  1027. }
  1028. /* use the socket buffer to read in the whole websocket frame */
  1029. b = WebSocket_getRawSocketData(net, payload_len, &len, &rcs);
  1030. if (rcs == SOCKET_ERROR)
  1031. {
  1032. rc = rcs;
  1033. goto exit;
  1034. }
  1035. if (!b)
  1036. {
  1037. rc = SOCKET_ERROR;
  1038. goto exit;
  1039. }
  1040. if (len < payload_len )
  1041. {
  1042. rc = TCPSOCKET_INTERRUPTED;
  1043. goto exit;
  1044. }
  1045. /* unmask data */
  1046. if ( has_mask )
  1047. {
  1048. size_t i;
  1049. for ( i = 0u; i < payload_len; ++i )
  1050. b[i] ^= mask[i % 4];
  1051. }
  1052. if ( res )
  1053. cur_len = res->len;
  1054. if (res == NULL)
  1055. {
  1056. if ((res = malloc( sizeof(struct ws_frame) + cur_len + len)) == NULL)
  1057. {
  1058. rc = PAHO_MEMORY_ERROR;
  1059. goto exit;
  1060. }
  1061. res->pos = 0u;
  1062. } else
  1063. {
  1064. void* newPtr = realloc( res, sizeof(struct ws_frame) + cur_len + len );
  1065. if (newPtr == NULL)
  1066. {
  1067. free(res);
  1068. res = NULL;
  1069. rc = PAHO_MEMORY_ERROR;
  1070. goto exit;
  1071. }
  1072. else
  1073. {
  1074. res = newPtr;
  1075. }
  1076. }
  1077. if (in_frames && in_frames->first)
  1078. in_frames->first->content = res; /* realloc moves the data */
  1079. memcpy( (unsigned char *)res + sizeof(struct ws_frame) + cur_len, b, len );
  1080. res->len = cur_len + len;
  1081. WebSocket_getRawSocketData(net, 0u, &len, &rcs);
  1082. if (rcs == SOCKET_ERROR)
  1083. {
  1084. rc = rcs;
  1085. goto exit;
  1086. }
  1087. }
  1088. if ( opcode == WebSocket_OP_PING || opcode == WebSocket_OP_PONG )
  1089. {
  1090. /* respond to a "ping" with a "pong" */
  1091. if ( opcode == WebSocket_OP_PING )
  1092. WebSocket_pong( net,
  1093. (char *)res + sizeof(struct ws_frame),
  1094. res->len );
  1095. /* discard message */
  1096. free( res );
  1097. res = NULL;
  1098. }
  1099. else if ( opcode == WebSocket_OP_CLOSE )
  1100. {
  1101. /* server end closed websocket connection */
  1102. free( res );
  1103. WebSocket_close( net, WebSocket_CLOSE_GOING_AWAY, NULL );
  1104. rc = SOCKET_ERROR; /* closes socket */
  1105. goto exit;
  1106. }
  1107. } while ( opcode == WebSocket_OP_PING || opcode == WebSocket_OP_PONG );
  1108. //}
  1109. if (in_frames->count == 0)
  1110. ListAppend( in_frames, res, sizeof(struct ws_frame) + res->len);
  1111. *actual_len = res->len - res->pos;
  1112. exit:
  1113. if (rc == TCPSOCKET_INTERRUPTED)
  1114. {
  1115. WebSocket_rewindData();
  1116. }
  1117. FUNC_EXIT_RC(rc);
  1118. return rc;
  1119. }
  1120. /**
  1121. * case-insensitive string search
  1122. *
  1123. * similar to @p strcase, but takes a maximum length
  1124. *
  1125. * @param[in] buf buffer to search
  1126. * @param[in] str string to find
  1127. * @param[in] len length of the buffer
  1128. *
  1129. * @retval !NULL location of string found
  1130. * @retval NULL string not found
  1131. */
  1132. const char *WebSocket_strcasefind(const char *buf, const char *str, size_t len)
  1133. {
  1134. const char *res = NULL;
  1135. if ( buf && len > 0u && str )
  1136. {
  1137. const size_t str_len = strlen( str );
  1138. while ( len >= str_len && !res )
  1139. {
  1140. if ( strncasecmp( buf, str, str_len ) == 0 )
  1141. res = buf;
  1142. ++buf;
  1143. --len;
  1144. }
  1145. }
  1146. return res;
  1147. }
  1148. /**
  1149. * releases resources used by the websocket sub-system
  1150. */
  1151. void WebSocket_terminate( void )
  1152. {
  1153. FUNC_ENTRY;
  1154. /* clean up and un-processed websocket frames */
  1155. if ( in_frames )
  1156. {
  1157. struct ws_frame *f = ListDetachHead( in_frames );
  1158. while ( f )
  1159. {
  1160. free( f );
  1161. f = ListDetachHead( in_frames );
  1162. }
  1163. ListFree( in_frames );
  1164. in_frames = NULL;
  1165. }
  1166. if ( last_frame )
  1167. {
  1168. free( last_frame );
  1169. last_frame = NULL;
  1170. }
  1171. if ( frame_buffer )
  1172. {
  1173. free( frame_buffer );
  1174. frame_buffer = NULL;
  1175. }
  1176. frame_buffer_len = 0;
  1177. frame_buffer_index = 0;
  1178. frame_buffer_data_len = 0;
  1179. Socket_outTerminate();
  1180. #if defined(OPENSSL)
  1181. SSLSocket_terminate();
  1182. #endif
  1183. FUNC_EXIT;
  1184. }
  1185. /**
  1186. * handles the websocket upgrade response
  1187. *
  1188. * @param[in,out] net network connection to upgrade
  1189. *
  1190. * @retval SOCKET_ERROR failed to upgrade network connection
  1191. * @retval TCPSOCKET_INTERRUPTED upgrade not complete, but not failed. Try again
  1192. * @retval 1 socket upgraded to use websockets
  1193. *
  1194. * @see WebSocket_connect
  1195. */
  1196. int WebSocket_upgrade( networkHandles *net )
  1197. {
  1198. static const char *const ws_guid =
  1199. "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  1200. int rc = SOCKET_ERROR;
  1201. FUNC_ENTRY;
  1202. if ( net->websocket_key )
  1203. {
  1204. char ws_key[62u] = {0};
  1205. size_t rcv = 0u;
  1206. char *read_buf;
  1207. #if defined(OPENSSL) && OPENSSL_VERSION_NUMBER >= 0x030000000
  1208. EVP_MD_CTX *sha1_ctx = NULL;
  1209. unsigned char sha_hash[EVP_MAX_MD_SIZE];
  1210. unsigned int sha_len = 0;
  1211. #else
  1212. SHA_CTX ctx;
  1213. unsigned char sha_hash[SHA1_DIGEST_LENGTH];
  1214. #endif
  1215. /* calculate the expected websocket key, expected from server */
  1216. snprintf(ws_key, sizeof(ws_key), "%s%s", net->websocket_key, ws_guid);
  1217. #if defined(OPENSSL) && OPENSSL_VERSION_NUMBER >= 0x030000000
  1218. sha1_ctx = EVP_MD_CTX_new();
  1219. if (sha1_ctx) {
  1220. rc = EVP_DigestInit(sha1_ctx, EVP_sha1());
  1221. if (rc == 0)
  1222. Log(LOG_ERROR, 1, "EVP_DigestInit failed");
  1223. else
  1224. rc = EVP_DigestUpdate(sha1_ctx, ws_key, strlen(ws_key));
  1225. if (rc == 0)
  1226. Log(LOG_ERROR, 1, "EVP_DigestUpdate failed");
  1227. else
  1228. rc = EVP_DigestFinal(sha1_ctx, sha_hash, &sha_len);
  1229. if (rc == 0)
  1230. Log(LOG_ERROR, 1, "EVP_DigestFinal failed");
  1231. EVP_MD_CTX_free(sha1_ctx);
  1232. if (rc == 0)
  1233. {
  1234. rc = SOCKET_ERROR;
  1235. goto exit;
  1236. }
  1237. } else
  1238. {
  1239. Log(LOG_ERROR, 1, "EVP_MD_CTX_new failed");
  1240. rc = SOCKET_ERROR;
  1241. goto exit;
  1242. }
  1243. Base64_encode( ws_key, sizeof(ws_key), sha_hash, sha_len);
  1244. #else
  1245. SHA1_Init( &ctx );
  1246. SHA1_Update( &ctx, ws_key, strlen(ws_key));
  1247. SHA1_Final( sha_hash, &ctx );
  1248. Base64_encode( ws_key, sizeof(ws_key), sha_hash, SHA1_DIGEST_LENGTH );
  1249. #endif
  1250. read_buf = WebSocket_getRawSocketData( net, 12u, &rcv, &rc);
  1251. if (rc == SOCKET_ERROR)
  1252. goto exit;
  1253. if ((read_buf == NULL) || rcv < 12u)
  1254. {
  1255. Log(TRACE_PROTOCOL, 1, "WebSocket upgrade read not complete %lu", rcv );
  1256. rc = TCPSOCKET_INTERRUPTED;
  1257. goto exit;
  1258. }
  1259. if (strncmp( read_buf, "HTTP/1.1", 8u ) == 0)
  1260. {
  1261. if (strncmp( &read_buf[9], "101", 3u ) != 0)
  1262. {
  1263. Log(TRACE_PROTOCOL, 1, "WebSocket HTTP rc %.3s", &read_buf[9]);
  1264. rc = SOCKET_ERROR;
  1265. goto exit;
  1266. }
  1267. }
  1268. if (strncmp( read_buf, "HTTP/1.1 101", 12u ) == 0)
  1269. {
  1270. const char *p;
  1271. read_buf = WebSocket_getRawSocketData(net, 1024u, &rcv, &rc);
  1272. if (rc == SOCKET_ERROR)
  1273. goto exit;
  1274. /* Did we read the whole response? */
  1275. if (read_buf && rcv > 4 && memcmp(&read_buf[rcv-4], "\r\n\r\n", 4) != 0)
  1276. {
  1277. Log(TRACE_PROTOCOL, -1, "WebSocket HTTP upgrade response read not complete %lu", rcv);
  1278. rc = SOCKET_ERROR;
  1279. goto exit;
  1280. }
  1281. /* check for upgrade */
  1282. p = WebSocket_strcasefind(
  1283. read_buf, "Connection", rcv );
  1284. if ( p )
  1285. {
  1286. const char *eol;
  1287. eol = memchr( p, '\n', rcv-(read_buf-p) );
  1288. if ( eol )
  1289. p = WebSocket_strcasefind(
  1290. p, "Upgrade", eol - p);
  1291. else
  1292. p = NULL;
  1293. }
  1294. /* check key hash */
  1295. if ( p )
  1296. p = WebSocket_strcasefind( read_buf,
  1297. "sec-websocket-accept", rcv );
  1298. if ( p )
  1299. {
  1300. const char *eol;
  1301. eol = memchr( p, '\n', rcv-(read_buf-p) );
  1302. if ( eol )
  1303. {
  1304. p = memchr( p, ':', eol-p );
  1305. if ( p )
  1306. {
  1307. size_t hash_len = eol-p-1;
  1308. while ( *p == ':' || *p == ' ' )
  1309. {
  1310. ++p;
  1311. --hash_len;
  1312. }
  1313. if ( strncmp( p, ws_key, hash_len ) != 0 )
  1314. p = NULL;
  1315. }
  1316. }
  1317. else
  1318. p = NULL;
  1319. }
  1320. if ( p )
  1321. {
  1322. net->websocket = 1;
  1323. Log(TRACE_PROTOCOL, 1, "WebSocket connection upgraded" );
  1324. rc = 1;
  1325. }
  1326. else
  1327. {
  1328. Log(TRACE_PROTOCOL, 1, "WebSocket failed to upgrade connection" );
  1329. rc = SOCKET_ERROR;
  1330. }
  1331. if ( net->websocket_key )
  1332. {
  1333. free(net->websocket_key);
  1334. net->websocket_key = NULL;
  1335. }
  1336. /* indicate that we done with the packet */
  1337. WebSocket_getRawSocketData( net, 0u, &rcv, &rc);
  1338. }
  1339. }
  1340. exit:
  1341. FUNC_EXIT_RC(rc);
  1342. return rc;
  1343. }