WebSocket.c 34 KB

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