ws.c 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393
  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. #if !defined(CURL_DISABLE_WEBSOCKETS) && !defined(CURL_DISABLE_HTTP)
  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 "select.h"
  39. #include "nonblock.h"
  40. /* The last 3 #include files should be in this order */
  41. #include "curl_printf.h"
  42. #include "curl_memory.h"
  43. #include "memdebug.h"
  44. #define WSBIT_FIN 0x80
  45. #define WSBIT_OPCODE_CONT 0
  46. #define WSBIT_OPCODE_TEXT (1)
  47. #define WSBIT_OPCODE_BIN (2)
  48. #define WSBIT_OPCODE_CLOSE (8)
  49. #define WSBIT_OPCODE_PING (9)
  50. #define WSBIT_OPCODE_PONG (0xa)
  51. #define WSBIT_OPCODE_MASK (0xf)
  52. #define WSBIT_MASK 0x80
  53. /* buffer dimensioning */
  54. #define WS_CHUNK_SIZE 65535
  55. #define WS_CHUNK_COUNT 2
  56. struct ws_frame_meta {
  57. char proto_opcode;
  58. int flags;
  59. const char *name;
  60. };
  61. static struct ws_frame_meta WS_FRAMES[] = {
  62. { WSBIT_OPCODE_CONT, CURLWS_CONT, "CONT" },
  63. { WSBIT_OPCODE_TEXT, CURLWS_TEXT, "TEXT" },
  64. { WSBIT_OPCODE_BIN, CURLWS_BINARY, "BIN" },
  65. { WSBIT_OPCODE_CLOSE, CURLWS_CLOSE, "CLOSE" },
  66. { WSBIT_OPCODE_PING, CURLWS_PING, "PING" },
  67. { WSBIT_OPCODE_PONG, CURLWS_PONG, "PONG" },
  68. };
  69. static const char *ws_frame_name_of_op(unsigned char proto_opcode)
  70. {
  71. unsigned char opcode = proto_opcode & WSBIT_OPCODE_MASK;
  72. size_t i;
  73. for(i = 0; i < sizeof(WS_FRAMES)/sizeof(WS_FRAMES[0]); ++i) {
  74. if(WS_FRAMES[i].proto_opcode == opcode)
  75. return WS_FRAMES[i].name;
  76. }
  77. return "???";
  78. }
  79. static int ws_frame_op2flags(unsigned char proto_opcode)
  80. {
  81. unsigned char opcode = proto_opcode & WSBIT_OPCODE_MASK;
  82. size_t i;
  83. for(i = 0; i < sizeof(WS_FRAMES)/sizeof(WS_FRAMES[0]); ++i) {
  84. if(WS_FRAMES[i].proto_opcode == opcode)
  85. return WS_FRAMES[i].flags;
  86. }
  87. return 0;
  88. }
  89. static unsigned char ws_frame_flags2op(int flags)
  90. {
  91. size_t i;
  92. for(i = 0; i < sizeof(WS_FRAMES)/sizeof(WS_FRAMES[0]); ++i) {
  93. if(WS_FRAMES[i].flags & flags)
  94. return (unsigned char)WS_FRAMES[i].proto_opcode;
  95. }
  96. return 0;
  97. }
  98. static void ws_dec_info(struct ws_decoder *dec, struct Curl_easy *data,
  99. const char *msg)
  100. {
  101. switch(dec->head_len) {
  102. case 0:
  103. break;
  104. case 1:
  105. CURL_TRC_WRITE(data, "websocket, decoded %s [%s%s]", msg,
  106. ws_frame_name_of_op(dec->head[0]),
  107. (dec->head[0] & WSBIT_FIN) ? "" : " NON-FINAL");
  108. break;
  109. default:
  110. if(dec->head_len < dec->head_total) {
  111. CURL_TRC_WRITE(data, "websocket, decoded %s [%s%s](%d/%d)", msg,
  112. ws_frame_name_of_op(dec->head[0]),
  113. (dec->head[0] & WSBIT_FIN) ? "" : " NON-FINAL",
  114. dec->head_len, dec->head_total);
  115. }
  116. else {
  117. CURL_TRC_WRITE(data, "websocket, decoded %s [%s%s payload=%"
  118. FMT_OFF_T "/%" FMT_OFF_T "]",
  119. msg, ws_frame_name_of_op(dec->head[0]),
  120. (dec->head[0] & WSBIT_FIN) ? "" : " NON-FINAL",
  121. dec->payload_offset, dec->payload_len);
  122. }
  123. break;
  124. }
  125. }
  126. static CURLcode ws_send_raw_blocking(CURL *data, struct websocket *ws,
  127. const char *buffer, size_t buflen);
  128. typedef ssize_t ws_write_payload(const unsigned char *buf, size_t buflen,
  129. int frame_age, int frame_flags,
  130. curl_off_t payload_offset,
  131. curl_off_t payload_len,
  132. void *userp,
  133. CURLcode *err);
  134. static void ws_dec_reset(struct ws_decoder *dec)
  135. {
  136. dec->frame_age = 0;
  137. dec->frame_flags = 0;
  138. dec->payload_offset = 0;
  139. dec->payload_len = 0;
  140. dec->head_len = dec->head_total = 0;
  141. dec->state = WS_DEC_INIT;
  142. }
  143. static void ws_dec_init(struct ws_decoder *dec)
  144. {
  145. ws_dec_reset(dec);
  146. }
  147. static CURLcode ws_dec_read_head(struct ws_decoder *dec,
  148. struct Curl_easy *data,
  149. struct bufq *inraw)
  150. {
  151. const unsigned char *inbuf;
  152. size_t inlen;
  153. while(Curl_bufq_peek(inraw, &inbuf, &inlen)) {
  154. if(dec->head_len == 0) {
  155. dec->head[0] = *inbuf;
  156. Curl_bufq_skip(inraw, 1);
  157. dec->frame_flags = ws_frame_op2flags(dec->head[0]);
  158. if(!dec->frame_flags) {
  159. failf(data, "WS: unknown opcode: %x", dec->head[0]);
  160. ws_dec_reset(dec);
  161. return CURLE_RECV_ERROR;
  162. }
  163. dec->head_len = 1;
  164. /* ws_dec_info(dec, data, "seeing opcode"); */
  165. continue;
  166. }
  167. else if(dec->head_len == 1) {
  168. dec->head[1] = *inbuf;
  169. Curl_bufq_skip(inraw, 1);
  170. dec->head_len = 2;
  171. if(dec->head[1] & WSBIT_MASK) {
  172. /* A client MUST close a connection if it detects a masked frame. */
  173. failf(data, "WS: masked input frame");
  174. ws_dec_reset(dec);
  175. return CURLE_RECV_ERROR;
  176. }
  177. /* How long is the frame head? */
  178. if(dec->head[1] == 126) {
  179. dec->head_total = 4;
  180. continue;
  181. }
  182. else if(dec->head[1] == 127) {
  183. dec->head_total = 10;
  184. continue;
  185. }
  186. else {
  187. dec->head_total = 2;
  188. }
  189. }
  190. if(dec->head_len < dec->head_total) {
  191. dec->head[dec->head_len] = *inbuf;
  192. Curl_bufq_skip(inraw, 1);
  193. ++dec->head_len;
  194. if(dec->head_len < dec->head_total) {
  195. /* ws_dec_info(dec, data, "decoding head"); */
  196. continue;
  197. }
  198. }
  199. /* got the complete frame head */
  200. DEBUGASSERT(dec->head_len == dec->head_total);
  201. switch(dec->head_total) {
  202. case 2:
  203. dec->payload_len = dec->head[1];
  204. break;
  205. case 4:
  206. dec->payload_len = (dec->head[2] << 8) | dec->head[3];
  207. break;
  208. case 10:
  209. if(dec->head[2] > 127) {
  210. failf(data, "WS: frame length longer than 64 signed not supported");
  211. return CURLE_RECV_ERROR;
  212. }
  213. dec->payload_len = ((curl_off_t)dec->head[2] << 56) |
  214. (curl_off_t)dec->head[3] << 48 |
  215. (curl_off_t)dec->head[4] << 40 |
  216. (curl_off_t)dec->head[5] << 32 |
  217. (curl_off_t)dec->head[6] << 24 |
  218. (curl_off_t)dec->head[7] << 16 |
  219. (curl_off_t)dec->head[8] << 8 |
  220. dec->head[9];
  221. break;
  222. default:
  223. /* this should never happen */
  224. DEBUGASSERT(0);
  225. failf(data, "WS: unexpected frame header length");
  226. return CURLE_RECV_ERROR;
  227. }
  228. dec->frame_age = 0;
  229. dec->payload_offset = 0;
  230. ws_dec_info(dec, data, "decoded");
  231. return CURLE_OK;
  232. }
  233. return CURLE_AGAIN;
  234. }
  235. static CURLcode ws_dec_pass_payload(struct ws_decoder *dec,
  236. struct Curl_easy *data,
  237. struct bufq *inraw,
  238. ws_write_payload *write_payload,
  239. void *write_ctx)
  240. {
  241. const unsigned char *inbuf;
  242. size_t inlen;
  243. ssize_t nwritten;
  244. CURLcode result;
  245. curl_off_t remain = dec->payload_len - dec->payload_offset;
  246. (void)data;
  247. while(remain && Curl_bufq_peek(inraw, &inbuf, &inlen)) {
  248. if((curl_off_t)inlen > remain)
  249. inlen = (size_t)remain;
  250. nwritten = write_payload(inbuf, inlen, dec->frame_age, dec->frame_flags,
  251. dec->payload_offset, dec->payload_len,
  252. write_ctx, &result);
  253. if(nwritten < 0)
  254. return result;
  255. Curl_bufq_skip(inraw, (size_t)nwritten);
  256. dec->payload_offset += (curl_off_t)nwritten;
  257. remain = dec->payload_len - dec->payload_offset;
  258. CURL_TRC_WRITE(data, "websocket, passed %zd bytes payload, %"
  259. FMT_OFF_T " remain", nwritten, remain);
  260. }
  261. return remain ? CURLE_AGAIN : CURLE_OK;
  262. }
  263. static CURLcode ws_dec_pass(struct ws_decoder *dec,
  264. struct Curl_easy *data,
  265. struct bufq *inraw,
  266. ws_write_payload *write_payload,
  267. void *write_ctx)
  268. {
  269. CURLcode result;
  270. if(Curl_bufq_is_empty(inraw))
  271. return CURLE_AGAIN;
  272. switch(dec->state) {
  273. case WS_DEC_INIT:
  274. ws_dec_reset(dec);
  275. dec->state = WS_DEC_HEAD;
  276. FALLTHROUGH();
  277. case WS_DEC_HEAD:
  278. result = ws_dec_read_head(dec, data, inraw);
  279. if(result) {
  280. if(result != CURLE_AGAIN) {
  281. infof(data, "WS: decode error %d", (int)result);
  282. break; /* real error */
  283. }
  284. /* incomplete ws frame head */
  285. DEBUGASSERT(Curl_bufq_is_empty(inraw));
  286. break;
  287. }
  288. /* head parsing done */
  289. dec->state = WS_DEC_PAYLOAD;
  290. if(dec->payload_len == 0) {
  291. ssize_t nwritten;
  292. const unsigned char tmp = '\0';
  293. /* special case of a 0 length frame, need to write once */
  294. nwritten = write_payload(&tmp, 0, dec->frame_age, dec->frame_flags,
  295. 0, 0, write_ctx, &result);
  296. if(nwritten < 0)
  297. return result;
  298. dec->state = WS_DEC_INIT;
  299. break;
  300. }
  301. FALLTHROUGH();
  302. case WS_DEC_PAYLOAD:
  303. result = ws_dec_pass_payload(dec, data, inraw, write_payload, write_ctx);
  304. ws_dec_info(dec, data, "passing");
  305. if(result)
  306. return result;
  307. /* paylod parsing done */
  308. dec->state = WS_DEC_INIT;
  309. break;
  310. default:
  311. /* we covered all enums above, but some code analyzers are whimps */
  312. result = CURLE_FAILED_INIT;
  313. }
  314. return result;
  315. }
  316. static void update_meta(struct websocket *ws,
  317. int frame_age, int frame_flags,
  318. curl_off_t payload_offset,
  319. curl_off_t payload_len,
  320. size_t cur_len)
  321. {
  322. ws->frame.age = frame_age;
  323. ws->frame.flags = frame_flags;
  324. ws->frame.offset = payload_offset;
  325. ws->frame.len = cur_len;
  326. ws->frame.bytesleft = (payload_len - payload_offset - cur_len);
  327. }
  328. /* WebSockets decoding client writer */
  329. struct ws_cw_ctx {
  330. struct Curl_cwriter super;
  331. struct bufq buf;
  332. };
  333. static CURLcode ws_cw_init(struct Curl_easy *data,
  334. struct Curl_cwriter *writer)
  335. {
  336. struct ws_cw_ctx *ctx = writer->ctx;
  337. (void)data;
  338. Curl_bufq_init2(&ctx->buf, WS_CHUNK_SIZE, 1, BUFQ_OPT_SOFT_LIMIT);
  339. return CURLE_OK;
  340. }
  341. static void ws_cw_close(struct Curl_easy *data, struct Curl_cwriter *writer)
  342. {
  343. struct ws_cw_ctx *ctx = writer->ctx;
  344. (void) data;
  345. Curl_bufq_free(&ctx->buf);
  346. }
  347. struct ws_cw_dec_ctx {
  348. struct Curl_easy *data;
  349. struct websocket *ws;
  350. struct Curl_cwriter *next_writer;
  351. int cw_type;
  352. };
  353. static ssize_t ws_cw_dec_next(const unsigned char *buf, size_t buflen,
  354. int frame_age, int frame_flags,
  355. curl_off_t payload_offset,
  356. curl_off_t payload_len,
  357. void *user_data,
  358. CURLcode *err)
  359. {
  360. struct ws_cw_dec_ctx *ctx = user_data;
  361. struct Curl_easy *data = ctx->data;
  362. struct websocket *ws = ctx->ws;
  363. curl_off_t remain = (payload_len - (payload_offset + buflen));
  364. (void)frame_age;
  365. if((frame_flags & CURLWS_PING) && !remain) {
  366. /* auto-respond to PINGs, only works for single-frame payloads atm */
  367. size_t bytes;
  368. infof(data, "WS: auto-respond to PING with a PONG");
  369. /* send back the exact same content as a PONG */
  370. *err = curl_ws_send(data, buf, buflen, &bytes, 0, CURLWS_PONG);
  371. if(*err)
  372. return -1;
  373. }
  374. else if(buflen || !remain) {
  375. /* forward the decoded frame to the next client writer. */
  376. update_meta(ws, frame_age, frame_flags, payload_offset,
  377. payload_len, buflen);
  378. *err = Curl_cwriter_write(data, ctx->next_writer, ctx->cw_type,
  379. (const char *)buf, buflen);
  380. if(*err)
  381. return -1;
  382. }
  383. *err = CURLE_OK;
  384. return (ssize_t)buflen;
  385. }
  386. static CURLcode ws_cw_write(struct Curl_easy *data,
  387. struct Curl_cwriter *writer, int type,
  388. const char *buf, size_t nbytes)
  389. {
  390. struct ws_cw_ctx *ctx = writer->ctx;
  391. struct websocket *ws;
  392. CURLcode result;
  393. if(!(type & CLIENTWRITE_BODY) || data->set.ws_raw_mode)
  394. return Curl_cwriter_write(data, writer->next, type, buf, nbytes);
  395. ws = data->conn->proto.ws;
  396. if(!ws) {
  397. failf(data, "WS: not a websocket transfer");
  398. return CURLE_FAILED_INIT;
  399. }
  400. if(nbytes) {
  401. ssize_t nwritten;
  402. nwritten = Curl_bufq_write(&ctx->buf, (const unsigned char *)buf,
  403. nbytes, &result);
  404. if(nwritten < 0) {
  405. infof(data, "WS: error adding data to buffer %d", result);
  406. return result;
  407. }
  408. }
  409. while(!Curl_bufq_is_empty(&ctx->buf)) {
  410. struct ws_cw_dec_ctx pass_ctx;
  411. pass_ctx.data = data;
  412. pass_ctx.ws = ws;
  413. pass_ctx.next_writer = writer->next;
  414. pass_ctx.cw_type = type;
  415. result = ws_dec_pass(&ws->dec, data, &ctx->buf,
  416. ws_cw_dec_next, &pass_ctx);
  417. if(result == CURLE_AGAIN) {
  418. /* insufficient amount of data, keep it for later.
  419. * we pretend to have written all since we have a copy */
  420. CURL_TRC_WRITE(data, "websocket, buffered incomplete frame head");
  421. return CURLE_OK;
  422. }
  423. else if(result) {
  424. infof(data, "WS: decode error %d", (int)result);
  425. return result;
  426. }
  427. }
  428. if((type & CLIENTWRITE_EOS) && !Curl_bufq_is_empty(&ctx->buf)) {
  429. infof(data, "WS: decode ending with %zd frame bytes remaining",
  430. Curl_bufq_len(&ctx->buf));
  431. return CURLE_RECV_ERROR;
  432. }
  433. return CURLE_OK;
  434. }
  435. /* WebSocket payload decoding client writer. */
  436. static const struct Curl_cwtype ws_cw_decode = {
  437. "ws-decode",
  438. NULL,
  439. ws_cw_init,
  440. ws_cw_write,
  441. ws_cw_close,
  442. sizeof(struct ws_cw_ctx)
  443. };
  444. static void ws_enc_info(struct ws_encoder *enc, struct Curl_easy *data,
  445. const char *msg)
  446. {
  447. infof(data, "WS-ENC: %s [%s%s%s payload=%" FMT_OFF_T "/%" FMT_OFF_T "]",
  448. msg, ws_frame_name_of_op(enc->firstbyte),
  449. (enc->firstbyte & WSBIT_OPCODE_MASK) == WSBIT_OPCODE_CONT ?
  450. " CONT" : "",
  451. (enc->firstbyte & WSBIT_FIN) ? "" : " NON-FIN",
  452. enc->payload_len - enc->payload_remain, enc->payload_len);
  453. }
  454. static void ws_enc_reset(struct ws_encoder *enc)
  455. {
  456. enc->payload_remain = 0;
  457. enc->xori = 0;
  458. enc->contfragment = FALSE;
  459. }
  460. static void ws_enc_init(struct ws_encoder *enc)
  461. {
  462. ws_enc_reset(enc);
  463. }
  464. /***
  465. RFC 6455 Section 5.2
  466. 0 1 2 3
  467. 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
  468. +-+-+-+-+-------+-+-------------+-------------------------------+
  469. |F|R|R|R| opcode|M| Payload len | Extended payload length |
  470. |I|S|S|S| (4) |A| (7) | (16/64) |
  471. |N|V|V|V| |S| | (if payload len==126/127) |
  472. | |1|2|3| |K| | |
  473. +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
  474. | Extended payload length continued, if payload len == 127 |
  475. + - - - - - - - - - - - - - - - +-------------------------------+
  476. | |Masking-key, if MASK set to 1 |
  477. +-------------------------------+-------------------------------+
  478. | Masking-key (continued) | Payload Data |
  479. +-------------------------------- - - - - - - - - - - - - - - - +
  480. : Payload Data continued ... :
  481. + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
  482. | Payload Data continued ... |
  483. +---------------------------------------------------------------+
  484. */
  485. static ssize_t ws_enc_write_head(struct Curl_easy *data,
  486. struct ws_encoder *enc,
  487. unsigned int flags,
  488. curl_off_t payload_len,
  489. struct bufq *out,
  490. CURLcode *err)
  491. {
  492. unsigned char firstbyte = 0;
  493. unsigned char opcode;
  494. unsigned char head[14];
  495. size_t hlen;
  496. ssize_t n;
  497. if(payload_len < 0) {
  498. failf(data, "WS: starting new frame with negative payload length %"
  499. FMT_OFF_T, payload_len);
  500. *err = CURLE_SEND_ERROR;
  501. return -1;
  502. }
  503. if(enc->payload_remain > 0) {
  504. /* trying to write a new frame before the previous one is finished */
  505. failf(data, "WS: starting new frame with %zd bytes from last one "
  506. "remaining to be sent", (ssize_t)enc->payload_remain);
  507. *err = CURLE_SEND_ERROR;
  508. return -1;
  509. }
  510. opcode = ws_frame_flags2op((int)flags & ~CURLWS_CONT);
  511. if(!opcode) {
  512. failf(data, "WS: provided flags not recognized '%x'", flags);
  513. *err = CURLE_SEND_ERROR;
  514. return -1;
  515. }
  516. if(!(flags & CURLWS_CONT)) {
  517. if(!enc->contfragment)
  518. /* not marked as continuing, this is the final fragment */
  519. firstbyte |= WSBIT_FIN | opcode;
  520. else
  521. /* marked as continuing, this is the final fragment; set CONT
  522. opcode and FIN bit */
  523. firstbyte |= WSBIT_FIN | WSBIT_OPCODE_CONT;
  524. enc->contfragment = FALSE;
  525. }
  526. else if(enc->contfragment) {
  527. /* the previous fragment was not a final one and this is not either, keep a
  528. CONT opcode and no FIN bit */
  529. firstbyte |= WSBIT_OPCODE_CONT;
  530. }
  531. else {
  532. firstbyte = opcode;
  533. enc->contfragment = TRUE;
  534. }
  535. head[0] = enc->firstbyte = firstbyte;
  536. if(payload_len > 65535) {
  537. head[1] = 127 | WSBIT_MASK;
  538. head[2] = (unsigned char)((payload_len >> 56) & 0xff);
  539. head[3] = (unsigned char)((payload_len >> 48) & 0xff);
  540. head[4] = (unsigned char)((payload_len >> 40) & 0xff);
  541. head[5] = (unsigned char)((payload_len >> 32) & 0xff);
  542. head[6] = (unsigned char)((payload_len >> 24) & 0xff);
  543. head[7] = (unsigned char)((payload_len >> 16) & 0xff);
  544. head[8] = (unsigned char)((payload_len >> 8) & 0xff);
  545. head[9] = (unsigned char)(payload_len & 0xff);
  546. hlen = 10;
  547. }
  548. else if(payload_len >= 126) {
  549. head[1] = 126 | WSBIT_MASK;
  550. head[2] = (unsigned char)((payload_len >> 8) & 0xff);
  551. head[3] = (unsigned char)(payload_len & 0xff);
  552. hlen = 4;
  553. }
  554. else {
  555. head[1] = (unsigned char)payload_len | WSBIT_MASK;
  556. hlen = 2;
  557. }
  558. enc->payload_remain = enc->payload_len = payload_len;
  559. ws_enc_info(enc, data, "sending");
  560. /* add 4 bytes mask */
  561. memcpy(&head[hlen], &enc->mask, 4);
  562. hlen += 4;
  563. /* reset for payload to come */
  564. enc->xori = 0;
  565. n = Curl_bufq_write(out, head, hlen, err);
  566. if(n < 0)
  567. return -1;
  568. if((size_t)n != hlen) {
  569. /* We use a bufq with SOFT_LIMIT, writing should always succeed */
  570. DEBUGASSERT(0);
  571. *err = CURLE_SEND_ERROR;
  572. return -1;
  573. }
  574. return n;
  575. }
  576. static ssize_t ws_enc_write_payload(struct ws_encoder *enc,
  577. struct Curl_easy *data,
  578. const unsigned char *buf, size_t buflen,
  579. struct bufq *out, CURLcode *err)
  580. {
  581. ssize_t n;
  582. size_t i, len;
  583. if(Curl_bufq_is_full(out)) {
  584. *err = CURLE_AGAIN;
  585. return -1;
  586. }
  587. /* not the most performant way to do this */
  588. len = buflen;
  589. if((curl_off_t)len > enc->payload_remain)
  590. len = (size_t)enc->payload_remain;
  591. for(i = 0; i < len; ++i) {
  592. unsigned char c = buf[i] ^ enc->mask[enc->xori];
  593. n = Curl_bufq_write(out, &c, 1, err);
  594. if(n < 0) {
  595. if((*err != CURLE_AGAIN) || !i)
  596. return -1;
  597. break;
  598. }
  599. enc->xori++;
  600. enc->xori &= 3;
  601. }
  602. enc->payload_remain -= (curl_off_t)i;
  603. ws_enc_info(enc, data, "buffered");
  604. return (ssize_t)i;
  605. }
  606. struct wsfield {
  607. const char *name;
  608. const char *val;
  609. };
  610. CURLcode Curl_ws_request(struct Curl_easy *data, REQTYPE *req)
  611. {
  612. unsigned int i;
  613. CURLcode result = CURLE_OK;
  614. unsigned char rand[16];
  615. char *randstr;
  616. size_t randlen;
  617. char keyval[40];
  618. struct SingleRequest *k = &data->req;
  619. struct wsfield heads[]= {
  620. {
  621. /* The request MUST contain an |Upgrade| header field whose value
  622. MUST include the "websocket" keyword. */
  623. "Upgrade:", "websocket"
  624. },
  625. {
  626. /* The request MUST contain a |Connection| header field whose value
  627. MUST include the "Upgrade" token. */
  628. "Connection:", "Upgrade",
  629. },
  630. {
  631. /* The request MUST include a header field with the name
  632. |Sec-WebSocket-Version|. The value of this header field MUST be
  633. 13. */
  634. "Sec-WebSocket-Version:", "13",
  635. },
  636. {
  637. /* The request MUST include a header field with the name
  638. |Sec-WebSocket-Key|. The value of this header field MUST be a nonce
  639. consisting of a randomly selected 16-byte value that has been
  640. base64-encoded (see Section 4 of [RFC4648]). The nonce MUST be
  641. selected randomly for each connection. */
  642. "Sec-WebSocket-Key:", NULL,
  643. }
  644. };
  645. heads[3].val = &keyval[0];
  646. /* 16 bytes random */
  647. result = Curl_rand(data, (unsigned char *)rand, sizeof(rand));
  648. if(result)
  649. return result;
  650. result = Curl_base64_encode((char *)rand, sizeof(rand), &randstr, &randlen);
  651. if(result)
  652. return result;
  653. DEBUGASSERT(randlen < sizeof(keyval));
  654. if(randlen >= sizeof(keyval)) {
  655. free(randstr);
  656. return CURLE_FAILED_INIT;
  657. }
  658. strcpy(keyval, randstr);
  659. free(randstr);
  660. for(i = 0; !result && (i < sizeof(heads)/sizeof(heads[0])); i++) {
  661. if(!Curl_checkheaders(data, STRCONST(heads[i].name))) {
  662. #ifdef USE_HYPER
  663. char field[128];
  664. msnprintf(field, sizeof(field), "%s %s", heads[i].name,
  665. heads[i].val);
  666. result = Curl_hyper_header(data, req, field);
  667. #else
  668. (void)data;
  669. result = Curl_dyn_addf(req, "%s %s\r\n", heads[i].name,
  670. heads[i].val);
  671. #endif
  672. }
  673. }
  674. k->upgr101 = UPGR101_WS;
  675. return result;
  676. }
  677. /*
  678. * 'nread' is number of bytes of websocket data already in the buffer at
  679. * 'mem'.
  680. */
  681. CURLcode Curl_ws_accept(struct Curl_easy *data,
  682. const char *mem, size_t nread)
  683. {
  684. struct SingleRequest *k = &data->req;
  685. struct websocket *ws;
  686. struct Curl_cwriter *ws_dec_writer;
  687. CURLcode result;
  688. DEBUGASSERT(data->conn);
  689. ws = data->conn->proto.ws;
  690. if(!ws) {
  691. size_t chunk_size = WS_CHUNK_SIZE;
  692. ws = calloc(1, sizeof(*ws));
  693. if(!ws)
  694. return CURLE_OUT_OF_MEMORY;
  695. data->conn->proto.ws = ws;
  696. #ifdef DEBUGBUILD
  697. {
  698. char *p = getenv("CURL_WS_CHUNK_SIZE");
  699. if(p) {
  700. long l = strtol(p, NULL, 10);
  701. if(l > 0 && l <= (1*1024*1024)) {
  702. chunk_size = (size_t)l;
  703. }
  704. }
  705. }
  706. #endif
  707. CURL_TRC_WS(data, "WS, using chunk size %zu", chunk_size);
  708. Curl_bufq_init2(&ws->recvbuf, chunk_size, WS_CHUNK_COUNT,
  709. BUFQ_OPT_SOFT_LIMIT);
  710. Curl_bufq_init2(&ws->sendbuf, chunk_size, WS_CHUNK_COUNT,
  711. BUFQ_OPT_SOFT_LIMIT);
  712. ws_dec_init(&ws->dec);
  713. ws_enc_init(&ws->enc);
  714. }
  715. else {
  716. Curl_bufq_reset(&ws->recvbuf);
  717. ws_dec_reset(&ws->dec);
  718. ws_enc_reset(&ws->enc);
  719. }
  720. /* Verify the Sec-WebSocket-Accept response.
  721. The sent value is the base64 encoded version of a SHA-1 hash done on the
  722. |Sec-WebSocket-Key| header field concatenated with
  723. the string "258EAFA5-E914-47DA-95CA-C5AB0DC85B11".
  724. */
  725. /* If the response includes a |Sec-WebSocket-Extensions| header field and
  726. this header field indicates the use of an extension that was not present
  727. in the client's handshake (the server has indicated an extension not
  728. requested by the client), the client MUST Fail the WebSocket Connection.
  729. */
  730. /* If the response includes a |Sec-WebSocket-Protocol| header field
  731. and this header field indicates the use of a subprotocol that was
  732. not present in the client's handshake (the server has indicated a
  733. subprotocol not requested by the client), the client MUST Fail
  734. the WebSocket Connection. */
  735. /* 4 bytes random */
  736. result = Curl_rand(data, (unsigned char *)&ws->enc.mask,
  737. sizeof(ws->enc.mask));
  738. if(result)
  739. return result;
  740. infof(data, "Received 101, switch to WebSocket; mask %02x%02x%02x%02x",
  741. ws->enc.mask[0], ws->enc.mask[1], ws->enc.mask[2], ws->enc.mask[3]);
  742. /* Install our client writer that decodes WS frames payload */
  743. result = Curl_cwriter_create(&ws_dec_writer, data, &ws_cw_decode,
  744. CURL_CW_CONTENT_DECODE);
  745. if(result)
  746. return result;
  747. result = Curl_cwriter_add(data, ws_dec_writer);
  748. if(result) {
  749. Curl_cwriter_free(data, ws_dec_writer);
  750. return result;
  751. }
  752. if(data->set.connect_only) {
  753. ssize_t nwritten;
  754. /* In CONNECT_ONLY setup, the payloads from `mem` need to be received
  755. * when using `curl_ws_recv` later on after this transfer is already
  756. * marked as DONE. */
  757. nwritten = Curl_bufq_write(&ws->recvbuf, (const unsigned char *)mem,
  758. nread, &result);
  759. if(nwritten < 0)
  760. return result;
  761. infof(data, "%zu bytes websocket payload", nread);
  762. }
  763. else { /* !connect_only */
  764. /* And pass any additional data to the writers */
  765. if(nread) {
  766. result = Curl_client_write(data, CLIENTWRITE_BODY, (char *)mem, nread);
  767. }
  768. }
  769. k->upgr101 = UPGR101_RECEIVED;
  770. return result;
  771. }
  772. struct ws_collect {
  773. struct Curl_easy *data;
  774. unsigned char *buffer;
  775. size_t buflen;
  776. size_t bufidx;
  777. int frame_age;
  778. int frame_flags;
  779. curl_off_t payload_offset;
  780. curl_off_t payload_len;
  781. bool written;
  782. };
  783. static ssize_t ws_client_collect(const unsigned char *buf, size_t buflen,
  784. int frame_age, int frame_flags,
  785. curl_off_t payload_offset,
  786. curl_off_t payload_len,
  787. void *userp,
  788. CURLcode *err)
  789. {
  790. struct ws_collect *ctx = userp;
  791. size_t nwritten;
  792. curl_off_t remain = (payload_len - (payload_offset + buflen));
  793. if(!ctx->bufidx) {
  794. /* first write */
  795. ctx->frame_age = frame_age;
  796. ctx->frame_flags = frame_flags;
  797. ctx->payload_offset = payload_offset;
  798. ctx->payload_len = payload_len;
  799. }
  800. if((frame_flags & CURLWS_PING) && !remain) {
  801. /* auto-respond to PINGs, only works for single-frame payloads atm */
  802. size_t bytes;
  803. infof(ctx->data, "WS: auto-respond to PING with a PONG");
  804. /* send back the exact same content as a PONG */
  805. *err = curl_ws_send(ctx->data, buf, buflen, &bytes, 0, CURLWS_PONG);
  806. if(*err)
  807. return -1;
  808. nwritten = bytes;
  809. }
  810. else {
  811. ctx->written = TRUE;
  812. DEBUGASSERT(ctx->buflen >= ctx->bufidx);
  813. nwritten = CURLMIN(buflen, ctx->buflen - ctx->bufidx);
  814. if(!nwritten) {
  815. if(!buflen) { /* 0 length write, we accept that */
  816. *err = CURLE_OK;
  817. return 0;
  818. }
  819. *err = CURLE_AGAIN; /* no more space */
  820. return -1;
  821. }
  822. *err = CURLE_OK;
  823. memcpy(ctx->buffer + ctx->bufidx, buf, nwritten);
  824. ctx->bufidx += nwritten;
  825. }
  826. return nwritten;
  827. }
  828. static ssize_t nw_in_recv(void *reader_ctx,
  829. unsigned char *buf, size_t buflen,
  830. CURLcode *err)
  831. {
  832. struct Curl_easy *data = reader_ctx;
  833. size_t nread;
  834. *err = curl_easy_recv(data, buf, buflen, &nread);
  835. if(*err)
  836. return -1;
  837. return (ssize_t)nread;
  838. }
  839. CURL_EXTERN CURLcode curl_ws_recv(CURL *d, void *buffer,
  840. size_t buflen, size_t *nread,
  841. const struct curl_ws_frame **metap)
  842. {
  843. struct Curl_easy *data = d;
  844. struct connectdata *conn = data->conn;
  845. struct websocket *ws;
  846. struct ws_collect ctx;
  847. *nread = 0;
  848. *metap = NULL;
  849. if(!conn) {
  850. /* Unhappy hack with lifetimes of transfers and connection */
  851. if(!data->set.connect_only) {
  852. failf(data, "CONNECT_ONLY is required");
  853. return CURLE_UNSUPPORTED_PROTOCOL;
  854. }
  855. Curl_getconnectinfo(data, &conn);
  856. if(!conn) {
  857. failf(data, "connection not found");
  858. return CURLE_BAD_FUNCTION_ARGUMENT;
  859. }
  860. }
  861. ws = conn->proto.ws;
  862. if(!ws) {
  863. failf(data, "connection is not setup for websocket");
  864. return CURLE_BAD_FUNCTION_ARGUMENT;
  865. }
  866. memset(&ctx, 0, sizeof(ctx));
  867. ctx.data = data;
  868. ctx.buffer = buffer;
  869. ctx.buflen = buflen;
  870. while(1) {
  871. CURLcode result;
  872. /* receive more when our buffer is empty */
  873. if(Curl_bufq_is_empty(&ws->recvbuf)) {
  874. ssize_t n = Curl_bufq_slurp(&ws->recvbuf, nw_in_recv, data, &result);
  875. if(n < 0) {
  876. return result;
  877. }
  878. else if(n == 0) {
  879. /* connection closed */
  880. infof(data, "connection expectedly closed?");
  881. return CURLE_GOT_NOTHING;
  882. }
  883. CURL_TRC_WS(data, "curl_ws_recv, added %zu bytes from network",
  884. Curl_bufq_len(&ws->recvbuf));
  885. }
  886. result = ws_dec_pass(&ws->dec, data, &ws->recvbuf,
  887. ws_client_collect, &ctx);
  888. if(result == CURLE_AGAIN) {
  889. if(!ctx.written) {
  890. ws_dec_info(&ws->dec, data, "need more input");
  891. continue; /* nothing written, try more input */
  892. }
  893. break;
  894. }
  895. else if(result) {
  896. return result;
  897. }
  898. else if(ctx.written) {
  899. /* The decoded frame is passed back to our caller.
  900. * There are frames like PING were we auto-respond to and
  901. * that we do not return. For these `ctx.written` is not set. */
  902. break;
  903. }
  904. }
  905. /* update frame information to be passed back */
  906. update_meta(ws, ctx.frame_age, ctx.frame_flags, ctx.payload_offset,
  907. ctx.payload_len, ctx.bufidx);
  908. *metap = &ws->frame;
  909. *nread = ws->frame.len;
  910. CURL_TRC_WS(data, "curl_ws_recv(len=%zu) -> %zu bytes (frame at %"
  911. FMT_OFF_T ", %" FMT_OFF_T " left)",
  912. buflen, *nread, ws->frame.offset, ws->frame.bytesleft);
  913. return CURLE_OK;
  914. }
  915. static CURLcode ws_flush(struct Curl_easy *data, struct websocket *ws,
  916. bool blocking)
  917. {
  918. if(!Curl_bufq_is_empty(&ws->sendbuf)) {
  919. CURLcode result;
  920. const unsigned char *out;
  921. size_t outlen, n;
  922. while(Curl_bufq_peek(&ws->sendbuf, &out, &outlen)) {
  923. if(blocking) {
  924. result = ws_send_raw_blocking(data, ws, (char *)out, outlen);
  925. n = result ? 0 : outlen;
  926. }
  927. else if(data->set.connect_only || Curl_is_in_callback(data))
  928. result = Curl_senddata(data, out, outlen, &n);
  929. else {
  930. result = Curl_xfer_send(data, out, outlen, FALSE, &n);
  931. if(!result && !n && outlen)
  932. result = CURLE_AGAIN;
  933. }
  934. if(result == CURLE_AGAIN) {
  935. CURL_TRC_WS(data, "flush EAGAIN, %zu bytes remain in buffer",
  936. Curl_bufq_len(&ws->sendbuf));
  937. return result;
  938. }
  939. else if(result) {
  940. failf(data, "WS: flush, write error %d", result);
  941. return result;
  942. }
  943. else {
  944. infof(data, "WS: flushed %zu bytes", n);
  945. Curl_bufq_skip(&ws->sendbuf, n);
  946. }
  947. }
  948. }
  949. return CURLE_OK;
  950. }
  951. static CURLcode ws_send_raw_blocking(CURL *d, struct websocket *ws,
  952. const char *buffer, size_t buflen)
  953. {
  954. CURLcode result = CURLE_OK;
  955. size_t nwritten;
  956. struct Curl_easy *data = d;
  957. (void)ws;
  958. while(buflen) {
  959. result = Curl_xfer_send(data, buffer, buflen, FALSE, &nwritten);
  960. if(result)
  961. return result;
  962. DEBUGASSERT(nwritten <= buflen);
  963. buffer += nwritten;
  964. buflen -= nwritten;
  965. if(buflen) {
  966. curl_socket_t sock = data->conn->sock[FIRSTSOCKET];
  967. timediff_t left_ms;
  968. int ev;
  969. CURL_TRC_WS(data, "ws_send_raw_blocking() partial, %zu left to send",
  970. buflen);
  971. left_ms = Curl_timeleft(data, NULL, FALSE);
  972. if(left_ms < 0) {
  973. failf(data, "Timeout waiting for socket becoming writable");
  974. return CURLE_SEND_ERROR;
  975. }
  976. /* POLLOUT socket */
  977. if(sock == CURL_SOCKET_BAD)
  978. return CURLE_SEND_ERROR;
  979. ev = Curl_socket_check(CURL_SOCKET_BAD, CURL_SOCKET_BAD, sock,
  980. left_ms ? left_ms : 500);
  981. if(ev < 0) {
  982. failf(data, "Error while waiting for socket becoming writable");
  983. return CURLE_SEND_ERROR;
  984. }
  985. }
  986. }
  987. return result;
  988. }
  989. static CURLcode ws_send_raw(struct Curl_easy *data, const void *buffer,
  990. size_t buflen, size_t *pnwritten)
  991. {
  992. struct websocket *ws = data->conn->proto.ws;
  993. CURLcode result;
  994. if(!ws) {
  995. failf(data, "Not a websocket transfer");
  996. return CURLE_SEND_ERROR;
  997. }
  998. if(!buflen)
  999. return CURLE_OK;
  1000. if(Curl_is_in_callback(data)) {
  1001. /* When invoked from inside callbacks, we do a blocking send as the
  1002. * callback will probably not implement partial writes that may then
  1003. * mess up the ws framing subsequently.
  1004. * We need any pending data to be flushed before sending. */
  1005. result = ws_flush(data, ws, TRUE);
  1006. if(result)
  1007. return result;
  1008. result = ws_send_raw_blocking(data, ws, buffer, buflen);
  1009. }
  1010. else {
  1011. /* We need any pending data to be sent or EAGAIN this call. */
  1012. result = ws_flush(data, ws, FALSE);
  1013. if(result)
  1014. return result;
  1015. result = Curl_senddata(data, buffer, buflen, pnwritten);
  1016. }
  1017. CURL_TRC_WS(data, "ws_send_raw(len=%zu) -> %d, %zu",
  1018. buflen, result, *pnwritten);
  1019. return result;
  1020. }
  1021. CURL_EXTERN CURLcode curl_ws_send(CURL *d, const void *buffer,
  1022. size_t buflen, size_t *sent,
  1023. curl_off_t fragsize,
  1024. unsigned int flags)
  1025. {
  1026. struct websocket *ws;
  1027. ssize_t n;
  1028. size_t space, payload_added;
  1029. CURLcode result;
  1030. struct Curl_easy *data = d;
  1031. CURL_TRC_WS(data, "curl_ws_send(len=%zu, fragsize=%" FMT_OFF_T
  1032. ", flags=%x), raw=%d",
  1033. buflen, fragsize, flags, data->set.ws_raw_mode);
  1034. *sent = 0;
  1035. if(!data->conn && data->set.connect_only) {
  1036. result = Curl_connect_only_attach(data);
  1037. if(result)
  1038. goto out;
  1039. }
  1040. if(!data->conn) {
  1041. failf(data, "No associated connection");
  1042. result = CURLE_SEND_ERROR;
  1043. goto out;
  1044. }
  1045. if(!data->conn->proto.ws) {
  1046. failf(data, "Not a websocket transfer");
  1047. result = CURLE_SEND_ERROR;
  1048. goto out;
  1049. }
  1050. ws = data->conn->proto.ws;
  1051. /* try flushing any content still waiting to be sent. */
  1052. result = ws_flush(data, ws, FALSE);
  1053. if(result)
  1054. goto out;
  1055. if(data->set.ws_raw_mode) {
  1056. /* In raw mode, we write directly to the connection */
  1057. if(fragsize || flags) {
  1058. failf(data, "ws_send, raw mode: fragsize and flags cannot be non-zero");
  1059. return CURLE_BAD_FUNCTION_ARGUMENT;
  1060. }
  1061. result = ws_send_raw(data, buffer, buflen, sent);
  1062. goto out;
  1063. }
  1064. /* Not RAW mode, buf we do the frame encoding */
  1065. space = Curl_bufq_space(&ws->sendbuf);
  1066. CURL_TRC_WS(data, "curl_ws_send(len=%zu), sendbuf=%zu space_left=%zu",
  1067. buflen, Curl_bufq_len(&ws->sendbuf), space);
  1068. if(space < 14) {
  1069. result = CURLE_AGAIN;
  1070. goto out;
  1071. }
  1072. if(flags & CURLWS_OFFSET) {
  1073. if(fragsize) {
  1074. /* a frame series 'fragsize' bytes big, this is the first */
  1075. n = ws_enc_write_head(data, &ws->enc, flags, fragsize,
  1076. &ws->sendbuf, &result);
  1077. if(n < 0)
  1078. goto out;
  1079. }
  1080. else {
  1081. if((curl_off_t)buflen > ws->enc.payload_remain) {
  1082. infof(data, "WS: unaligned frame size (sending %zu instead of %"
  1083. FMT_OFF_T ")",
  1084. buflen, ws->enc.payload_remain);
  1085. }
  1086. }
  1087. }
  1088. else if(!ws->enc.payload_remain) {
  1089. n = ws_enc_write_head(data, &ws->enc, flags, (curl_off_t)buflen,
  1090. &ws->sendbuf, &result);
  1091. if(n < 0)
  1092. goto out;
  1093. }
  1094. n = ws_enc_write_payload(&ws->enc, data,
  1095. buffer, buflen, &ws->sendbuf, &result);
  1096. if(n < 0)
  1097. goto out;
  1098. payload_added = (size_t)n;
  1099. while(!result && (buflen || !Curl_bufq_is_empty(&ws->sendbuf))) {
  1100. /* flush, blocking when in callback */
  1101. result = ws_flush(data, ws, Curl_is_in_callback(data));
  1102. if(!result) {
  1103. DEBUGASSERT(payload_added <= buflen);
  1104. /* all buffered data sent. Try sending the rest if there is any. */
  1105. *sent += payload_added;
  1106. buffer = (const char *)buffer + payload_added;
  1107. buflen -= payload_added;
  1108. payload_added = 0;
  1109. if(buflen) {
  1110. n = ws_enc_write_payload(&ws->enc, data,
  1111. buffer, buflen, &ws->sendbuf, &result);
  1112. if(n < 0)
  1113. goto out;
  1114. payload_added = Curl_bufq_len(&ws->sendbuf);
  1115. }
  1116. }
  1117. else if(result == CURLE_AGAIN) {
  1118. /* partially sent. how much of the call data has been part of it? what
  1119. * should we report to out caller so it can retry/send the rest? */
  1120. if(payload_added < buflen) {
  1121. /* We did not add everything the caller wanted. Return just
  1122. * the partial write to our buffer. */
  1123. *sent = payload_added;
  1124. result = CURLE_OK;
  1125. goto out;
  1126. }
  1127. else if(!buflen) {
  1128. /* We have no payload to report a partial write. EAGAIN would make
  1129. * the caller repeat this and add the frame again.
  1130. * Flush blocking seems the only way out of this. */
  1131. *sent = (size_t)n;
  1132. result = ws_flush(data, ws, TRUE);
  1133. goto out;
  1134. }
  1135. /* We added the complete data to our sendbuf. Report one byte less as
  1136. * sent. This partial success should make the caller invoke us again
  1137. * with the last byte. */
  1138. *sent = payload_added - 1;
  1139. result = Curl_bufq_unwrite(&ws->sendbuf, 1);
  1140. if(!result)
  1141. result = CURLE_AGAIN;
  1142. }
  1143. }
  1144. out:
  1145. CURL_TRC_WS(data, "curl_ws_send(len=%zu, fragsize=%" FMT_OFF_T
  1146. ", flags=%x, raw=%d) -> %d, %zu",
  1147. buflen, fragsize, flags, data->set.ws_raw_mode, result, *sent);
  1148. return result;
  1149. }
  1150. static void ws_free(struct connectdata *conn)
  1151. {
  1152. if(conn && conn->proto.ws) {
  1153. Curl_bufq_free(&conn->proto.ws->recvbuf);
  1154. Curl_bufq_free(&conn->proto.ws->sendbuf);
  1155. Curl_safefree(conn->proto.ws);
  1156. }
  1157. }
  1158. static CURLcode ws_setup_conn(struct Curl_easy *data,
  1159. struct connectdata *conn)
  1160. {
  1161. /* WebSockets is 1.1 only (for now) */
  1162. data->state.httpwant = CURL_HTTP_VERSION_1_1;
  1163. return Curl_http_setup_conn(data, conn);
  1164. }
  1165. static CURLcode ws_disconnect(struct Curl_easy *data,
  1166. struct connectdata *conn,
  1167. bool dead_connection)
  1168. {
  1169. (void)data;
  1170. (void)dead_connection;
  1171. ws_free(conn);
  1172. return CURLE_OK;
  1173. }
  1174. CURL_EXTERN const struct curl_ws_frame *curl_ws_meta(CURL *d)
  1175. {
  1176. /* we only return something for websocket, called from within the callback
  1177. when not using raw mode */
  1178. struct Curl_easy *data = d;
  1179. if(GOOD_EASY_HANDLE(data) && Curl_is_in_callback(data) && data->conn &&
  1180. data->conn->proto.ws && !data->set.ws_raw_mode)
  1181. return &data->conn->proto.ws->frame;
  1182. return NULL;
  1183. }
  1184. const struct Curl_handler Curl_handler_ws = {
  1185. "WS", /* scheme */
  1186. ws_setup_conn, /* setup_connection */
  1187. Curl_http, /* do_it */
  1188. Curl_http_done, /* done */
  1189. ZERO_NULL, /* do_more */
  1190. Curl_http_connect, /* connect_it */
  1191. ZERO_NULL, /* connecting */
  1192. ZERO_NULL, /* doing */
  1193. ZERO_NULL, /* proto_getsock */
  1194. Curl_http_getsock_do, /* doing_getsock */
  1195. ZERO_NULL, /* domore_getsock */
  1196. ZERO_NULL, /* perform_getsock */
  1197. ws_disconnect, /* disconnect */
  1198. Curl_http_write_resp, /* write_resp */
  1199. Curl_http_write_resp_hd, /* write_resp_hd */
  1200. ZERO_NULL, /* connection_check */
  1201. ZERO_NULL, /* attach connection */
  1202. PORT_HTTP, /* defport */
  1203. CURLPROTO_WS, /* protocol */
  1204. CURLPROTO_HTTP, /* family */
  1205. PROTOPT_CREDSPERREQUEST | /* flags */
  1206. PROTOPT_USERPWDCTRL
  1207. };
  1208. #ifdef USE_SSL
  1209. const struct Curl_handler Curl_handler_wss = {
  1210. "WSS", /* scheme */
  1211. ws_setup_conn, /* setup_connection */
  1212. Curl_http, /* do_it */
  1213. Curl_http_done, /* done */
  1214. ZERO_NULL, /* do_more */
  1215. Curl_http_connect, /* connect_it */
  1216. NULL, /* connecting */
  1217. ZERO_NULL, /* doing */
  1218. NULL, /* proto_getsock */
  1219. Curl_http_getsock_do, /* doing_getsock */
  1220. ZERO_NULL, /* domore_getsock */
  1221. ZERO_NULL, /* perform_getsock */
  1222. ws_disconnect, /* disconnect */
  1223. Curl_http_write_resp, /* write_resp */
  1224. Curl_http_write_resp_hd, /* write_resp_hd */
  1225. ZERO_NULL, /* connection_check */
  1226. ZERO_NULL, /* attach connection */
  1227. PORT_HTTPS, /* defport */
  1228. CURLPROTO_WSS, /* protocol */
  1229. CURLPROTO_HTTP, /* family */
  1230. PROTOPT_SSL | PROTOPT_CREDSPERREQUEST | /* flags */
  1231. PROTOPT_USERPWDCTRL
  1232. };
  1233. #endif
  1234. #else
  1235. CURL_EXTERN CURLcode curl_ws_recv(CURL *curl, void *buffer, size_t buflen,
  1236. size_t *nread,
  1237. const struct curl_ws_frame **metap)
  1238. {
  1239. (void)curl;
  1240. (void)buffer;
  1241. (void)buflen;
  1242. (void)nread;
  1243. (void)metap;
  1244. return CURLE_NOT_BUILT_IN;
  1245. }
  1246. CURL_EXTERN CURLcode curl_ws_send(CURL *curl, const void *buffer,
  1247. size_t buflen, size_t *sent,
  1248. curl_off_t fragsize,
  1249. unsigned int flags)
  1250. {
  1251. (void)curl;
  1252. (void)buffer;
  1253. (void)buflen;
  1254. (void)sent;
  1255. (void)fragsize;
  1256. (void)flags;
  1257. return CURLE_NOT_BUILT_IN;
  1258. }
  1259. CURL_EXTERN const struct curl_ws_frame *curl_ws_meta(CURL *data)
  1260. {
  1261. (void)data;
  1262. return NULL;
  1263. }
  1264. #endif /* !CURL_DISABLE_WEBSOCKETS */