server-ws.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  1. /*
  2. * libwebsockets - small server side websockets and web server implementation
  3. *
  4. * Copyright (C) 2010-2018 Andy Green <[email protected]>
  5. *
  6. * This library is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation:
  9. * version 2.1 of the License.
  10. *
  11. * This library is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with this library; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  19. * MA 02110-1301 USA
  20. */
  21. #include <core/private.h>
  22. #define LWS_CPYAPP(ptr, str) { strcpy(ptr, str); ptr += strlen(str); }
  23. #if !defined(LWS_WITHOUT_EXTENSIONS)
  24. static int
  25. lws_extension_server_handshake(struct lws *wsi, char **p, int budget)
  26. {
  27. struct lws_context *context = wsi->context;
  28. struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
  29. char ext_name[64], *args, *end = (*p) + budget - 1;
  30. const struct lws_ext_options *opts, *po;
  31. const struct lws_extension *ext;
  32. struct lws_ext_option_arg oa;
  33. int n, m, more = 1;
  34. int ext_count = 0;
  35. char ignore;
  36. char *c;
  37. /*
  38. * Figure out which extensions the client has that we want to
  39. * enable on this connection, and give him back the list
  40. */
  41. if (!lws_hdr_total_length(wsi, WSI_TOKEN_EXTENSIONS))
  42. return 0;
  43. /*
  44. * break down the list of client extensions
  45. * and go through them
  46. */
  47. if (lws_hdr_copy(wsi, (char *)pt->serv_buf, context->pt_serv_buf_size,
  48. WSI_TOKEN_EXTENSIONS) < 0)
  49. return 1;
  50. c = (char *)pt->serv_buf;
  51. lwsl_parser("WSI_TOKEN_EXTENSIONS = '%s'\n", c);
  52. wsi->ws->count_act_ext = 0;
  53. ignore = 0;
  54. n = 0;
  55. args = NULL;
  56. /*
  57. * We may get a simple request
  58. *
  59. * Sec-WebSocket-Extensions: permessage-deflate
  60. *
  61. * or an elaborated one with requested options
  62. *
  63. * Sec-WebSocket-Extensions: permessage-deflate; \
  64. * server_no_context_takeover; \
  65. * client_no_context_takeover
  66. */
  67. while (more) {
  68. if (c >= (char *)pt->serv_buf + 255)
  69. return -1;
  70. if (*c && (*c != ',' && *c != '\t')) {
  71. if (*c == ';') {
  72. ignore = 1;
  73. if (!args)
  74. args = c + 1;
  75. }
  76. if (ignore || *c == ' ') {
  77. c++;
  78. continue;
  79. }
  80. ext_name[n] = *c++;
  81. if (n < (int)sizeof(ext_name) - 1)
  82. n++;
  83. continue;
  84. }
  85. ext_name[n] = '\0';
  86. ignore = 0;
  87. if (!*c)
  88. more = 0;
  89. else {
  90. c++;
  91. if (!n)
  92. continue;
  93. }
  94. while (args && *args == ' ')
  95. args++;
  96. /* check a client's extension against our support */
  97. ext = wsi->vhost->ws.extensions;
  98. while (ext && ext->callback) {
  99. if (strcmp(ext_name, ext->name)) {
  100. ext++;
  101. continue;
  102. }
  103. /*
  104. * oh, we do support this one he asked for... but let's
  105. * confirm he only gave it once
  106. */
  107. for (m = 0; m < wsi->ws->count_act_ext; m++)
  108. if (wsi->ws->active_extensions[m] == ext) {
  109. lwsl_info("ext mentioned twice\n");
  110. return 1; /* shenanigans */
  111. }
  112. /*
  113. * ask user code if it's OK to apply it on this
  114. * particular connection + protocol
  115. */
  116. m = (wsi->protocol->callback)(wsi,
  117. LWS_CALLBACK_CONFIRM_EXTENSION_OKAY,
  118. wsi->user_space, ext_name, 0);
  119. /*
  120. * zero return from callback means go ahead and allow
  121. * the extension, it's what we get if the callback is
  122. * unhandled
  123. */
  124. if (m) {
  125. ext++;
  126. continue;
  127. }
  128. /* apply it */
  129. ext_count++;
  130. /* instantiate the extension on this conn */
  131. wsi->ws->active_extensions[wsi->ws->count_act_ext] = ext;
  132. /* allow him to construct his context */
  133. if (ext->callback(lws_get_context(wsi), ext, wsi,
  134. LWS_EXT_CB_CONSTRUCT,
  135. (void *)&wsi->ws->act_ext_user[
  136. wsi->ws->count_act_ext],
  137. (void *)&opts, 0)) {
  138. lwsl_info("ext %s failed construction\n",
  139. ext_name);
  140. ext_count--;
  141. ext++;
  142. continue;
  143. }
  144. if (ext_count > 1)
  145. *(*p)++ = ',';
  146. else
  147. LWS_CPYAPP(*p,
  148. "\x0d\x0aSec-WebSocket-Extensions: ");
  149. *p += lws_snprintf(*p, (end - *p), "%s", ext_name);
  150. /*
  151. * The client may send a bunch of different option
  152. * sets for the same extension, we are supposed to
  153. * pick one we like the look of. The option sets are
  154. * separated by comma.
  155. *
  156. * Actually we just either accept the first one or
  157. * nothing.
  158. *
  159. * Go through the options trying to apply the
  160. * recognized ones
  161. */
  162. lwsl_info("ext args %s\n", args);
  163. while (args && *args && *args != ',') {
  164. while (*args == ' ')
  165. args++;
  166. po = opts;
  167. while (po->name) {
  168. /* only support arg-less options... */
  169. if (po->type != EXTARG_NONE ||
  170. strncmp(args, po->name,
  171. strlen(po->name))) {
  172. po++;
  173. continue;
  174. }
  175. oa.option_name = NULL;
  176. oa.option_index = (int)(po - opts);
  177. oa.start = NULL;
  178. oa.len = 0;
  179. lwsl_info("setting '%s'\n", po->name);
  180. if (!ext->callback(lws_get_context(wsi),
  181. ext, wsi,
  182. LWS_EXT_CB_OPTION_SET,
  183. wsi->ws->act_ext_user[
  184. wsi->ws->count_act_ext],
  185. &oa, (end - *p))) {
  186. *p += lws_snprintf(*p,
  187. (end - *p),
  188. "; %s", po->name);
  189. lwsl_debug("adding option %s\n",
  190. po->name);
  191. }
  192. po++;
  193. }
  194. while (*args && *args != ',' && *args != ';')
  195. args++;
  196. if (*args == ';')
  197. args++;
  198. }
  199. wsi->ws->count_act_ext++;
  200. lwsl_parser("cnt_act_ext <- %d\n",
  201. wsi->ws->count_act_ext);
  202. if (args && *args == ',')
  203. more = 0;
  204. ext++;
  205. }
  206. n = 0;
  207. args = NULL;
  208. }
  209. return 0;
  210. }
  211. #endif
  212. int
  213. lws_process_ws_upgrade(struct lws *wsi)
  214. {
  215. struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
  216. const struct lws_protocols *pcol = NULL;
  217. char buf[128], name[64];
  218. struct lws_tokenize ts;
  219. lws_tokenize_elem e;
  220. if (!wsi->protocol)
  221. lwsl_err("NULL protocol at lws_read\n");
  222. /*
  223. * We are upgrading to ws, so http/1.1 + h2 and keepalive + pipelined
  224. * header considerations about keeping the ah around no longer apply.
  225. *
  226. * However it's common for the first ws protocol data to have been
  227. * coalesced with the browser upgrade request and to already be in the
  228. * ah rx buffer.
  229. */
  230. lws_pt_lock(pt, __func__);
  231. if (!wsi->h2_stream_carries_ws)
  232. lws_role_transition(wsi, LWSIFR_SERVER, LRS_ESTABLISHED,
  233. &role_ops_ws);
  234. lws_pt_unlock(pt);
  235. /*
  236. * It's either websocket or h2->websocket
  237. *
  238. * If we are on h1, confirm we got the required "connection: upgrade"
  239. * header. h2 / ws-over-h2 does not have this.
  240. */
  241. #if defined(LWS_WITH_HTTP2)
  242. if (wsi->http2_substream)
  243. goto check_protocol;
  244. #endif
  245. lws_tokenize_init(&ts, buf, LWS_TOKENIZE_F_COMMA_SEP_LIST |
  246. LWS_TOKENIZE_F_MINUS_NONTERM);
  247. ts.len = lws_hdr_copy(wsi, buf, sizeof(buf) - 1, WSI_TOKEN_CONNECTION);
  248. if (ts.len <= 0)
  249. goto bad_conn_format;
  250. do {
  251. e = lws_tokenize(&ts);
  252. switch (e) {
  253. case LWS_TOKZE_TOKEN:
  254. if (!strcasecmp(ts.token, "upgrade"))
  255. e = LWS_TOKZE_ENDED;
  256. break;
  257. case LWS_TOKZE_DELIMITER:
  258. break;
  259. default: /* includes ENDED */
  260. bad_conn_format:
  261. lwsl_err("%s: malformed or absent connection hdr\n",
  262. __func__);
  263. return 1;
  264. }
  265. } while (e > 0);
  266. #if defined(LWS_WITH_HTTP2)
  267. check_protocol:
  268. #endif
  269. /*
  270. * Select the first protocol we support from the list
  271. * the client sent us.
  272. */
  273. lws_tokenize_init(&ts, buf, LWS_TOKENIZE_F_COMMA_SEP_LIST |
  274. LWS_TOKENIZE_F_MINUS_NONTERM |
  275. LWS_TOKENIZE_F_RFC7230_DELIMS);
  276. ts.len = lws_hdr_copy(wsi, buf, sizeof(buf) - 1, WSI_TOKEN_PROTOCOL);
  277. if (ts.len < 0) {
  278. lwsl_err("%s: protocol list too long\n", __func__);
  279. return 1;
  280. }
  281. if (!ts.len) {
  282. int n = wsi->vhost->default_protocol_index;
  283. /*
  284. * some clients only have one protocol and do not send the
  285. * protocol list header... allow it and match to the vhost's
  286. * default protocol (which itself defaults to zero)
  287. */
  288. lwsl_info("%s: defaulting to prot handler %d\n", __func__, n);
  289. lws_bind_protocol(wsi, &wsi->vhost->protocols[n],
  290. "ws upgrade default pcol");
  291. goto alloc_ws;
  292. }
  293. /* otherwise go through the user-provided protocol list */
  294. do {
  295. e = lws_tokenize(&ts);
  296. switch (e) {
  297. case LWS_TOKZE_TOKEN:
  298. if (lws_tokenize_cstr(&ts, name, sizeof(name))) {
  299. lwsl_err("%s: pcol name too long\n", __func__);
  300. return 1;
  301. }
  302. lwsl_debug("checking %s\n", name);
  303. pcol = lws_vhost_name_to_protocol(wsi->vhost, name);
  304. if (pcol) {
  305. /* if we know it, bind to it and stop looking */
  306. lws_bind_protocol(wsi, pcol, "ws upg pcol");
  307. e = LWS_TOKZE_ENDED;
  308. }
  309. break;
  310. case LWS_TOKZE_DELIMITER:
  311. case LWS_TOKZE_ENDED:
  312. break;
  313. default:
  314. lwsl_err("%s: malformatted protocol list", __func__);
  315. return 1;
  316. }
  317. } while (e > 0);
  318. /* we didn't find a protocol he wanted? */
  319. if (!pcol) {
  320. lwsl_notice("No supported protocol \"%s\"\n", buf);
  321. return 1;
  322. }
  323. alloc_ws:
  324. /* allocate the ws struct for the wsi */
  325. wsi->ws = lws_zalloc(sizeof(*wsi->ws), "ws struct");
  326. if (!wsi->ws) {
  327. lwsl_notice("OOM\n");
  328. return 1;
  329. }
  330. if (lws_hdr_total_length(wsi, WSI_TOKEN_VERSION))
  331. wsi->ws->ietf_spec_revision =
  332. atoi(lws_hdr_simple_ptr(wsi, WSI_TOKEN_VERSION));
  333. /* allocate wsi->user storage */
  334. if (lws_ensure_user_space(wsi)) {
  335. lwsl_notice("problem with user space\n");
  336. return 1;
  337. }
  338. /*
  339. * Give the user code a chance to study the request and
  340. * have the opportunity to deny it
  341. */
  342. if ((wsi->protocol->callback)(wsi,
  343. LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION,
  344. wsi->user_space,
  345. lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL), 0)) {
  346. lwsl_warn("User code denied connection\n");
  347. return 1;
  348. }
  349. /*
  350. * Perform the handshake according to the protocol version the
  351. * client announced
  352. */
  353. switch (wsi->ws->ietf_spec_revision) {
  354. default:
  355. lwsl_notice("Unknown client spec version %d\n",
  356. wsi->ws->ietf_spec_revision);
  357. wsi->ws->ietf_spec_revision = 13;
  358. //return 1;
  359. /* fallthru */
  360. case 13:
  361. #if defined(LWS_WITH_HTTP2)
  362. if (wsi->h2_stream_carries_ws) {
  363. if (lws_h2_ws_handshake(wsi)) {
  364. lwsl_notice("h2 ws handshake failed\n");
  365. return 1;
  366. }
  367. lws_role_transition(wsi,
  368. LWSIFR_SERVER | LWSIFR_P_ENCAP_H2,
  369. LRS_ESTABLISHED, &role_ops_ws);
  370. } else
  371. #endif
  372. {
  373. lwsl_parser("lws_parse calling handshake_04\n");
  374. if (handshake_0405(wsi->context, wsi)) {
  375. lwsl_notice("hs0405 has failed the connection\n");
  376. return 1;
  377. }
  378. }
  379. break;
  380. }
  381. lws_server_init_wsi_for_ws(wsi);
  382. lwsl_parser("accepted v%02d connection\n", wsi->ws->ietf_spec_revision);
  383. lwsl_info("%s: %p: dropping ah on ws upgrade\n", __func__, wsi);
  384. lws_header_table_detach(wsi, 1);
  385. return 0;
  386. }
  387. int
  388. handshake_0405(struct lws_context *context, struct lws *wsi)
  389. {
  390. struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
  391. struct lws_process_html_args args;
  392. unsigned char hash[20];
  393. int n, accept_len;
  394. char *response;
  395. char *p;
  396. if (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST) ||
  397. !lws_hdr_total_length(wsi, WSI_TOKEN_KEY)) {
  398. lwsl_info("handshake_04 missing pieces\n");
  399. /* completed header processing, but missing some bits */
  400. goto bail;
  401. }
  402. if (lws_hdr_total_length(wsi, WSI_TOKEN_KEY) >=
  403. MAX_WEBSOCKET_04_KEY_LEN) {
  404. lwsl_warn("Client key too long %d\n", MAX_WEBSOCKET_04_KEY_LEN);
  405. goto bail;
  406. }
  407. /*
  408. * since key length is restricted above (currently 128), cannot
  409. * overflow
  410. */
  411. n = sprintf((char *)pt->serv_buf,
  412. "%s258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
  413. lws_hdr_simple_ptr(wsi, WSI_TOKEN_KEY));
  414. lws_SHA1(pt->serv_buf, n, hash);
  415. accept_len = lws_b64_encode_string((char *)hash, 20,
  416. (char *)pt->serv_buf, context->pt_serv_buf_size);
  417. if (accept_len < 0) {
  418. lwsl_warn("Base64 encoded hash too long\n");
  419. goto bail;
  420. }
  421. /* allocate the per-connection user memory (if any) */
  422. if (lws_ensure_user_space(wsi))
  423. goto bail;
  424. /* create the response packet */
  425. /* make a buffer big enough for everything */
  426. response = (char *)pt->serv_buf + MAX_WEBSOCKET_04_KEY_LEN +
  427. 256 + LWS_PRE;
  428. p = response;
  429. LWS_CPYAPP(p, "HTTP/1.1 101 Switching Protocols\x0d\x0a"
  430. "Upgrade: WebSocket\x0d\x0a"
  431. "Connection: Upgrade\x0d\x0a"
  432. "Sec-WebSocket-Accept: ");
  433. strcpy(p, (char *)pt->serv_buf);
  434. p += accept_len;
  435. /* we can only return the protocol header if:
  436. * - one came in, and ... */
  437. if (lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL) &&
  438. /* - it is not an empty string */
  439. wsi->protocol->name &&
  440. wsi->protocol->name[0]) {
  441. LWS_CPYAPP(p, "\x0d\x0aSec-WebSocket-Protocol: ");
  442. p += lws_snprintf(p, 128, "%s", wsi->protocol->name);
  443. }
  444. #if !defined(LWS_WITHOUT_EXTENSIONS)
  445. /*
  446. * Figure out which extensions the client has that we want to
  447. * enable on this connection, and give him back the list.
  448. *
  449. * Give him a limited write bugdet
  450. */
  451. if (lws_extension_server_handshake(wsi, &p, 192))
  452. goto bail;
  453. #endif
  454. LWS_CPYAPP(p, "\x0d\x0a");
  455. args.p = p;
  456. args.max_len = lws_ptr_diff((char *)pt->serv_buf +
  457. context->pt_serv_buf_size, p);
  458. if (user_callback_handle_rxflow(wsi->protocol->callback, wsi,
  459. LWS_CALLBACK_ADD_HEADERS,
  460. wsi->user_space, &args, 0))
  461. goto bail;
  462. p = args.p;
  463. /* end of response packet */
  464. LWS_CPYAPP(p, "\x0d\x0a");
  465. /* okay send the handshake response accepting the connection */
  466. lwsl_parser("issuing resp pkt %d len\n",
  467. lws_ptr_diff(p, response));
  468. #if defined(DEBUG)
  469. fwrite(response, 1, p - response, stderr);
  470. #endif
  471. n = lws_write(wsi, (unsigned char *)response, p - response,
  472. LWS_WRITE_HTTP_HEADERS);
  473. if (n != (p - response)) {
  474. lwsl_info("%s: ERROR writing to socket %d\n", __func__, n);
  475. goto bail;
  476. }
  477. /* alright clean up and set ourselves into established state */
  478. lwsi_set_state(wsi, LRS_ESTABLISHED);
  479. wsi->lws_rx_parse_state = LWS_RXPS_NEW;
  480. {
  481. const char * uri_ptr =
  482. lws_hdr_simple_ptr(wsi, WSI_TOKEN_GET_URI);
  483. int uri_len = lws_hdr_total_length(wsi, WSI_TOKEN_GET_URI);
  484. const struct lws_http_mount *hit =
  485. lws_find_mount(wsi, uri_ptr, uri_len);
  486. if (hit && hit->cgienv &&
  487. wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP_PMO,
  488. wsi->user_space, (void *)hit->cgienv, 0))
  489. return 1;
  490. }
  491. return 0;
  492. bail:
  493. /* caller will free up his parsing allocations */
  494. return -1;
  495. }
  496. /*
  497. * Once we reach LWS_RXPS_WS_FRAME_PAYLOAD, we know how much
  498. * to expect in that state and can deal with it in bulk more efficiently.
  499. */
  500. static int
  501. lws_ws_frame_rest_is_payload(struct lws *wsi, uint8_t **buf, size_t len)
  502. {
  503. unsigned int avail = (unsigned int)len;
  504. uint8_t *buffer = *buf, mask[4];
  505. struct lws_tokens ebuf;
  506. #if !defined(LWS_WITHOUT_EXTENSIONS)
  507. unsigned int old_packet_length = (int)wsi->ws->rx_packet_length;
  508. #endif
  509. int n = 0;
  510. /*
  511. * With zlib, we can give it as much input as we like. The pmd
  512. * extension will draw it down in chunks (default 1024).
  513. *
  514. * If we try to restrict how much we give it, because we must go
  515. * back to the event loop each time, we will drop the remainder...
  516. */
  517. #if !defined(LWS_WITHOUT_EXTENSIONS)
  518. if (!wsi->ws->count_act_ext)
  519. #endif
  520. {
  521. if (wsi->protocol->rx_buffer_size)
  522. avail = (int)wsi->protocol->rx_buffer_size;
  523. else
  524. avail = wsi->context->pt_serv_buf_size;
  525. }
  526. /* do not consume more than we should */
  527. if (avail > wsi->ws->rx_packet_length)
  528. avail = (unsigned int)wsi->ws->rx_packet_length;
  529. /* do not consume more than what is in the buffer */
  530. if (avail > len)
  531. avail = (unsigned int)len;
  532. if (!avail)
  533. return 0;
  534. ebuf.token = (char *)buffer;
  535. ebuf.len = avail;
  536. //lwsl_hexdump_notice(ebuf.token, ebuf.len);
  537. if (!wsi->ws->all_zero_nonce) {
  538. for (n = 0; n < 4; n++)
  539. mask[n] = wsi->ws->mask[(wsi->ws->mask_idx + n) & 3];
  540. /* deal with 4-byte chunks using unwrapped loop */
  541. n = avail >> 2;
  542. while (n--) {
  543. *(buffer) = *(buffer) ^ mask[0];
  544. buffer++;
  545. *(buffer) = *(buffer) ^ mask[1];
  546. buffer++;
  547. *(buffer) = *(buffer) ^ mask[2];
  548. buffer++;
  549. *(buffer) = *(buffer) ^ mask[3];
  550. buffer++;
  551. }
  552. /* and the remaining bytes bytewise */
  553. for (n = 0; n < (int)(avail & 3); n++) {
  554. *(buffer) = *(buffer) ^ mask[n];
  555. buffer++;
  556. }
  557. wsi->ws->mask_idx = (wsi->ws->mask_idx + avail) & 3;
  558. }
  559. lwsl_info("%s: using %d of raw input (total %d on offer)\n", __func__,
  560. avail, (int)len);
  561. (*buf) += avail;
  562. len -= avail;
  563. #if !defined(LWS_WITHOUT_EXTENSIONS)
  564. n = lws_ext_cb_active(wsi, LWS_EXT_CB_PAYLOAD_RX, &ebuf, 0);
  565. lwsl_info("%s: ext says %d / ebuf.len %d\n", __func__, n, ebuf.len);
  566. #endif
  567. /*
  568. * ebuf may be pointing somewhere completely different now,
  569. * it's the output
  570. */
  571. #if !defined(LWS_WITHOUT_EXTENSIONS)
  572. if (n < 0) {
  573. /*
  574. * we may rely on this to get RX, just drop connection
  575. */
  576. lwsl_notice("%s: LWS_EXT_CB_PAYLOAD_RX blew out\n", __func__);
  577. wsi->socket_is_permanently_unusable = 1;
  578. return -1;
  579. }
  580. #endif
  581. wsi->ws->rx_packet_length -= avail;
  582. #if !defined(LWS_WITHOUT_EXTENSIONS)
  583. /*
  584. * if we had an rx fragment right at the last compressed byte of the
  585. * message, we can get a zero length inflated output, where no prior
  586. * rx inflated output marked themselves with FIN, since there was
  587. * raw ws payload still to drain at that time.
  588. *
  589. * Then we need to generate a zero length ws rx that can be understood
  590. * as the message completion.
  591. */
  592. if (!ebuf.len && /* zero-length inflation output */
  593. !n && /* nothing left to drain from the inflator */
  594. wsi->ws->count_act_ext && /* we are using pmd */
  595. old_packet_length && /* we gave the inflator new input */
  596. !wsi->ws->rx_packet_length && /* raw ws packet payload all gone */
  597. wsi->ws->final && /* the raw ws packet is a FIN guy */
  598. wsi->protocol->callback &&
  599. !wsi->wsistate_pre_close) {
  600. if (user_callback_handle_rxflow(wsi->protocol->callback, wsi,
  601. LWS_CALLBACK_RECEIVE,
  602. wsi->user_space, NULL, 0))
  603. return -1;
  604. return avail;
  605. }
  606. #endif
  607. if (!ebuf.len)
  608. return avail;
  609. if (
  610. #if !defined(LWS_WITHOUT_EXTENSIONS)
  611. n &&
  612. #endif
  613. ebuf.len)
  614. /* extension had more... main loop will come back */
  615. lws_add_wsi_to_draining_ext_list(wsi);
  616. else
  617. lws_remove_wsi_from_draining_ext_list(wsi);
  618. if (wsi->ws->check_utf8 && !wsi->ws->defeat_check_utf8) {
  619. if (lws_check_utf8(&wsi->ws->utf8,
  620. (unsigned char *)ebuf.token, ebuf.len)) {
  621. lws_close_reason(wsi, LWS_CLOSE_STATUS_INVALID_PAYLOAD,
  622. (uint8_t *)"bad utf8", 8);
  623. goto utf8_fail;
  624. }
  625. /* we are ending partway through utf-8 character? */
  626. if (!wsi->ws->rx_packet_length && wsi->ws->final &&
  627. wsi->ws->utf8 && !n) {
  628. lwsl_info("FINAL utf8 error\n");
  629. lws_close_reason(wsi, LWS_CLOSE_STATUS_INVALID_PAYLOAD,
  630. (uint8_t *)"partial utf8", 12);
  631. utf8_fail:
  632. lwsl_info("utf8 error\n");
  633. lwsl_hexdump_info(ebuf.token, ebuf.len);
  634. return -1;
  635. }
  636. }
  637. if (wsi->protocol->callback && !wsi->wsistate_pre_close)
  638. if (user_callback_handle_rxflow(wsi->protocol->callback, wsi,
  639. LWS_CALLBACK_RECEIVE,
  640. wsi->user_space,
  641. ebuf.token, ebuf.len))
  642. return -1;
  643. wsi->ws->first_fragment = 0;
  644. #if !defined(LWS_WITHOUT_EXTENSIONS)
  645. lwsl_info("%s: input used %d, output %d, rem len %d, rx_draining_ext %d\n",
  646. __func__, avail, ebuf.len, (int)len, wsi->ws->rx_draining_ext);
  647. #endif
  648. return avail; /* how much we used from the input */
  649. }
  650. int
  651. lws_parse_ws(struct lws *wsi, unsigned char **buf, size_t len)
  652. {
  653. int m, bulk = 0;
  654. lwsl_debug("%s: received %d byte packet\n", __func__, (int)len);
  655. //lwsl_hexdump_notice(*buf, len);
  656. /* let the rx protocol state machine have as much as it needs */
  657. while (len) {
  658. /*
  659. * we were accepting input but now we stopped doing so
  660. */
  661. if (wsi->rxflow_bitmap) {
  662. lwsl_info("%s: doing rxflow\n", __func__);
  663. lws_rxflow_cache(wsi, *buf, 0, (int)len);
  664. lwsl_parser("%s: cached %ld\n", __func__, (long)len);
  665. *buf += len; /* stashing it is taking care of it */
  666. return 1;
  667. }
  668. #if !defined(LWS_WITHOUT_EXTENSIONS)
  669. if (wsi->ws->rx_draining_ext) {
  670. lwsl_debug("%s: draining rx ext\n", __func__);
  671. m = lws_ws_rx_sm(wsi, ALREADY_PROCESSED_IGNORE_CHAR, 0);
  672. if (m < 0)
  673. return -1;
  674. continue;
  675. }
  676. #endif
  677. /* consume payload bytes efficiently */
  678. while (wsi->lws_rx_parse_state == LWS_RXPS_WS_FRAME_PAYLOAD &&
  679. (wsi->ws->opcode == LWSWSOPC_TEXT_FRAME ||
  680. wsi->ws->opcode == LWSWSOPC_BINARY_FRAME ||
  681. wsi->ws->opcode == LWSWSOPC_CONTINUATION) &&
  682. len) {
  683. uint8_t *bin = *buf;
  684. bulk = 1;
  685. m = lws_ws_frame_rest_is_payload(wsi, buf, len);
  686. assert((int)lws_ptr_diff(*buf, bin) <= (int)len);
  687. len -= lws_ptr_diff(*buf, bin);
  688. if (!m) {
  689. break;
  690. }
  691. if (m < 0) {
  692. lwsl_info("%s: rest_is_payload bailed\n",
  693. __func__);
  694. return -1;
  695. }
  696. }
  697. if (!bulk) {
  698. /* process the byte */
  699. m = lws_ws_rx_sm(wsi, 0, *(*buf)++);
  700. len--;
  701. } else {
  702. /*
  703. * We already handled this byte in bulk, just deal
  704. * with the ramifications
  705. */
  706. #if !defined(LWS_WITHOUT_EXTENSIONS)
  707. lwsl_debug("%s: coming out of bulk with len %d, "
  708. "wsi->ws->rx_draining_ext %d\n",
  709. __func__, (int)len,
  710. wsi->ws->rx_draining_ext);
  711. #endif
  712. m = lws_ws_rx_sm(wsi, ALREADY_PROCESSED_IGNORE_CHAR |
  713. ALREADY_PROCESSED_NO_CB, 0);
  714. }
  715. if (m < 0) {
  716. lwsl_info("%s: lws_ws_rx_sm bailed %d\n", __func__,
  717. bulk);
  718. return -1;
  719. }
  720. bulk = 0;
  721. }
  722. lwsl_debug("%s: exit with %d unused\n", __func__, (int)len);
  723. return 0;
  724. }