ws.c 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at https://curl.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. * SPDX-License-Identifier: curl
  22. *
  23. ***************************************************************************/
  24. #include "curl_setup.h"
  25. #include <curl/curl.h>
  26. #ifdef USE_WEBSOCKETS
  27. #include "urldata.h"
  28. #include "bufq.h"
  29. #include "dynbuf.h"
  30. #include "rand.h"
  31. #include "curl_base64.h"
  32. #include "connect.h"
  33. #include "sendf.h"
  34. #include "multiif.h"
  35. #include "ws.h"
  36. #include "easyif.h"
  37. #include "transfer.h"
  38. #include "nonblock.h"
  39. /* The last 3 #include files should be in this order */
  40. #include "curl_printf.h"
  41. #include "curl_memory.h"
  42. #include "memdebug.h"
  43. #define WSBIT_FIN 0x80
  44. #define WSBIT_OPCODE_CONT 0
  45. #define WSBIT_OPCODE_TEXT (1)
  46. #define WSBIT_OPCODE_BIN (2)
  47. #define WSBIT_OPCODE_CLOSE (8)
  48. #define WSBIT_OPCODE_PING (9)
  49. #define WSBIT_OPCODE_PONG (0xa)
  50. #define WSBIT_OPCODE_MASK (0xf)
  51. #define WSBIT_MASK 0x80
  52. /* buffer dimensioning */
  53. #define WS_CHUNK_SIZE 65535
  54. #define WS_CHUNK_COUNT 2
  55. struct ws_frame_meta {
  56. char proto_opcode;
  57. int flags;
  58. const char *name;
  59. };
  60. static struct ws_frame_meta WS_FRAMES[] = {
  61. { WSBIT_OPCODE_CONT, CURLWS_CONT, "CONT" },
  62. { WSBIT_OPCODE_TEXT, CURLWS_TEXT, "TEXT" },
  63. { WSBIT_OPCODE_BIN, CURLWS_BINARY, "BIN" },
  64. { WSBIT_OPCODE_CLOSE, CURLWS_CLOSE, "CLOSE" },
  65. { WSBIT_OPCODE_PING, CURLWS_PING, "PING" },
  66. { WSBIT_OPCODE_PONG, CURLWS_PONG, "PONG" },
  67. };
  68. static const char *ws_frame_name_of_op(unsigned char proto_opcode)
  69. {
  70. unsigned char opcode = proto_opcode & WSBIT_OPCODE_MASK;
  71. size_t i;
  72. for(i = 0; i < sizeof(WS_FRAMES)/sizeof(WS_FRAMES[0]); ++i) {
  73. if(WS_FRAMES[i].proto_opcode == opcode)
  74. return WS_FRAMES[i].name;
  75. }
  76. return "???";
  77. }
  78. static int ws_frame_op2flags(unsigned char proto_opcode)
  79. {
  80. unsigned char opcode = proto_opcode & WSBIT_OPCODE_MASK;
  81. size_t i;
  82. for(i = 0; i < sizeof(WS_FRAMES)/sizeof(WS_FRAMES[0]); ++i) {
  83. if(WS_FRAMES[i].proto_opcode == opcode)
  84. return WS_FRAMES[i].flags;
  85. }
  86. return 0;
  87. }
  88. static unsigned char ws_frame_flags2op(int flags)
  89. {
  90. size_t i;
  91. for(i = 0; i < sizeof(WS_FRAMES)/sizeof(WS_FRAMES[0]); ++i) {
  92. if(WS_FRAMES[i].flags & flags)
  93. return WS_FRAMES[i].proto_opcode;
  94. }
  95. return 0;
  96. }
  97. static void ws_dec_info(struct ws_decoder *dec, struct Curl_easy *data,
  98. const char *msg)
  99. {
  100. switch(dec->head_len) {
  101. case 0:
  102. break;
  103. case 1:
  104. infof(data, "WS-DEC: %s [%s%s]", msg,
  105. ws_frame_name_of_op(dec->head[0]),
  106. (dec->head[0] & WSBIT_FIN)? "" : " NON-FINAL");
  107. break;
  108. default:
  109. if(dec->head_len < dec->head_total) {
  110. infof(data, "WS-DEC: %s [%s%s](%d/%d)", msg,
  111. ws_frame_name_of_op(dec->head[0]),
  112. (dec->head[0] & WSBIT_FIN)? "" : " NON-FINAL",
  113. dec->head_len, dec->head_total);
  114. }
  115. else {
  116. infof(data, "WS-DEC: %s [%s%s payload=%" CURL_FORMAT_CURL_OFF_T
  117. "/%" CURL_FORMAT_CURL_OFF_T "]",
  118. msg, ws_frame_name_of_op(dec->head[0]),
  119. (dec->head[0] & WSBIT_FIN)? "" : " NON-FINAL",
  120. dec->payload_offset, dec->payload_len);
  121. }
  122. break;
  123. }
  124. }
  125. typedef ssize_t ws_write_payload(const unsigned char *buf, size_t buflen,
  126. int frame_age, int frame_flags,
  127. curl_off_t payload_offset,
  128. curl_off_t payload_len,
  129. void *userp,
  130. CURLcode *err);
  131. static void ws_dec_reset(struct ws_decoder *dec)
  132. {
  133. dec->frame_age = 0;
  134. dec->frame_flags = 0;
  135. dec->payload_offset = 0;
  136. dec->payload_len = 0;
  137. dec->head_len = dec->head_total = 0;
  138. dec->state = WS_DEC_INIT;
  139. }
  140. static void ws_dec_init(struct ws_decoder *dec)
  141. {
  142. ws_dec_reset(dec);
  143. }
  144. static CURLcode ws_dec_read_head(struct ws_decoder *dec,
  145. struct Curl_easy *data,
  146. struct bufq *inraw)
  147. {
  148. const unsigned char *inbuf;
  149. size_t inlen;
  150. while(Curl_bufq_peek(inraw, &inbuf, &inlen)) {
  151. if(dec->head_len == 0) {
  152. dec->head[0] = *inbuf;
  153. Curl_bufq_skip(inraw, 1);
  154. dec->frame_flags = ws_frame_op2flags(dec->head[0]);
  155. if(!dec->frame_flags) {
  156. failf(data, "WS: unknown opcode: %x", dec->head[0]);
  157. ws_dec_reset(dec);
  158. return CURLE_RECV_ERROR;
  159. }
  160. dec->head_len = 1;
  161. /* ws_dec_info(dec, data, "seeing opcode"); */
  162. continue;
  163. }
  164. else if(dec->head_len == 1) {
  165. dec->head[1] = *inbuf;
  166. Curl_bufq_skip(inraw, 1);
  167. dec->head_len = 2;
  168. if(dec->head[1] & WSBIT_MASK) {
  169. /* A client MUST close a connection if it detects a masked frame. */
  170. failf(data, "WS: masked input frame");
  171. ws_dec_reset(dec);
  172. return CURLE_RECV_ERROR;
  173. }
  174. /* How long is the frame head? */
  175. if(dec->head[1] == 126) {
  176. dec->head_total = 4;
  177. continue;
  178. }
  179. else if(dec->head[1] == 127) {
  180. dec->head_total = 10;
  181. continue;
  182. }
  183. else {
  184. dec->head_total = 2;
  185. }
  186. }
  187. if(dec->head_len < dec->head_total) {
  188. dec->head[dec->head_len] = *inbuf;
  189. Curl_bufq_skip(inraw, 1);
  190. ++dec->head_len;
  191. if(dec->head_len < dec->head_total) {
  192. /* ws_dec_info(dec, data, "decoding head"); */
  193. continue;
  194. }
  195. }
  196. /* got the complete frame head */
  197. DEBUGASSERT(dec->head_len == dec->head_total);
  198. switch(dec->head_total) {
  199. case 2:
  200. dec->payload_len = dec->head[1];
  201. break;
  202. case 4:
  203. dec->payload_len = (dec->head[2] << 8) | dec->head[3];
  204. break;
  205. case 10:
  206. dec->payload_len = ((curl_off_t)dec->head[2] << 56) |
  207. (curl_off_t)dec->head[3] << 48 |
  208. (curl_off_t)dec->head[4] << 40 |
  209. (curl_off_t)dec->head[5] << 32 |
  210. (curl_off_t)dec->head[6] << 24 |
  211. (curl_off_t)dec->head[7] << 16 |
  212. (curl_off_t)dec->head[8] << 8 |
  213. dec->head[9];
  214. break;
  215. default:
  216. /* this should never happen */
  217. DEBUGASSERT(0);
  218. failf(data, "WS: unexpected frame header length");
  219. return CURLE_RECV_ERROR;
  220. }
  221. dec->frame_age = 0;
  222. dec->payload_offset = 0;
  223. ws_dec_info(dec, data, "decoded");
  224. return CURLE_OK;
  225. }
  226. return CURLE_AGAIN;
  227. }
  228. static CURLcode ws_dec_pass_payload(struct ws_decoder *dec,
  229. struct Curl_easy *data,
  230. struct bufq *inraw,
  231. ws_write_payload *write_payload,
  232. void *write_ctx)
  233. {
  234. const unsigned char *inbuf;
  235. size_t inlen;
  236. ssize_t nwritten;
  237. CURLcode result;
  238. curl_off_t remain = dec->payload_len - dec->payload_offset;
  239. (void)data;
  240. while(remain && Curl_bufq_peek(inraw, &inbuf, &inlen)) {
  241. if((curl_off_t)inlen > remain)
  242. inlen = (size_t)remain;
  243. nwritten = write_payload(inbuf, inlen, dec->frame_age, dec->frame_flags,
  244. dec->payload_offset, dec->payload_len,
  245. write_ctx, &result);
  246. if(nwritten < 0)
  247. return result;
  248. Curl_bufq_skip(inraw, (size_t)nwritten);
  249. dec->payload_offset += (curl_off_t)nwritten;
  250. remain = dec->payload_len - dec->payload_offset;
  251. /* infof(data, "WS-DEC: passed %zd bytes payload, %"
  252. CURL_FORMAT_CURL_OFF_T " remain",
  253. nwritten, remain); */
  254. }
  255. return remain? CURLE_AGAIN : CURLE_OK;
  256. }
  257. static CURLcode ws_dec_pass(struct ws_decoder *dec,
  258. struct Curl_easy *data,
  259. struct bufq *inraw,
  260. ws_write_payload *write_payload,
  261. void *write_ctx)
  262. {
  263. CURLcode result;
  264. if(Curl_bufq_is_empty(inraw))
  265. return CURLE_AGAIN;
  266. switch(dec->state) {
  267. case WS_DEC_INIT:
  268. ws_dec_reset(dec);
  269. dec->state = WS_DEC_HEAD;
  270. /* FALLTHROUGH */
  271. case WS_DEC_HEAD:
  272. result = ws_dec_read_head(dec, data, inraw);
  273. if(result) {
  274. if(result != CURLE_AGAIN) {
  275. infof(data, "WS: decode error %d", (int)result);
  276. break; /* real error */
  277. }
  278. /* incomplete ws frame head */
  279. DEBUGASSERT(Curl_bufq_is_empty(inraw));
  280. break;
  281. }
  282. /* head parsing done */
  283. dec->state = WS_DEC_PAYLOAD;
  284. if(dec->payload_len == 0) {
  285. ssize_t nwritten;
  286. const unsigned char tmp = '\0';
  287. /* special case of a 0 length frame, need to write once */
  288. nwritten = write_payload(&tmp, 0, dec->frame_age, dec->frame_flags,
  289. 0, 0, write_ctx, &result);
  290. if(nwritten < 0)
  291. return result;
  292. dec->state = WS_DEC_INIT;
  293. break;
  294. }
  295. /* FALLTHROUGH */
  296. case WS_DEC_PAYLOAD:
  297. result = ws_dec_pass_payload(dec, data, inraw, write_payload, write_ctx);
  298. ws_dec_info(dec, data, "passing");
  299. if(result)
  300. return result;
  301. /* paylod parsing done */
  302. dec->state = WS_DEC_INIT;
  303. break;
  304. default:
  305. /* we covered all enums above, but some code analyzers are whimps */
  306. result = CURLE_FAILED_INIT;
  307. }
  308. return result;
  309. }
  310. static void update_meta(struct websocket *ws,
  311. int frame_age, int frame_flags,
  312. curl_off_t payload_offset,
  313. curl_off_t payload_len,
  314. size_t cur_len)
  315. {
  316. ws->frame.age = frame_age;
  317. ws->frame.flags = frame_flags;
  318. ws->frame.offset = payload_offset;
  319. ws->frame.len = cur_len;
  320. ws->frame.bytesleft = (payload_len - payload_offset - cur_len);
  321. }
  322. static void ws_enc_info(struct ws_encoder *enc, struct Curl_easy *data,
  323. const char *msg)
  324. {
  325. infof(data, "WS-ENC: %s [%s%s%s payload=%" CURL_FORMAT_CURL_OFF_T
  326. "/%" CURL_FORMAT_CURL_OFF_T "]",
  327. msg, ws_frame_name_of_op(enc->firstbyte),
  328. (enc->firstbyte & WSBIT_OPCODE_MASK) == WSBIT_OPCODE_CONT ?
  329. " CONT" : "",
  330. (enc->firstbyte & WSBIT_FIN)? "" : " NON-FIN",
  331. enc->payload_len - enc->payload_remain, enc->payload_len);
  332. }
  333. static void ws_enc_reset(struct ws_encoder *enc)
  334. {
  335. enc->payload_remain = 0;
  336. enc->xori = 0;
  337. enc->contfragment = FALSE;
  338. }
  339. static void ws_enc_init(struct ws_encoder *enc)
  340. {
  341. ws_enc_reset(enc);
  342. }
  343. /***
  344. RFC 6455 Section 5.2
  345. 0 1 2 3
  346. 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
  347. +-+-+-+-+-------+-+-------------+-------------------------------+
  348. |F|R|R|R| opcode|M| Payload len | Extended payload length |
  349. |I|S|S|S| (4) |A| (7) | (16/64) |
  350. |N|V|V|V| |S| | (if payload len==126/127) |
  351. | |1|2|3| |K| | |
  352. +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
  353. | Extended payload length continued, if payload len == 127 |
  354. + - - - - - - - - - - - - - - - +-------------------------------+
  355. | |Masking-key, if MASK set to 1 |
  356. +-------------------------------+-------------------------------+
  357. | Masking-key (continued) | Payload Data |
  358. +-------------------------------- - - - - - - - - - - - - - - - +
  359. : Payload Data continued ... :
  360. + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
  361. | Payload Data continued ... |
  362. +---------------------------------------------------------------+
  363. */
  364. static ssize_t ws_enc_write_head(struct Curl_easy *data,
  365. struct ws_encoder *enc,
  366. unsigned int flags,
  367. curl_off_t payload_len,
  368. struct bufq *out,
  369. CURLcode *err)
  370. {
  371. unsigned char firstbyte = 0;
  372. unsigned char opcode;
  373. unsigned char head[14];
  374. size_t hlen;
  375. ssize_t n;
  376. if(enc->payload_remain > 0) {
  377. /* trying to write a new frame before the previous one is finished */
  378. failf(data, "WS: starting new frame with %zd bytes from last one"
  379. "remaining to be sent", (ssize_t)enc->payload_remain);
  380. *err = CURLE_SEND_ERROR;
  381. return -1;
  382. }
  383. opcode = ws_frame_flags2op(flags);
  384. if(!opcode) {
  385. failf(data, "WS: provided flags not recognized '%x'", flags);
  386. *err = CURLE_SEND_ERROR;
  387. return -1;
  388. }
  389. if(!(flags & CURLWS_CONT)) {
  390. if(!enc->contfragment)
  391. /* not marked as continuing, this is the final fragment */
  392. firstbyte |= WSBIT_FIN | opcode;
  393. else
  394. /* marked as continuing, this is the final fragment; set CONT
  395. opcode and FIN bit */
  396. firstbyte |= WSBIT_FIN | WSBIT_OPCODE_CONT;
  397. enc->contfragment = FALSE;
  398. }
  399. else if(enc->contfragment) {
  400. /* the previous fragment was not a final one and this isn't either, keep a
  401. CONT opcode and no FIN bit */
  402. firstbyte |= WSBIT_OPCODE_CONT;
  403. }
  404. else {
  405. firstbyte = opcode;
  406. enc->contfragment = TRUE;
  407. }
  408. head[0] = enc->firstbyte = firstbyte;
  409. if(payload_len > 65535) {
  410. head[1] = 127 | WSBIT_MASK;
  411. head[2] = (unsigned char)((payload_len >> 56) & 0xff);
  412. head[3] = (unsigned char)((payload_len >> 48) & 0xff);
  413. head[4] = (unsigned char)((payload_len >> 40) & 0xff);
  414. head[5] = (unsigned char)((payload_len >> 32) & 0xff);
  415. head[6] = (unsigned char)((payload_len >> 24) & 0xff);
  416. head[7] = (unsigned char)((payload_len >> 16) & 0xff);
  417. head[8] = (unsigned char)((payload_len >> 8) & 0xff);
  418. head[9] = (unsigned char)(payload_len & 0xff);
  419. hlen = 10;
  420. }
  421. else if(payload_len >= 126) {
  422. head[1] = 126 | WSBIT_MASK;
  423. head[2] = (unsigned char)((payload_len >> 8) & 0xff);
  424. head[3] = (unsigned char)(payload_len & 0xff);
  425. hlen = 4;
  426. }
  427. else {
  428. head[1] = (unsigned char)payload_len | WSBIT_MASK;
  429. hlen = 2;
  430. }
  431. enc->payload_remain = enc->payload_len = payload_len;
  432. ws_enc_info(enc, data, "sending");
  433. /* add 4 bytes mask */
  434. memcpy(&head[hlen], &enc->mask, 4);
  435. hlen += 4;
  436. /* reset for payload to come */
  437. enc->xori = 0;
  438. n = Curl_bufq_write(out, head, hlen, err);
  439. if(n < 0)
  440. return -1;
  441. if((size_t)n != hlen) {
  442. /* We use a bufq with SOFT_LIMIT, writing should always succeed */
  443. DEBUGASSERT(0);
  444. *err = CURLE_SEND_ERROR;
  445. return -1;
  446. }
  447. return n;
  448. }
  449. static ssize_t ws_enc_write_payload(struct ws_encoder *enc,
  450. struct Curl_easy *data,
  451. const unsigned char *buf, size_t buflen,
  452. struct bufq *out, CURLcode *err)
  453. {
  454. ssize_t n;
  455. size_t i, len;
  456. if(Curl_bufq_is_full(out)) {
  457. *err = CURLE_AGAIN;
  458. return -1;
  459. }
  460. /* not the most performant way to do this */
  461. len = buflen;
  462. if((curl_off_t)len > enc->payload_remain)
  463. len = (size_t)enc->payload_remain;
  464. for(i = 0; i < len; ++i) {
  465. unsigned char c = buf[i] ^ enc->mask[enc->xori];
  466. n = Curl_bufq_write(out, &c, 1, err);
  467. if(n < 0) {
  468. if((*err != CURLE_AGAIN) || !i)
  469. return -1;
  470. break;
  471. }
  472. enc->xori++;
  473. enc->xori &= 3;
  474. }
  475. enc->payload_remain -= (curl_off_t)i;
  476. ws_enc_info(enc, data, "buffered");
  477. return (ssize_t)i;
  478. }
  479. struct wsfield {
  480. const char *name;
  481. const char *val;
  482. };
  483. CURLcode Curl_ws_request(struct Curl_easy *data, REQTYPE *req)
  484. {
  485. unsigned int i;
  486. CURLcode result = CURLE_OK;
  487. unsigned char rand[16];
  488. char *randstr;
  489. size_t randlen;
  490. char keyval[40];
  491. struct SingleRequest *k = &data->req;
  492. struct wsfield heads[]= {
  493. {
  494. /* The request MUST contain an |Upgrade| header field whose value
  495. MUST include the "websocket" keyword. */
  496. "Upgrade:", "websocket"
  497. },
  498. {
  499. /* The request MUST contain a |Connection| header field whose value
  500. MUST include the "Upgrade" token. */
  501. "Connection:", "Upgrade",
  502. },
  503. {
  504. /* The request MUST include a header field with the name
  505. |Sec-WebSocket-Version|. The value of this header field MUST be
  506. 13. */
  507. "Sec-WebSocket-Version:", "13",
  508. },
  509. {
  510. /* The request MUST include a header field with the name
  511. |Sec-WebSocket-Key|. The value of this header field MUST be a nonce
  512. consisting of a randomly selected 16-byte value that has been
  513. base64-encoded (see Section 4 of [RFC4648]). The nonce MUST be
  514. selected randomly for each connection. */
  515. "Sec-WebSocket-Key:", NULL,
  516. }
  517. };
  518. heads[3].val = &keyval[0];
  519. /* 16 bytes random */
  520. result = Curl_rand(data, (unsigned char *)rand, sizeof(rand));
  521. if(result)
  522. return result;
  523. result = Curl_base64_encode((char *)rand, sizeof(rand), &randstr, &randlen);
  524. if(result)
  525. return result;
  526. DEBUGASSERT(randlen < sizeof(keyval));
  527. if(randlen >= sizeof(keyval))
  528. return CURLE_FAILED_INIT;
  529. strcpy(keyval, randstr);
  530. free(randstr);
  531. for(i = 0; !result && (i < sizeof(heads)/sizeof(heads[0])); i++) {
  532. if(!Curl_checkheaders(data, STRCONST(heads[i].name))) {
  533. #ifdef USE_HYPER
  534. char field[128];
  535. msnprintf(field, sizeof(field), "%s %s", heads[i].name,
  536. heads[i].val);
  537. result = Curl_hyper_header(data, req, field);
  538. #else
  539. (void)data;
  540. result = Curl_dyn_addf(req, "%s %s\r\n", heads[i].name,
  541. heads[i].val);
  542. #endif
  543. }
  544. }
  545. k->upgr101 = UPGR101_WS;
  546. return result;
  547. }
  548. /*
  549. * 'nread' is number of bytes of websocket data already in the buffer at
  550. * 'mem'.
  551. */
  552. CURLcode Curl_ws_accept(struct Curl_easy *data,
  553. const char *mem, size_t nread)
  554. {
  555. struct SingleRequest *k = &data->req;
  556. struct websocket *ws;
  557. CURLcode result;
  558. DEBUGASSERT(data->conn);
  559. ws = data->conn->proto.ws;
  560. if(!ws) {
  561. ws = calloc(1, sizeof(*ws));
  562. if(!ws)
  563. return CURLE_OUT_OF_MEMORY;
  564. data->conn->proto.ws = ws;
  565. Curl_bufq_init(&ws->recvbuf, WS_CHUNK_SIZE, WS_CHUNK_COUNT);
  566. Curl_bufq_init2(&ws->sendbuf, WS_CHUNK_SIZE, WS_CHUNK_COUNT,
  567. BUFQ_OPT_SOFT_LIMIT);
  568. ws_dec_init(&ws->dec);
  569. ws_enc_init(&ws->enc);
  570. }
  571. else {
  572. Curl_bufq_reset(&ws->recvbuf);
  573. ws_dec_reset(&ws->dec);
  574. ws_enc_reset(&ws->enc);
  575. }
  576. /* Verify the Sec-WebSocket-Accept response.
  577. The sent value is the base64 encoded version of a SHA-1 hash done on the
  578. |Sec-WebSocket-Key| header field concatenated with
  579. the string "258EAFA5-E914-47DA-95CA-C5AB0DC85B11".
  580. */
  581. /* If the response includes a |Sec-WebSocket-Extensions| header field and
  582. this header field indicates the use of an extension that was not present
  583. in the client's handshake (the server has indicated an extension not
  584. requested by the client), the client MUST Fail the WebSocket Connection.
  585. */
  586. /* If the response includes a |Sec-WebSocket-Protocol| header field
  587. and this header field indicates the use of a subprotocol that was
  588. not present in the client's handshake (the server has indicated a
  589. subprotocol not requested by the client), the client MUST Fail
  590. the WebSocket Connection. */
  591. /* 4 bytes random */
  592. result = Curl_rand(data, (unsigned char *)&ws->enc.mask,
  593. sizeof(ws->enc.mask));
  594. if(result)
  595. return result;
  596. infof(data, "Received 101, switch to WebSocket; mask %02x%02x%02x%02x",
  597. ws->enc.mask[0], ws->enc.mask[1], ws->enc.mask[2], ws->enc.mask[3]);
  598. if(data->set.connect_only) {
  599. ssize_t nwritten;
  600. /* In CONNECT_ONLY setup, the payloads from `mem` need to be received
  601. * when using `curl_ws_recv` later on after this transfer is already
  602. * marked as DONE. */
  603. nwritten = Curl_bufq_write(&ws->recvbuf, (const unsigned char *)mem,
  604. nread, &result);
  605. if(nwritten < 0)
  606. return result;
  607. infof(data, "%zu bytes websocket payload", nread);
  608. }
  609. k->upgr101 = UPGR101_RECEIVED;
  610. return result;
  611. }
  612. static ssize_t ws_client_write(const unsigned char *buf, size_t buflen,
  613. int frame_age, int frame_flags,
  614. curl_off_t payload_offset,
  615. curl_off_t payload_len,
  616. void *userp,
  617. CURLcode *err)
  618. {
  619. struct Curl_easy *data = userp;
  620. struct websocket *ws;
  621. size_t wrote;
  622. curl_off_t remain = (payload_len - (payload_offset + buflen));
  623. (void)frame_age;
  624. if(!data->conn || !data->conn->proto.ws) {
  625. *err = CURLE_FAILED_INIT;
  626. return -1;
  627. }
  628. ws = data->conn->proto.ws;
  629. if((frame_flags & CURLWS_PING) && !remain) {
  630. /* auto-respond to PINGs, only works for single-frame payloads atm */
  631. size_t bytes;
  632. infof(data, "WS: auto-respond to PING with a PONG");
  633. /* send back the exact same content as a PONG */
  634. *err = curl_ws_send(data, buf, buflen, &bytes, 0, CURLWS_PONG);
  635. if(*err)
  636. return -1;
  637. }
  638. else if(buflen || !remain) {
  639. /* deliver the decoded frame to the user callback. The application
  640. * may invoke curl_ws_meta() to access frame information. */
  641. update_meta(ws, frame_age, frame_flags, payload_offset,
  642. payload_len, buflen);
  643. Curl_set_in_callback(data, true);
  644. wrote = data->set.fwrite_func((char *)buf, 1,
  645. buflen, data->set.out);
  646. Curl_set_in_callback(data, false);
  647. if(wrote != buflen) {
  648. *err = CURLE_RECV_ERROR;
  649. return -1;
  650. }
  651. }
  652. *err = CURLE_OK;
  653. return (ssize_t)buflen;
  654. }
  655. /* Curl_ws_writecb() is the write callback for websocket traffic. The
  656. websocket data is provided to this raw, in chunks. This function should
  657. handle/decode the data and call the "real" underlying callback accordingly.
  658. */
  659. size_t Curl_ws_writecb(char *buffer, size_t size /* 1 */,
  660. size_t nitems, void *userp)
  661. {
  662. struct Curl_easy *data = userp;
  663. if(data->set.ws_raw_mode)
  664. return data->set.fwrite_func(buffer, size, nitems, data->set.out);
  665. else if(nitems) {
  666. struct websocket *ws;
  667. CURLcode result;
  668. if(!data->conn || !data->conn->proto.ws) {
  669. failf(data, "WS: not a websocket transfer");
  670. return nitems - 1;
  671. }
  672. ws = data->conn->proto.ws;
  673. if(buffer) {
  674. ssize_t nwritten;
  675. nwritten = Curl_bufq_write(&ws->recvbuf, (const unsigned char *)buffer,
  676. nitems, &result);
  677. if(nwritten < 0) {
  678. infof(data, "WS: error adding data to buffer %d", (int)result);
  679. return nitems - 1;
  680. }
  681. buffer = NULL;
  682. }
  683. while(!Curl_bufq_is_empty(&ws->recvbuf)) {
  684. result = ws_dec_pass(&ws->dec, data, &ws->recvbuf,
  685. ws_client_write, data);
  686. if(result == CURLE_AGAIN)
  687. /* insufficient amount of data, keep it for later.
  688. * we pretend to have written all since we have a copy */
  689. return nitems;
  690. else if(result) {
  691. infof(data, "WS: decode error %d", (int)result);
  692. return nitems - 1;
  693. }
  694. }
  695. }
  696. return nitems;
  697. }
  698. struct ws_collect {
  699. struct Curl_easy *data;
  700. void *buffer;
  701. size_t buflen;
  702. size_t bufidx;
  703. int frame_age;
  704. int frame_flags;
  705. curl_off_t payload_offset;
  706. curl_off_t payload_len;
  707. bool written;
  708. };
  709. static ssize_t ws_client_collect(const unsigned char *buf, size_t buflen,
  710. int frame_age, int frame_flags,
  711. curl_off_t payload_offset,
  712. curl_off_t payload_len,
  713. void *userp,
  714. CURLcode *err)
  715. {
  716. struct ws_collect *ctx = userp;
  717. size_t nwritten;
  718. curl_off_t remain = (payload_len - (payload_offset + buflen));
  719. if(!ctx->bufidx) {
  720. /* first write */
  721. ctx->frame_age = frame_age;
  722. ctx->frame_flags = frame_flags;
  723. ctx->payload_offset = payload_offset;
  724. ctx->payload_len = payload_len;
  725. }
  726. if((frame_flags & CURLWS_PING) && !remain) {
  727. /* auto-respond to PINGs, only works for single-frame payloads atm */
  728. size_t bytes;
  729. infof(ctx->data, "WS: auto-respond to PING with a PONG");
  730. /* send back the exact same content as a PONG */
  731. *err = curl_ws_send(ctx->data, buf, buflen, &bytes, 0, CURLWS_PONG);
  732. if(*err)
  733. return -1;
  734. nwritten = bytes;
  735. }
  736. else {
  737. ctx->written = TRUE;
  738. DEBUGASSERT(ctx->buflen >= ctx->bufidx);
  739. nwritten = CURLMIN(buflen, ctx->buflen - ctx->bufidx);
  740. if(!nwritten) {
  741. if(!buflen) { /* 0 length write, we accept that */
  742. *err = CURLE_OK;
  743. return 0;
  744. }
  745. *err = CURLE_AGAIN; /* no more space */
  746. return -1;
  747. }
  748. *err = CURLE_OK;
  749. memcpy(ctx->buffer, buf, nwritten);
  750. ctx->bufidx += nwritten;
  751. }
  752. return nwritten;
  753. }
  754. static ssize_t nw_in_recv(void *reader_ctx,
  755. unsigned char *buf, size_t buflen,
  756. CURLcode *err)
  757. {
  758. struct Curl_easy *data = reader_ctx;
  759. size_t nread;
  760. *err = curl_easy_recv(data, buf, buflen, &nread);
  761. if(*err)
  762. return -1;
  763. return (ssize_t)nread;
  764. }
  765. CURL_EXTERN CURLcode curl_ws_recv(struct Curl_easy *data, void *buffer,
  766. size_t buflen, size_t *nread,
  767. const struct curl_ws_frame **metap)
  768. {
  769. struct connectdata *conn = data->conn;
  770. struct websocket *ws;
  771. bool done = FALSE; /* not filled passed buffer yet */
  772. struct ws_collect ctx;
  773. CURLcode result;
  774. if(!conn) {
  775. /* Unhappy hack with lifetimes of transfers and connection */
  776. if(!data->set.connect_only) {
  777. failf(data, "CONNECT_ONLY is required");
  778. return CURLE_UNSUPPORTED_PROTOCOL;
  779. }
  780. Curl_getconnectinfo(data, &conn);
  781. if(!conn) {
  782. failf(data, "connection not found");
  783. return CURLE_BAD_FUNCTION_ARGUMENT;
  784. }
  785. }
  786. ws = conn->proto.ws;
  787. if(!ws) {
  788. failf(data, "connection is not setup for websocket");
  789. return CURLE_BAD_FUNCTION_ARGUMENT;
  790. }
  791. *nread = 0;
  792. *metap = NULL;
  793. /* get a download buffer */
  794. result = Curl_preconnect(data);
  795. if(result)
  796. return result;
  797. memset(&ctx, 0, sizeof(ctx));
  798. ctx.data = data;
  799. ctx.buffer = buffer;
  800. ctx.buflen = buflen;
  801. while(!done) {
  802. /* receive more when our buffer is empty */
  803. if(Curl_bufq_is_empty(&ws->recvbuf)) {
  804. ssize_t n = Curl_bufq_slurp(&ws->recvbuf, nw_in_recv, data, &result);
  805. if(n < 0) {
  806. return result;
  807. }
  808. else if(n == 0) {
  809. /* connection closed */
  810. infof(data, "connection expectedly closed?");
  811. return CURLE_GOT_NOTHING;
  812. }
  813. DEBUGF(infof(data, "curl_ws_recv, added %zu bytes from network",
  814. Curl_bufq_len(&ws->recvbuf)));
  815. }
  816. result = ws_dec_pass(&ws->dec, data, &ws->recvbuf,
  817. ws_client_collect, &ctx);
  818. if(result == CURLE_AGAIN) {
  819. if(!ctx.written) {
  820. ws_dec_info(&ws->dec, data, "need more input");
  821. continue; /* nothing written, try more input */
  822. }
  823. done = TRUE;
  824. break;
  825. }
  826. else if(result) {
  827. return result;
  828. }
  829. else if(ctx.written) {
  830. /* The decoded frame is passed back to our caller.
  831. * There are frames like PING were we auto-respond to and
  832. * that we do not return. For these `ctx.written` is not set. */
  833. done = TRUE;
  834. break;
  835. }
  836. }
  837. /* update frame information to be passed back */
  838. update_meta(ws, ctx.frame_age, ctx.frame_flags, ctx.payload_offset,
  839. ctx.payload_len, ctx.bufidx);
  840. *metap = &ws->frame;
  841. *nread = ws->frame.len;
  842. /* infof(data, "curl_ws_recv(len=%zu) -> %zu bytes (frame at %"
  843. CURL_FORMAT_CURL_OFF_T ", %" CURL_FORMAT_CURL_OFF_T " left)",
  844. buflen, *nread, ws->frame.offset, ws->frame.bytesleft); */
  845. return CURLE_OK;
  846. }
  847. static CURLcode ws_flush(struct Curl_easy *data, struct websocket *ws,
  848. bool complete)
  849. {
  850. if(!Curl_bufq_is_empty(&ws->sendbuf)) {
  851. CURLcode result;
  852. const unsigned char *out;
  853. size_t outlen;
  854. ssize_t n;
  855. while(Curl_bufq_peek(&ws->sendbuf, &out, &outlen)) {
  856. if(data->set.connect_only)
  857. result = Curl_senddata(data, out, outlen, &n);
  858. else
  859. result = Curl_write(data, data->conn->writesockfd, out, outlen, &n);
  860. if(result) {
  861. if(result == CURLE_AGAIN) {
  862. if(!complete) {
  863. infof(data, "WS: flush EAGAIN, %zu bytes remain in buffer",
  864. Curl_bufq_len(&ws->sendbuf));
  865. return result;
  866. }
  867. /* TODO: the current design does not allow for buffered writes.
  868. * We need to flush the buffer now. There is no ws_flush() later */
  869. n = 0;
  870. continue;
  871. }
  872. else if(result) {
  873. failf(data, "WS: flush, write error %d", result);
  874. return result;
  875. }
  876. }
  877. else {
  878. infof(data, "WS: flushed %zu bytes", (size_t)n);
  879. Curl_bufq_skip(&ws->sendbuf, (size_t)n);
  880. }
  881. }
  882. }
  883. return CURLE_OK;
  884. }
  885. CURL_EXTERN CURLcode curl_ws_send(CURL *data, const void *buffer,
  886. size_t buflen, size_t *sent,
  887. curl_off_t fragsize,
  888. unsigned int flags)
  889. {
  890. struct websocket *ws;
  891. ssize_t nwritten, n;
  892. size_t space;
  893. CURLcode result;
  894. *sent = 0;
  895. if(!data->conn && data->set.connect_only) {
  896. result = Curl_connect_only_attach(data);
  897. if(result)
  898. return result;
  899. }
  900. if(!data->conn) {
  901. failf(data, "No associated connection");
  902. return CURLE_SEND_ERROR;
  903. }
  904. if(!data->conn->proto.ws) {
  905. failf(data, "Not a websocket transfer");
  906. return CURLE_SEND_ERROR;
  907. }
  908. ws = data->conn->proto.ws;
  909. if(data->set.ws_raw_mode) {
  910. if(fragsize || flags)
  911. return CURLE_BAD_FUNCTION_ARGUMENT;
  912. if(!buflen)
  913. /* nothing to do */
  914. return CURLE_OK;
  915. /* raw mode sends exactly what was requested, and this is from within
  916. the write callback */
  917. if(Curl_is_in_callback(data)) {
  918. result = Curl_write(data, data->conn->writesockfd, buffer, buflen,
  919. &nwritten);
  920. }
  921. else
  922. result = Curl_senddata(data, buffer, buflen, &nwritten);
  923. infof(data, "WS: wanted to send %zu bytes, sent %zu bytes",
  924. buflen, nwritten);
  925. *sent = (nwritten >= 0)? (size_t)nwritten : 0;
  926. return result;
  927. }
  928. /* Not RAW mode, buf we do the frame encoding */
  929. result = ws_flush(data, ws, FALSE);
  930. if(result)
  931. return result;
  932. /* TODO: the current design does not allow partial writes, afaict.
  933. * It is not clear who the application is supposed to react. */
  934. space = Curl_bufq_space(&ws->sendbuf);
  935. DEBUGF(infof(data, "curl_ws_send(len=%zu), sendbuf len=%zu space %zu",
  936. buflen, Curl_bufq_len(&ws->sendbuf), space));
  937. if(space < 14)
  938. return CURLE_AGAIN;
  939. if(flags & CURLWS_OFFSET) {
  940. if(fragsize) {
  941. /* a frame series 'fragsize' bytes big, this is the first */
  942. n = ws_enc_write_head(data, &ws->enc, flags, fragsize,
  943. &ws->sendbuf, &result);
  944. if(n < 0)
  945. return result;
  946. }
  947. else {
  948. if((curl_off_t)buflen > ws->enc.payload_remain) {
  949. infof(data, "WS: unaligned frame size (sending %zu instead of %"
  950. CURL_FORMAT_CURL_OFF_T ")",
  951. buflen, ws->enc.payload_remain);
  952. }
  953. }
  954. }
  955. else if(!ws->enc.payload_remain) {
  956. n = ws_enc_write_head(data, &ws->enc, flags, (curl_off_t)buflen,
  957. &ws->sendbuf, &result);
  958. if(n < 0)
  959. return result;
  960. }
  961. n = ws_enc_write_payload(&ws->enc, data,
  962. buffer, buflen, &ws->sendbuf, &result);
  963. if(n < 0)
  964. return result;
  965. *sent = (size_t)n;
  966. return ws_flush(data, ws, TRUE);
  967. }
  968. static void ws_free(struct connectdata *conn)
  969. {
  970. if(conn && conn->proto.ws) {
  971. Curl_bufq_free(&conn->proto.ws->recvbuf);
  972. Curl_bufq_free(&conn->proto.ws->sendbuf);
  973. Curl_safefree(conn->proto.ws);
  974. }
  975. }
  976. void Curl_ws_done(struct Curl_easy *data)
  977. {
  978. (void)data;
  979. }
  980. CURLcode Curl_ws_disconnect(struct Curl_easy *data,
  981. struct connectdata *conn,
  982. bool dead_connection)
  983. {
  984. (void)data;
  985. (void)dead_connection;
  986. ws_free(conn);
  987. return CURLE_OK;
  988. }
  989. CURL_EXTERN const struct curl_ws_frame *curl_ws_meta(struct Curl_easy *data)
  990. {
  991. /* we only return something for websocket, called from within the callback
  992. when not using raw mode */
  993. if(GOOD_EASY_HANDLE(data) && Curl_is_in_callback(data) && data->conn &&
  994. data->conn->proto.ws && !data->set.ws_raw_mode)
  995. return &data->conn->proto.ws->frame;
  996. return NULL;
  997. }
  998. #else
  999. CURL_EXTERN CURLcode curl_ws_recv(CURL *curl, void *buffer, size_t buflen,
  1000. size_t *nread,
  1001. const struct curl_ws_frame **metap)
  1002. {
  1003. (void)curl;
  1004. (void)buffer;
  1005. (void)buflen;
  1006. (void)nread;
  1007. (void)metap;
  1008. return CURLE_NOT_BUILT_IN;
  1009. }
  1010. CURL_EXTERN CURLcode curl_ws_send(CURL *curl, const void *buffer,
  1011. size_t buflen, size_t *sent,
  1012. curl_off_t fragsize,
  1013. unsigned int flags)
  1014. {
  1015. (void)curl;
  1016. (void)buffer;
  1017. (void)buflen;
  1018. (void)sent;
  1019. (void)fragsize;
  1020. (void)flags;
  1021. return CURLE_NOT_BUILT_IN;
  1022. }
  1023. CURL_EXTERN const struct curl_ws_frame *curl_ws_meta(struct Curl_easy *data)
  1024. {
  1025. (void)data;
  1026. return NULL;
  1027. }
  1028. #endif /* USE_WEBSOCKETS */