master
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 "urldata.h"
26#include "ws.h"
28#ifndef CURL_DISABLE_WEBSOCKETS
30#include "url.h"
31#include "bufq.h"
32#include "curlx/dynbuf.h"
33#include "rand.h"
34#include "curlx/base64.h"
35#include "cf-recvbuf.h"
36#include "connect.h"
37#include "sendf.h"
38#include "curl_trc.h"
39#include "multiif.h"
40#include "easyif.h"
41#include "transfer.h"
42#include "select.h"
43#include "curlx/strparse.h"
44#include "curlx/strcopy.h"
46/* RFC 6455 Section 5.2
48 0 1 2 3 4 5 6 7
49 +-+-+-+-+-------+
50 |F|R|R|R| opcode|
51 |I|S|S|S| (4) |
52 |N|V|V|V| |
53 | |1|2|3| |
54 */
55#define WSBIT_FIN 0x80
56#define WSBIT_RSV1 0x40
57#define WSBIT_RSV2 0x20
58#define WSBIT_RSV3 0x10
59#define WSBIT_RSV_MASK (WSBIT_RSV1 | WSBIT_RSV2 | WSBIT_RSV3)
60#define WSBIT_OPCODE_CONT 0x0
61#define WSBIT_OPCODE_TEXT 0x1
62#define WSBIT_OPCODE_BIN 0x2
63#define WSBIT_OPCODE_CLOSE 0x8
64#define WSBIT_OPCODE_PING 0x9
65#define WSBIT_OPCODE_PONG 0xa
66#ifdef CURLVERBOSE
67#define WSBIT_OPCODE_MASK 0xf
68#endif
70#define WSBIT_MASK 0x80
72/* buffer dimensioning */
73#define WS_CHUNK_SIZE 65535
74#define WS_CHUNK_COUNT 2
76/* a client-side WS frame decoder, parsing frame headers and
77 * payload, keeping track of current position and stats */
78enum ws_dec_state {
79 WS_DEC_INIT,
80 WS_DEC_HEAD,
81 WS_DEC_PAYLOAD
82};
84struct ws_decoder {
85 int frame_age; /* zero */
86 int frame_flags; /* See the CURLWS_* defines */
87 curl_off_t payload_offset; /* the offset parsing is at */
88 curl_off_t payload_len;
89 uint8_t head[10];
90 int head_len, head_total;
91 enum ws_dec_state state;
92 int cont_flags;
93 BIT(seen_close); /* passed on a complete CLOSE frame */
94};
96/* a client-side WS frame encoder, generating frame headers and
97 * converting payloads, tracking remaining data in current frame */
98struct ws_encoder {
99 curl_off_t payload_len; /* payload length of current frame */
100 curl_off_t payload_remain; /* remaining payload of current */
101 unsigned int xori; /* xor index */
102 unsigned int maskpool_left; /* bytes not yet used at the end of maskpool */
103 uint8_t mask[4]; /* 32-bit mask for this connection */
104 uint8_t firstbyte; /* first byte of frame we encode */
105 BIT(contfragment); /* set TRUE if the previous fragment sent was not final */
106 uint8_t maskpool[256]; /* random bytes for the masks of coming frames */
107};
109/* Control frames are allowed up to 125 characters, rfc6455, ch. 5.5 */
110#define WS_MAX_CNTRL_LEN 125
112struct ws_cntrl_frame {
113 unsigned int type;
114 size_t payload_len;
115 uint8_t payload[WS_MAX_CNTRL_LEN];
116};
118/* A websocket connection with en- and decoder that treat frames
119 * and keep track of boundaries. */
120struct websocket {
121 struct Curl_easy *data; /* used for write callback handling */
122 struct ws_decoder dec; /* decode of ws frames */
123 struct ws_encoder enc; /* encode of ws frames */
124 struct bufq recvbuf; /* raw data from the server */
125 struct bufq sendbuf; /* raw data to be sent to the server */
126 struct curl_ws_frame recvframe; /* the current WS FRAME received */
127 struct ws_cntrl_frame pending; /* a control frame pending to be sent */
128 size_t sendbuf_payload; /* number of payload bytes in sendbuf */
129 BIT(using_reader); /* sending WS data is handled via a client reader */
130};
132#ifdef CURLVERBOSE
133static const char *ws_frame_name_of_op(uint8_t firstbyte)
134{
135 switch(firstbyte & WSBIT_OPCODE_MASK) {
136 case WSBIT_OPCODE_CONT:
137 return "CONT";
138 case WSBIT_OPCODE_TEXT:
139 return "TEXT";
140 case WSBIT_OPCODE_BIN:
141 return "BIN";
142 case WSBIT_OPCODE_CLOSE:
143 return "CLOSE";
144 case WSBIT_OPCODE_PING:
145 return "PING";
146 case WSBIT_OPCODE_PONG:
147 return "PONG";
148 default:
149 return "???";
150 }
151}
152#endif
154static int ws_frame_firstbyte2flags(struct Curl_easy *data,
155 uint8_t firstbyte, int cont_flags)
156{
157 switch(firstbyte) {
158 /* 0x00 - intermediate TEXT/BINARY fragment */
159 case WSBIT_OPCODE_CONT:
160 if(!(cont_flags & CURLWS_CONT)) {
161 failf(data, "[WS] no ongoing fragmented message to resume");
162 return 0;
163 }
164 return cont_flags | CURLWS_CONT;
165 /* 0x80 - final TEXT/BIN fragment */
166 case (WSBIT_OPCODE_CONT | WSBIT_FIN):
167 if(!(cont_flags & CURLWS_CONT)) {
168 failf(data, "[WS] no ongoing fragmented message to resume");
169 return 0;
170 }
171 return cont_flags & ~CURLWS_CONT;
172 /* 0x01 - first TEXT fragment */
173 case WSBIT_OPCODE_TEXT:
174 if(cont_flags & CURLWS_CONT) {
175 failf(data, "[WS] fragmented message interrupted by new TEXT msg");
176 return 0;
177 }
178 return CURLWS_TEXT | CURLWS_CONT;
179 /* 0x81 - unfragmented TEXT msg */
180 case (WSBIT_OPCODE_TEXT | WSBIT_FIN):
181 if(cont_flags & CURLWS_CONT) {
182 failf(data, "[WS] fragmented message interrupted by new TEXT msg");
183 return 0;
184 }
185 return CURLWS_TEXT;
186 /* 0x02 - first BINARY fragment */
187 case WSBIT_OPCODE_BIN:
188 if(cont_flags & CURLWS_CONT) {
189 failf(data, "[WS] fragmented message interrupted by new BINARY msg");
190 return 0;
191 }
192 return CURLWS_BINARY | CURLWS_CONT;
193 /* 0x82 - unfragmented BINARY msg */
194 case (WSBIT_OPCODE_BIN | WSBIT_FIN):
195 if(cont_flags & CURLWS_CONT) {
196 failf(data, "[WS] fragmented message interrupted by new BINARY msg");
197 return 0;
198 }
199 return CURLWS_BINARY;
200 /* 0x08 - first CLOSE fragment */
201 case WSBIT_OPCODE_CLOSE:
202 failf(data, "[WS] invalid fragmented CLOSE frame");
203 return 0;
204 /* 0x88 - unfragmented CLOSE */
205 case (WSBIT_OPCODE_CLOSE | WSBIT_FIN):
206 return CURLWS_CLOSE;
207 /* 0x09 - first PING fragment */
208 case WSBIT_OPCODE_PING:
209 failf(data, "[WS] invalid fragmented PING frame");
210 return 0;
211 /* 0x89 - unfragmented PING */
212 case (WSBIT_OPCODE_PING | WSBIT_FIN):
213 return CURLWS_PING;
214 /* 0x0a - first PONG fragment */
215 case WSBIT_OPCODE_PONG:
216 failf(data, "[WS] invalid fragmented PONG frame");
217 return 0;
218 /* 0x8a - unfragmented PONG */
219 case (WSBIT_OPCODE_PONG | WSBIT_FIN):
220 return CURLWS_PONG;
221 /* invalid first byte */
222 default:
223 if(firstbyte & WSBIT_RSV_MASK)
224 /* any of the reserved bits 0x40/0x20/0x10 are set */
225 failf(data, "[WS] invalid reserved bits: %02x", firstbyte);
226 else
227 /* any of the reserved opcodes 0x3-0x7 or 0xb-0xf is used */
228 failf(data, "[WS] invalid opcode: %02x", firstbyte);
229 return 0;
230 }
231}
233static CURLcode ws_frame_flags2firstbyte(struct Curl_easy *data,
234 unsigned int flags,
235 bool contfragment,
236 uint8_t *pfirstbyte)
237{
238 *pfirstbyte = 0;
239 switch(flags & ~CURLWS_OFFSET) {
240 case 0:
241 if(contfragment) {
242 CURL_TRC_WS(data, "no flags given; interpreting as continuation "
243 "fragment for compatibility");
244 *pfirstbyte = (WSBIT_OPCODE_CONT | WSBIT_FIN);
245 return CURLE_OK;
246 }
247 failf(data, "[WS] no flags given");
248 return CURLE_BAD_FUNCTION_ARGUMENT;
249 case CURLWS_CONT:
250 if(contfragment) {
251 infof(data, "[WS] setting CURLWS_CONT flag without message type is "
252 "supported for compatibility but highly discouraged");
253 *pfirstbyte = WSBIT_OPCODE_CONT;
254 return CURLE_OK;
255 }
256 failf(data, "[WS] No ongoing fragmented message to continue");
257 return CURLE_BAD_FUNCTION_ARGUMENT;
258 case CURLWS_TEXT:
259 *pfirstbyte = contfragment ? (WSBIT_OPCODE_CONT | WSBIT_FIN)
260 : (WSBIT_OPCODE_TEXT | WSBIT_FIN);
261 return CURLE_OK;
262 case (CURLWS_TEXT | CURLWS_CONT):
263 *pfirstbyte = contfragment ? WSBIT_OPCODE_CONT : WSBIT_OPCODE_TEXT;
264 return CURLE_OK;
265 case CURLWS_BINARY:
266 *pfirstbyte = contfragment ? (WSBIT_OPCODE_CONT | WSBIT_FIN)
267 : (WSBIT_OPCODE_BIN | WSBIT_FIN);
268 return CURLE_OK;
269 case (CURLWS_BINARY | CURLWS_CONT):
270 *pfirstbyte = contfragment ? WSBIT_OPCODE_CONT : WSBIT_OPCODE_BIN;
271 return CURLE_OK;
272 case CURLWS_CLOSE:
273 *pfirstbyte = WSBIT_OPCODE_CLOSE | WSBIT_FIN;
274 return CURLE_OK;
275 case (CURLWS_CLOSE | CURLWS_CONT):
276 failf(data, "[WS] CLOSE frame must not be fragmented");
277 return CURLE_BAD_FUNCTION_ARGUMENT;
278 case CURLWS_PING:
279 *pfirstbyte = WSBIT_OPCODE_PING | WSBIT_FIN;
280 return CURLE_OK;
281 case (CURLWS_PING | CURLWS_CONT):
282 failf(data, "[WS] PING frame must not be fragmented");
283 return CURLE_BAD_FUNCTION_ARGUMENT;
284 case CURLWS_PONG:
285 *pfirstbyte = WSBIT_OPCODE_PONG | WSBIT_FIN;
286 return CURLE_OK;
287 case (CURLWS_PONG | CURLWS_CONT):
288 failf(data, "[WS] PONG frame must not be fragmented");
289 return CURLE_BAD_FUNCTION_ARGUMENT;
290 default:
291 failf(data, "[WS] unknown flags: %x", flags);
292 return CURLE_BAD_FUNCTION_ARGUMENT;
293 }
294}
296static void ws_dec_info(struct ws_decoder *dec, struct Curl_easy *data,
297 const char *msg)
298{
299 NOVERBOSE((void)msg);
300 switch(dec->head_len) {
301 case 0:
302 break;
303 case 1:
304 CURL_TRC_WS(data, "decoded %s [%s%s]", msg,
305 ws_frame_name_of_op(dec->head[0]),
306 (dec->head[0] & WSBIT_FIN) ? "" : " NON-FINAL");
307 break;
308 default:
309 if(dec->head_len < dec->head_total) {
310 CURL_TRC_WS(data, "decoded %s [%s%s](%d/%d)", msg,
311 ws_frame_name_of_op(dec->head[0]),
312 (dec->head[0] & WSBIT_FIN) ? "" : " NON-FINAL",
313 dec->head_len, dec->head_total);
314 }
315 else {
316 CURL_TRC_WS(data, "decoded %s [%s%s payload=%"
317 FMT_OFF_T "/%" FMT_OFF_T "]",
318 msg, ws_frame_name_of_op(dec->head[0]),
319 (dec->head[0] & WSBIT_FIN) ? "" : " NON-FINAL",
320 dec->payload_offset, dec->payload_len);
321 }
322 break;
323 }
324}
326static CURLcode ws_send_raw_blocking(struct Curl_easy *data,
327 struct websocket *ws,
328 const char *buffer, size_t buflen);
330typedef CURLcode ws_write_payload(const uint8_t *buf, size_t buflen,
331 int frame_age, int frame_flags,
332 curl_off_t payload_offset,
333 curl_off_t payload_len,
334 void *userp,
335 size_t *pnwritten);
337static void ws_dec_next_frame(struct ws_decoder *dec)
338{
339 dec->frame_age = 0;
340 dec->frame_flags = 0;
341 dec->payload_offset = 0;
342 dec->payload_len = 0;
343 dec->head_len = dec->head_total = 0;
344 dec->state = WS_DEC_INIT;
345 /* dec->cont_flags must be carried over to next frame */
346}
348static void ws_dec_reset(struct ws_decoder *dec)
349{
350 dec->frame_age = 0;
351 dec->frame_flags = 0;
352 dec->payload_offset = 0;
353 dec->payload_len = 0;
354 dec->head_len = dec->head_total = 0;
355 dec->state = WS_DEC_INIT;
356 dec->cont_flags = 0;
357 dec->seen_close = FALSE;
358}
360static void ws_dec_init(struct ws_decoder *dec)
361{
362 ws_dec_reset(dec);
363}
365static CURLcode ws_dec_read_head(struct ws_decoder *dec,
366 struct Curl_easy *data,
367 struct bufq *inraw)
368{
369 const uint8_t *inbuf;
370 size_t inlen;
372 while(Curl_bufq_peek(inraw, &inbuf, &inlen)) {
373 if(dec->head_len == 0) {
374 dec->head[0] = *inbuf;
375 Curl_bufq_skip(inraw, 1);
377 dec->frame_flags = ws_frame_firstbyte2flags(data, dec->head[0],
378 dec->cont_flags);
379 if(!dec->frame_flags) {
380 ws_dec_reset(dec);
381 return CURLE_RECV_ERROR;
382 }
384 /* fragmentation only applies to data frames (text/binary);
385 * control frames (close/ping/pong) do not affect the CONT status */
386 if(dec->frame_flags & (CURLWS_TEXT | CURLWS_BINARY)) {
387 dec->cont_flags = dec->frame_flags;
388 }
390 dec->head_len = 1;
391#if 0
392 ws_dec_info(dec, data, "seeing opcode");
393#endif
394 continue;
395 }
396 else if(dec->head_len == 1) {
397 dec->head[1] = *inbuf;
398 Curl_bufq_skip(inraw, 1);
399 dec->head_len = 2;
401 if(dec->head[1] & WSBIT_MASK) {
402 /* A client MUST close a connection if it detects a masked frame. */
403 failf(data, "[WS] masked input frame");
404 ws_dec_reset(dec);
405 return CURLE_RECV_ERROR;
406 }
407 if(dec->frame_flags & CURLWS_PING && dec->head[1] > WS_MAX_CNTRL_LEN) {
408 /* The maximum valid size of PING frames is 125 bytes.
409 Accepting overlong pings would mean sending equivalent pongs! */
410 failf(data, "[WS] received PING frame is too big");
411 ws_dec_reset(dec);
412 return CURLE_RECV_ERROR;
413 }
414 if(dec->frame_flags & CURLWS_PONG && dec->head[1] > WS_MAX_CNTRL_LEN) {
415 /* The maximum valid size of PONG frames is 125 bytes. */
416 failf(data, "[WS] received PONG frame is too big");
417 ws_dec_reset(dec);
418 return CURLE_RECV_ERROR;
419 }
420 if((dec->frame_flags & CURLWS_CLOSE) &&
421 (dec->head[1] > WS_MAX_CNTRL_LEN)) {
422 failf(data, "[WS] received CLOSE frame is too big");
423 ws_dec_reset(dec);
424 return CURLE_RECV_ERROR;
425 }
427 /* How long is the frame head? */
428 if(dec->head[1] == 126) {
429 dec->head_total = 4;
430 continue;
431 }
432 else if(dec->head[1] == 127) {
433 dec->head_total = 10;
434 continue;
435 }
436 else {
437 dec->head_total = 2;
438 }
439 }
441 if(dec->head_len < dec->head_total) {
442 dec->head[dec->head_len] = *inbuf;
443 Curl_bufq_skip(inraw, 1);
444 ++dec->head_len;
445 if(dec->head_len < dec->head_total) {
446#if 0
447 ws_dec_info(dec, data, "decoding head");
448#endif
449 continue;
450 }
451 }
452 /* got the complete frame head */
453 DEBUGASSERT(dec->head_len == dec->head_total);
454 switch(dec->head_total) {
455 case 2:
456 dec->payload_len = dec->head[1];
457 break;
458 case 4:
459 dec->payload_len = (dec->head[2] << 8) | dec->head[3];
460 break;
461 case 10:
462 if(dec->head[2] > 127) {
463 failf(data, "[WS] frame length longer than 63 bits not supported");
464 return CURLE_RECV_ERROR;
465 }
466 dec->payload_len =
467 (curl_off_t)dec->head[2] << 56 |
468 (curl_off_t)dec->head[3] << 48 |
469 (curl_off_t)dec->head[4] << 40 |
470 (curl_off_t)dec->head[5] << 32 |
471 (curl_off_t)dec->head[6] << 24 |
472 (curl_off_t)dec->head[7] << 16 |
473 (curl_off_t)dec->head[8] << 8 |
474 dec->head[9];
475 break;
476 default:
477 /* this should never happen */
478 DEBUGASSERT(0);
479 failf(data, "[WS] unexpected frame header length");
480 return CURLE_RECV_ERROR;
481 }
483 dec->frame_age = 0;
484 dec->payload_offset = 0;
485 ws_dec_info(dec, data, "head");
486 return CURLE_OK;
487 }
488 return CURLE_AGAIN;
489}
491static CURLcode ws_dec_pass_payload(struct ws_decoder *dec,
492 struct Curl_easy *data,
493 struct bufq *inraw,
494 ws_write_payload *write_cb,
495 void *write_ctx)
496{
497 const uint8_t *inbuf;
498 size_t inlen;
499 size_t nwritten;
500 CURLcode result;
501 size_t remain = curlx_sotouz_range(dec->payload_len - dec->payload_offset,
502 0, SIZE_MAX);
504 while(remain && Curl_bufq_peek(inraw, &inbuf, &inlen) &&
505 !Curl_cwriter_is_paused(data)) {
506 if(inlen > remain)
507 inlen = remain;
508 result = write_cb(inbuf, inlen, dec->frame_age, dec->frame_flags,
509 dec->payload_offset, dec->payload_len,
510 write_ctx, &nwritten);
511 if(result)
512 return result;
513 Curl_bufq_skip(inraw, nwritten);
514 dec->payload_offset += nwritten;
515 remain = curlx_sotouz_range(dec->payload_len - dec->payload_offset,
516 0, SIZE_MAX);
517 CURL_TRC_WS(data, "passed %zu bytes payload, %zu remain",
518 nwritten, remain);
519 }
521 return remain ? CURLE_AGAIN : CURLE_OK;
522}
524static CURLcode ws_dec_pass(struct ws_decoder *dec,
525 struct Curl_easy *data,
526 struct bufq *inraw,
527 ws_write_payload *write_cb,
528 void *write_ctx)
529{
530 CURLcode result;
532 if(Curl_bufq_is_empty(inraw))
533 return CURLE_AGAIN;
535 switch(dec->state) {
536 case WS_DEC_INIT:
537 ws_dec_next_frame(dec);
538 dec->state = WS_DEC_HEAD;
539 FALLTHROUGH();
540 case WS_DEC_HEAD:
541 result = ws_dec_read_head(dec, data, inraw);
542 if(result) {
543 if(result != CURLE_AGAIN) {
544 failf(data, "[WS] decode frame error %d", (int)result);
545 break; /* real error */
546 }
547 /* incomplete ws frame head */
548 DEBUGASSERT(Curl_bufq_is_empty(inraw));
549 break;
550 }
551 /* head parsing done */
552 dec->state = WS_DEC_PAYLOAD;
553 if(dec->payload_len == 0) {
554 size_t nwritten;
555 const uint8_t tmp = '\0';
556 /* special case of a 0 length frame, need to write once */
557 result = write_cb(&tmp, 0, dec->frame_age, dec->frame_flags,
558 0, 0, write_ctx, &nwritten);
559 if(result)
560 return result;
561 dec->state = WS_DEC_INIT;
562 break;
563 }
564 FALLTHROUGH();
565 case WS_DEC_PAYLOAD:
566 result = ws_dec_pass_payload(dec, data, inraw, write_cb, write_ctx);
567 ws_dec_info(dec, data, "passing");
568 if(result)
569 return result;
570 /* payload parsing done */
571 dec->state = WS_DEC_INIT;
572 break;
573 default:
574 /* we covered all enums above, but some code analyzers are wimps */
575 result = CURLE_FAILED_INIT;
576 }
577 if(!result && (dec->state == WS_DEC_INIT) &&
578 (dec->frame_flags & CURLWS_CLOSE))
579 dec->seen_close = TRUE;
580 return result;
581}
583static void update_meta(struct websocket *ws,
584 int frame_age, int frame_flags,
585 curl_off_t payload_offset,
586 curl_off_t payload_len,
587 size_t cur_len)
588{
589 curl_off_t bytesleft = (payload_len - payload_offset - cur_len);
591 ws->recvframe.age = frame_age;
592 ws->recvframe.flags = frame_flags;
593 ws->recvframe.offset = payload_offset;
594 ws->recvframe.len = cur_len;
595 ws->recvframe.bytesleft = bytesleft;
596}
598/* WebSocket decoding client writer */
599struct ws_cw_ctx {
600 struct Curl_cwriter super;
601 struct bufq buf;
602};
604static CURLcode ws_cw_init(struct Curl_easy *data,
605 struct Curl_cwriter *writer)
606{
607 struct ws_cw_ctx *ctx = writer->ctx;
608 (void)data;
609 Curl_bufq_init2(&ctx->buf, WS_CHUNK_SIZE, 1, BUFQ_OPT_SOFT_LIMIT);
610 return CURLE_OK;
611}
613static void ws_cw_close(struct Curl_easy *data, struct Curl_cwriter *writer)
614{
615 struct ws_cw_ctx *ctx = writer->ctx;
616 (void)data;
617 Curl_bufq_free(&ctx->buf);
618}
620struct ws_cw_dec_ctx {
621 struct Curl_easy *data;
622 struct websocket *ws;
623 struct Curl_cwriter *next_writer;
624 int cw_type;
625};
627static CURLcode ws_flush(struct Curl_easy *data, struct websocket *ws,
628 bool blocking);
629static CURLcode ws_enc_add_pending(struct Curl_easy *data,
630 struct websocket *ws);
632static CURLcode ws_enc_add_cntrl(struct Curl_easy *data,
633 struct websocket *ws,
634 const uint8_t *payload,
635 size_t plen,
636 unsigned int frame_type)
637{
638 (void)data;
639 DEBUGASSERT(plen <= WS_MAX_CNTRL_LEN);
640 if(plen > WS_MAX_CNTRL_LEN)
641 return CURLE_BAD_FUNCTION_ARGUMENT;
643 /* Overwrite any pending frame with the new one, we keep
644 * only one. */
645 ws->pending.type = frame_type;
646 ws->pending.payload_len = plen;
647 memcpy(ws->pending.payload, payload, plen);
648 return CURLE_OK;
649}
651static curl_off_t ws_payload_remain(curl_off_t payload_total,
652 curl_off_t payload_offset,
653 size_t payload_buffered)
654{
655 curl_off_t buffered, remain = payload_total - payload_offset;
656 if((payload_total < 0) || (payload_offset < 0) || (remain < 0))
657 return -1;
658 buffered = curlx_uztoso(payload_buffered);
659 if(remain < buffered)
660 return -1;
661 return remain - buffered;
662}
664static CURLcode ws_cw_dec_next(const uint8_t *buf, size_t buflen,
665 int frame_age, int frame_flags,
666 curl_off_t payload_offset,
667 curl_off_t payload_len,
668 void *user_data,
669 size_t *pnwritten)
670{
671 struct ws_cw_dec_ctx *ctx = user_data;
672 struct Curl_easy *data = ctx->data;
673 struct websocket *ws = ctx->ws;
674 bool auto_pong = !data->set.ws_raw_mode && !data->set.ws_no_auto_pong;
675 curl_off_t remain;
676 CURLcode result;
678 (void)frame_age;
679 *pnwritten = 0;
680 remain = ws_payload_remain(payload_len, payload_offset, buflen);
681 if(remain < 0) {
682 DEBUGASSERT(0); /* parameter mismatch */
683 return CURLE_BAD_FUNCTION_ARGUMENT;
684 }
686 if(auto_pong && (frame_flags & CURLWS_PING) && !remain) {
687 /* auto-respond to PINGs, only works for single-frame payloads atm */
688 CURL_TRC_WS(data, "auto PONG to [PING payload=%" FMT_OFF_T
689 "/%" FMT_OFF_T "]", payload_offset, payload_len);
690 /* send back the exact same content as a PONG */
691 result = ws_enc_add_cntrl(data, ws, buf, buflen, CURLWS_PONG);
692 if(result)
693 return result;
694 }
695 else if(buflen || !remain) {
696 /* forward the decoded frame to the next client writer. */
697 update_meta(ws, frame_age, frame_flags, payload_offset,
698 payload_len, buflen);
700 CURL_TRC_WRITE(data, "[WS] pass %zu decoded bytes", buflen);
701 result = Curl_cwriter_write(data, ctx->next_writer,
702 (ctx->cw_type | CLIENTWRITE_0LEN),
703 (const char *)buf, buflen);
704 if(result)
705 return result;
706 }
707 *pnwritten = buflen;
708 return CURLE_OK;
709}
711static CURLcode ws_cw_write(struct Curl_easy *data,
712 struct Curl_cwriter *writer, int type,
713 const char *buf, size_t nbytes)
714{
715 struct ws_cw_ctx *ctx = writer->ctx;
716 struct websocket *ws;
717 CURLcode result = CURLE_OK;
719 CURL_TRC_WRITE(data, "[WS] write(len=%zu, type=%d)", nbytes, type);
720 if(!(type & CLIENTWRITE_BODY) || data->set.ws_raw_mode)
721 return Curl_cwriter_write(data, writer->next, type, buf, nbytes);
723 ws = Curl_conn_meta_get(data->conn, CURL_META_PROTO_WS_CONN);
724 if(!ws) {
725 failf(data, "[WS] not a websocket transfer");
726 return CURLE_FAILED_INIT;
727 }
729 if(nbytes) {
730 size_t nwritten;
731 result = Curl_bufq_write(&ctx->buf, (const uint8_t *)buf,
732 nbytes, &nwritten);
733 if(result) {
734 infof(data, "[WS] error adding data to buffer %d", (int)result);
735 return result;
736 }
737 }
739 result = Curl_cwriter_flush(data, writer->next, FALSE);
740 if(result)
741 goto out;
743 while(!Curl_bufq_is_empty(&ctx->buf) && !Curl_cwriter_is_paused(data)) {
744 struct ws_cw_dec_ctx pass_ctx;
745 pass_ctx.data = data;
746 pass_ctx.ws = ws;
747 pass_ctx.next_writer = writer->next;
748 pass_ctx.cw_type = type;
749 result = ws_dec_pass(&ws->dec, data, &ctx->buf,
750 ws_cw_dec_next, &pass_ctx);
751 if(result == CURLE_AGAIN) {
752 /* insufficient amount of data, keep it for later.
753 * we pretend to have written all since we have a copy */
754 result = CURLE_OK;
755 goto out;
756 }
757 else if(result) {
758 failf(data, "[WS] decode payload error %d", (int)result);
759 Curl_bufq_reset(&ctx->buf);
760 goto out;
761 }
762 }
764out:
765 if(!result && !ws->using_reader) {
766 result = ws_flush(data, ws, Curl_api_is_in_callback(data));
767 if(result == CURLE_AGAIN)
768 result = CURLE_OK;
769 }
771 if(!result && (type & CLIENTWRITE_EOS) &&
772 (!Curl_bufq_is_empty(&ctx->buf) || (ws->dec.state != WS_DEC_INIT))) {
773 failf(data, "[WS] decode ended with incomplete frame");
774 result = CURLE_RECV_ERROR;
775 }
776 if(!result && ws->dec.seen_close && !ws->pending.type &&
777 Curl_bufq_is_empty(&ctx->buf) &&
778 Curl_bufq_is_empty(&ws->sendbuf)) {
779 CURL_TRC_WS(data, "seen CLOSE from server, stop receiving");
780 CURL_REQ_CLEAR_RECV(data);
781 }
783 return result;
784}
786static CURLcode ws_cw_flush(struct Curl_easy *data,
787 struct Curl_cwriter *writer, bool eos)
788{
789 CURLcode result = CURLE_OK;
791 CURL_TRC_WRITE(data, "[ws] flush");
792 if(!data->set.ws_raw_mode) {
793 struct ws_cw_ctx *ctx = writer->ctx;
794 struct websocket *ws;
796 /* Frames should be written one by one, else the meta data does
797 * not fit. Flush the next writer first, so it does not aggregate
798 * our flushed data with anything it might have buffered. */
799 result = Curl_cwriter_flush(data, writer->next, FALSE);
800 if(result)
801 goto out;
803 ws = Curl_conn_meta_get(data->conn, CURL_META_PROTO_WS_CONN);
804 if(!ws) {
805 failf(data, "[WS] not a websocket transfer");
806 return CURLE_FAILED_INIT;
807 }
809 while(!Curl_bufq_is_empty(&ctx->buf) && !Curl_cwriter_is_paused(data)) {
810 struct ws_cw_dec_ctx pass_ctx;
811 pass_ctx.data = data;
812 pass_ctx.ws = ws;
813 pass_ctx.next_writer = writer->next;
814 pass_ctx.cw_type = CLIENTWRITE_BODY;
815 result = ws_dec_pass(&ws->dec, data, &ctx->buf,
816 ws_cw_dec_next, &pass_ctx);
817 if(result == CURLE_AGAIN) {
818 /* insufficient amount of data, keep it for later.
819 * we pretend to have written all since we have a copy */
820 result = CURLE_OK;
821 goto out;
822 }
823 else if(result) {
824 failf(data, "[WS] decode payload error %d", (int)result);
825 Curl_bufq_reset(&ctx->buf);
826 goto out;
827 }
828 }
829 }
831out:
832 if(!result)
833 result = Curl_cwriter_flush(data, writer->next, eos);
834 return result;
835}
837/* WebSocket payload decoding client writer. */
838static const struct Curl_cwtype ws_cw_decode = {
839 "ws-decode",
840 NULL,
841 0,
842 ws_cw_init,
843 ws_cw_write,
844 ws_cw_flush,
845 ws_cw_close,
846 sizeof(struct ws_cw_ctx)
847};
849static void ws_enc_info(struct ws_encoder *enc, struct Curl_easy *data,
850 const char *msg)
851{
852 NOVERBOSE((void)enc);
853 NOVERBOSE((void)msg);
854 CURL_TRC_WS(data, "WS-ENC: %s [%s%s payload=%"
855 FMT_OFF_T "/%" FMT_OFF_T "]",
856 msg, ws_frame_name_of_op(enc->firstbyte),
857 (enc->firstbyte & WSBIT_FIN) ? "" : " NON-FIN",
858 enc->payload_len - enc->payload_remain, enc->payload_len);
859}
861static void ws_enc_reset(struct ws_encoder *enc)
862{
863 enc->payload_remain = 0;
864 enc->xori = 0;
865 enc->contfragment = FALSE;
866}
868static void ws_enc_init(struct ws_encoder *enc)
869{
870 ws_enc_reset(enc);
871 enc->maskpool_left = 0;
872}
874/* RFC 6455 Section 5.2
876 0 1 2 3
877 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
878 +-+-+-+-+-------+-+-------------+-------------------------------+
879 |F|R|R|R| opcode|M| Payload len | Extended payload length |
880 |I|S|S|S| (4) |A| (7) | (16/64) |
881 |N|V|V|V| |S| | (if payload len==126/127) |
882 | |1|2|3| |K| | |
883 +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
884 | Extended payload length continued, if payload len == 127 |
885 + - - - - - - - - - - - - - - - +-------------------------------+
886 | |Masking-key, if MASK set to 1 |
887 +-------------------------------+-------------------------------+
888 | Masking-key (continued) | Payload Data |
889 +-------------------------------- - - - - - - - - - - - - - - - +
890 : Payload Data continued ... :
891 + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
892 | Payload Data continued ... |
893 +---------------------------------------------------------------+
894 */
896static CURLcode ws_enc_add_frame(struct Curl_easy *data,
897 struct ws_encoder *enc,
898 unsigned int flags,
899 curl_off_t payload_len,
900 struct bufq *out)
901{
902 uint8_t firstb = 0;
903 uint8_t head[14];
904 CURLcode result;
905 size_t hlen, nwritten;
907 if(payload_len < 0) {
908 failf(data, "[WS] starting new frame with negative payload length %"
909 FMT_OFF_T, payload_len);
910 return CURLE_SEND_ERROR;
911 }
913 if(enc->payload_remain > 0) {
914 /* trying to write a new frame before the previous one is finished */
915 failf(data, "[WS] starting new frame with %" FMT_OFF_T " bytes "
916 "from last one remaining to be sent", enc->payload_remain);
917 return CURLE_SEND_ERROR;
918 }
920 result = ws_frame_flags2firstbyte(data, flags, (bool)enc->contfragment,
921 &firstb);
922 if(result)
923 return result;
925 /* fragmentation only applies to data frames (text/binary);
926 * control frames (close/ping/pong) do not affect the CONT status */
927 if(flags & (CURLWS_TEXT | CURLWS_BINARY)) {
928 enc->contfragment = (curl_bit)((flags & CURLWS_CONT) ? TRUE : FALSE);
929 }
931 if(flags & CURLWS_PING && payload_len > WS_MAX_CNTRL_LEN) {
932 failf(data, "[WS] given PING frame is too big");
933 return CURLE_TOO_LARGE;
934 }
935 if(flags & CURLWS_PONG && payload_len > WS_MAX_CNTRL_LEN) {
936 failf(data, "[WS] given PONG frame is too big");
937 return CURLE_TOO_LARGE;
938 }
939 if(flags & CURLWS_CLOSE && payload_len > WS_MAX_CNTRL_LEN) {
940 failf(data, "[WS] given CLOSE frame is too big");
941 return CURLE_TOO_LARGE;
942 }
944 head[0] = enc->firstbyte = firstb;
945 if(payload_len > 65535) {
946 head[1] = 127 | WSBIT_MASK;
947 head[2] = (uint8_t)((payload_len >> 56) & 0xff);
948 head[3] = (uint8_t)((payload_len >> 48) & 0xff);
949 head[4] = (uint8_t)((payload_len >> 40) & 0xff);
950 head[5] = (uint8_t)((payload_len >> 32) & 0xff);
951 head[6] = (uint8_t)((payload_len >> 24) & 0xff);
952 head[7] = (uint8_t)((payload_len >> 16) & 0xff);
953 head[8] = (uint8_t)((payload_len >> 8) & 0xff);
954 head[9] = (uint8_t)(payload_len & 0xff);
955 hlen = 10;
956 }
957 else if(payload_len >= 126) {
958 head[1] = 126 | WSBIT_MASK;
959 head[2] = (uint8_t)((payload_len >> 8) & 0xff);
960 head[3] = (uint8_t)(payload_len & 0xff);
961 hlen = 4;
962 }
963 else {
964 head[1] = (uint8_t)payload_len | WSBIT_MASK;
965 hlen = 2;
966 }
968 enc->payload_remain = enc->payload_len = payload_len;
969 ws_enc_info(enc, data, "sending");
971 /* 4 bytes random */
973 if(enc->maskpool_left < sizeof(enc->mask)) {
974 result = Curl_rand(data, enc->maskpool, sizeof(enc->maskpool));
975 if(result)
976 return result;
977 enc->maskpool_left = sizeof(enc->maskpool);
978 }
979 memcpy(enc->mask, &enc->maskpool[sizeof(enc->maskpool) -
980 enc->maskpool_left], sizeof(enc->mask));
981 enc->maskpool_left -= (unsigned int)sizeof(enc->mask);
983#ifdef DEBUGBUILD
984 if(getenv("CURL_WS_FORCE_ZERO_MASK"))
985 /* force the bit mask to 0x00000000, effectively disabling masking */
986 memset(&enc->mask, 0, sizeof(enc->mask));
987#endif
989 /* add 4 bytes mask */
990 memcpy(&head[hlen], &enc->mask, 4);
991 hlen += 4;
992 /* reset for payload to come */
993 enc->xori = 0;
995 result = Curl_bufq_write(out, head, hlen, &nwritten);
996 if(result)
997 return result;
998 if(nwritten != hlen) {
999 /* We use a bufq with SOFT_LIMIT, writing should always succeed */
1000 DEBUGASSERT(0);
1001 return CURLE_SEND_ERROR;
1002 }
1003 return CURLE_OK;
1004}
1006static CURLcode ws_enc_write_head(struct Curl_easy *data,
1007 struct websocket *ws,
1008 struct ws_encoder *enc,
1009 unsigned int flags,
1010 curl_off_t payload_len,
1011 struct bufq *out)
1012{
1013 /* starting a new frame, we want a clean sendbuf.
1014 * Any pending control frame we can add now as part of the flush. */
1015 if(ws->pending.type) {
1016 CURLcode result = ws_enc_add_pending(data, ws);
1017 if(result)
1018 return result;
1019 }
1020 return ws_enc_add_frame(data, enc, flags, payload_len, out);
1021}
1023/*
1024 * Mask and append payload to the bufq in chunks.
1025 *
1026 * @unittest 2607
1027 */
1028UNITTEST CURLcode ws_enc_mask_write(const uint8_t *mask, unsigned int *pxori,
1029 const uint8_t *buf, size_t len,
1030 struct bufq *out, size_t *pnwritten);
1031UNITTEST CURLcode ws_enc_mask_write(const uint8_t *mask, unsigned int *pxori,
1032 const uint8_t *buf, size_t len,
1033 struct bufq *out, size_t *pnwritten)
1034{
1035 CURLcode result;
1036 size_t i, done = 0;
1038 *pnwritten = 0;
1039 while(done < len) {
1040 uint8_t tmp[1024];
1041 uint8_t mask8[8];
1042 uint64_t m;
1043 size_t n = CURLMIN(len - done, sizeof(tmp));
1044 size_t nwritten;
1046 for(i = 0; i < 8; i++)
1047 mask8[i] = mask[(*pxori + i) & 3];
1048 memcpy(&m, mask8, 8);
1049 for(i = 0; i + 8 <= n; i += 8) {
1050 uint64_t v;
1051 memcpy(&v, &buf[done + i], 8);
1052 v ^= m;
1053 memcpy(&tmp[i], &v, 8);
1054 }
1055 for(; i < n; i++)
1056 tmp[i] = buf[done + i] ^ mask8[i & 7];
1058 result = Curl_bufq_write(out, tmp, n, &nwritten);
1059 if(result) {
1060 if((result != CURLE_AGAIN) || !done)
1061 return result;
1062 break;
1063 }
1064 done += nwritten;
1065 *pxori = (*pxori + (unsigned int)nwritten) & 3;
1066 if(nwritten < n)
1067 break;
1068 }
1069 *pnwritten = done;
1070 return CURLE_OK;
1071}
1073static CURLcode ws_enc_write_payload(struct ws_encoder *enc,
1074 struct Curl_easy *data,
1075 const uint8_t *buf, size_t buflen,
1076 struct bufq *out, size_t *pnwritten)
1077{
1078 CURLcode result;
1079 size_t len, remain;
1081 *pnwritten = 0;
1082 if(Curl_bufq_is_full(out))
1083 return CURLE_AGAIN;
1085 len = buflen;
1086 remain = curlx_sotouz_range(enc->payload_remain, 0, SIZE_MAX);
1087 if(remain < len)
1088 len = remain;
1090 result = ws_enc_mask_write(enc->mask, &enc->xori, buf, len, out,
1091 pnwritten);
1092 if(result)
1093 return result;
1094 enc->payload_remain -= (curl_off_t)*pnwritten;
1095 ws_enc_info(enc, data, "buffered");
1096 return CURLE_OK;
1097}
1099static CURLcode ws_enc_add_pending(struct Curl_easy *data,
1100 struct websocket *ws)
1101{
1102 CURLcode result;
1103 size_t n;
1105 if(!ws->pending.type) /* no pending frame here */
1106 return CURLE_OK;
1107 if(ws->enc.payload_remain) /* in the middle of another frame */
1108 return CURLE_AGAIN;
1110 result = ws_enc_add_frame(data, &ws->enc, ws->pending.type,
1111 (curl_off_t)ws->pending.payload_len,
1112 &ws->sendbuf);
1113 if(result) {
1114 CURL_TRC_WS(data, "ws_enc_cntrl(), error adding head: %d",
1115 (int)result);
1116 goto out;
1117 }
1118 result = ws_enc_write_payload(&ws->enc, data, ws->pending.payload,
1119 ws->pending.payload_len,
1120 &ws->sendbuf, &n);
1121 if(result) {
1122 CURL_TRC_WS(data, "ws_enc_cntrl(), error adding payload: %d",
1123 (int)result);
1124 goto out;
1125 }
1126 if(n != ws->pending.payload_len) {
1127 DEBUGASSERT(0); /* buffer should always be able to take all */
1128 CURL_TRC_WS(data, "ws_enc_cntrl(), error added only %zu/%zu payload,",
1129 n, ws->pending.payload_len);
1130 result = CURLE_SEND_ERROR;
1131 goto out;
1132 }
1133 /* the frame should be complete now */
1134 DEBUGASSERT(!ws->enc.payload_remain);
1135 memset(&ws->pending, 0, sizeof(ws->pending));
1137out:
1138 return result;
1139}
1141static CURLcode ws_enc_send(struct Curl_easy *data,
1142 struct websocket *ws,
1143 const uint8_t *buffer,
1144 size_t buflen,
1145 curl_off_t fragsize,
1146 unsigned int flags,
1147 size_t *pnsent)
1148{
1149 size_t n;
1150 CURLcode result = CURLE_OK;
1152 DEBUGASSERT(!data->set.ws_raw_mode);
1153 *pnsent = 0;
1155 if(ws->enc.payload_remain || !Curl_bufq_is_empty(&ws->sendbuf)) {
1156 /* a frame is ongoing with payload buffered or more payload
1157 * that needs to be encoded into the buffer */
1158 if(buflen < ws->sendbuf_payload) {
1159 /* We have been called with LESS buffer data than before. This
1160 * is not how it is supposed too work. */
1161 failf(data, "[WS] curl_ws_send() called with smaller 'buflen' than "
1162 "bytes already buffered in previous call, %zu vs %zu",
1163 buflen, ws->sendbuf_payload);
1164 return CURLE_BAD_FUNCTION_ARGUMENT;
1165 }
1166 if((curl_off_t)buflen >
1167 (ws->enc.payload_remain + (curl_off_t)ws->sendbuf_payload)) {
1168 /* too large buflen beyond payload length of frame */
1169 failf(data, "[WS] unaligned frame size (sending %zu instead of "
1170 "%" FMT_OFF_T ")", buflen,
1171 (curl_off_t)(ws->enc.payload_remain + ws->sendbuf_payload));
1172 return CURLE_BAD_FUNCTION_ARGUMENT;
1173 }
1174 }
1175 else {
1176 result = ws_flush(data, ws, Curl_api_is_in_callback(data));
1177 if(result)
1178 return result;
1180 result = ws_enc_write_head(data, ws, &ws->enc, flags,
1181 (flags & CURLWS_OFFSET) ?
1182 fragsize : (curl_off_t)buflen,
1183 &ws->sendbuf);
1184 if(result) {
1185 CURL_TRC_WS(data, "curl_ws_send(), error writing frame head %d",
1186 (int)result);
1187 return result;
1188 }
1189 }
1191 /* While there is either sendbuf to flush OR more payload to encode... */
1192 while(!Curl_bufq_is_empty(&ws->sendbuf) || (buflen > ws->sendbuf_payload)) {
1193 /* Try to add more payload to sendbuf */
1194 if(buflen > ws->sendbuf_payload) {
1195 size_t prev_len = Curl_bufq_len(&ws->sendbuf);
1196 result = ws_enc_write_payload(&ws->enc, data,
1197 buffer + ws->sendbuf_payload,
1198 buflen - ws->sendbuf_payload,
1199 &ws->sendbuf, &n);
1200 if(result && (result != CURLE_AGAIN))
1201 return result;
1202 ws->sendbuf_payload += Curl_bufq_len(&ws->sendbuf) - prev_len;
1203 if(!ws->sendbuf_payload) {
1204 return CURLE_AGAIN;
1205 }
1206 }
1208 /* flush, blocking when in callback */
1209 result = ws_flush(data, ws, Curl_api_is_in_callback(data));
1210 if(!result && ws->sendbuf_payload > 0) {
1211 *pnsent += ws->sendbuf_payload;
1212 buffer += ws->sendbuf_payload;
1213 buflen -= ws->sendbuf_payload;
1214 ws->sendbuf_payload = 0;
1215 }
1216 else if(result == CURLE_AGAIN) {
1217 if(ws->sendbuf_payload > Curl_bufq_len(&ws->sendbuf)) {
1218 /* blocked, part of payload bytes remain, report length
1219 * that we managed to send. */
1220 size_t flushed = (ws->sendbuf_payload - Curl_bufq_len(&ws->sendbuf));
1221 *pnsent += flushed;
1222 ws->sendbuf_payload -= flushed;
1223 return CURLE_OK;
1224 }
1225 else {
1226 /* blocked before sending headers or 1st payload byte. We cannot report
1227 * OK on 0-length send (caller counts only payload) and EAGAIN */
1228 CURL_TRC_WS(data, "EAGAIN flushing sendbuf, payload_encoded: %zu/%zu",
1229 ws->sendbuf_payload, buflen);
1230 DEBUGASSERT(*pnsent == 0);
1231 return CURLE_AGAIN;
1232 }
1233 }
1234 else
1235 return result; /* real error sending the data */
1236 }
1237 return CURLE_OK;
1238}
1240struct cr_ws_ctx {
1241 struct Curl_creader super;
1242 BIT(read_eos); /* we read an EOS from the next reader */
1243 BIT(eos); /* we have returned an EOS */
1244};
1246static CURLcode cr_ws_init(struct Curl_easy *data, struct Curl_creader *reader)
1247{
1248 (void)data;
1249 (void)reader;
1250 return CURLE_OK;
1251}
1253static void cr_ws_close(struct Curl_easy *data, struct Curl_creader *reader)
1254{
1255 (void)data;
1256 (void)reader;
1257}
1259static CURLcode cr_ws_read(struct Curl_easy *data,
1260 struct Curl_creader *reader,
1261 char *buf, size_t blen,
1262 size_t *pnread, bool *peos)
1263{
1264 struct cr_ws_ctx *ctx = reader->ctx;
1265 CURLcode result = CURLE_OK;
1266 size_t nread, n;
1267 struct websocket *ws;
1268 bool eos;
1270 *pnread = 0;
1271 if(ctx->eos) {
1272 *peos = TRUE;
1273 return CURLE_OK;
1274 }
1276 ws = Curl_conn_meta_get(data->conn, CURL_META_PROTO_WS_CONN);
1277 if(!ws) {
1278 failf(data, "[WS] not a websocket transfer");
1279 return CURLE_FAILED_INIT;
1280 }
1282 if(Curl_bufq_is_empty(&ws->sendbuf)) {
1283 if(ctx->read_eos) {
1284 ctx->eos = TRUE;
1285 *peos = TRUE;
1286 return CURLE_OK;
1287 }
1289 if(ws->enc.payload_remain) {
1290 CURL_TRC_WS(data, "current frame, %" FMT_OFF_T " remaining",
1291 ws->enc.payload_remain);
1292 blen = curlx_sotouz_range(ws->enc.payload_remain, 0, blen);
1293 }
1295 result = Curl_creader_read(data, reader->next, buf, blen, &nread, &eos);
1296 if(result)
1297 return result;
1298 ctx->read_eos = eos;
1300 if(!Curl_bufq_is_empty(&ws->sendbuf)) {
1301 /* client_read started a new frame, we disregard any eos reported */
1302 ctx->read_eos = FALSE;
1303 Curl_creader_clear_eos(data, reader->next);
1304 }
1305 else if(!nread) {
1306 /* nothing to convert, return this right away */
1307 if(ctx->read_eos)
1308 ctx->eos = TRUE;
1309 *pnread = nread;
1310 *peos = (bool)ctx->eos;
1311 goto out;
1312 }
1314 if(!ws->enc.payload_remain && Curl_bufq_is_empty(&ws->sendbuf)) {
1315 /* encode the data as a new BINARY frame */
1316 result = ws_enc_write_head(data, ws, &ws->enc, CURLWS_BINARY, nread,
1317 &ws->sendbuf);
1318 if(result)
1319 goto out;
1320 }
1322 result = ws_enc_write_payload(&ws->enc, data, (uint8_t *)buf,
1323 nread, &ws->sendbuf, &n);
1324 if(result)
1325 goto out;
1326 CURL_TRC_READ(data, "cr_ws_read, added %zu payload, len=%zu", nread, n);
1327 }
1329 DEBUGASSERT(!Curl_bufq_is_empty(&ws->sendbuf));
1330 *peos = FALSE;
1331 result = Curl_bufq_cread(&ws->sendbuf, buf, blen, pnread);
1332 if(!result && ctx->read_eos && Curl_bufq_is_empty(&ws->sendbuf)) {
1333 /* no more data, read all, done. */
1334 ctx->eos = TRUE;
1335 *peos = TRUE;
1336 }
1338out:
1339 CURL_TRC_READ(data, "cr_ws_read(len=%zu) -> %d, nread=%zu, eos=%d",
1340 blen, (int)result, *pnread, *peos);
1341 return result;
1342}
1344static curl_off_t cr_ws_total_length(struct Curl_easy *data,
1345 struct Curl_creader *reader)
1346{
1347 /* this reader changes length depending on input */
1348 (void)data;
1349 (void)reader;
1350 return -1;
1351}
1353static const struct Curl_crtype ws_cr_encode = {
1354 "ws-encode",
1355 cr_ws_init,
1356 cr_ws_read,
1357 cr_ws_close,
1358 Curl_creader_def_needs_rewind,
1359 cr_ws_total_length,
1360 Curl_creader_def_resume_from,
1361 Curl_creader_def_cntrl,
1362 Curl_creader_def_is_paused,
1363 Curl_creader_def_done,
1364 sizeof(struct cr_ws_ctx)
1365};
1367struct wsfield {
1368 const char *name;
1369 const char *val;
1370};
1372CURLcode Curl_ws_request(struct Curl_easy *data, struct dynbuf *req)
1373{
1374 unsigned int i;
1375 CURLcode result = CURLE_OK;
1376 uint8_t rand[16];
1377 char *randstr;
1378 size_t randlen;
1379 char keyval[40];
1380 struct SingleRequest *k = &data->req;
1381 struct wsfield heads[] = {
1382 {
1383 /* The request MUST contain an |Upgrade| header field whose value
1384 MUST include the "websocket" keyword. */
1385 "Upgrade", "websocket"
1386 },
1387 {
1388 /* The request MUST include a header field with the name
1389 |Sec-WebSocket-Version|. The value of this header field MUST be
1390 13. */
1391 "Sec-WebSocket-Version", "13",
1392 },
1393 {
1394 /* The request MUST include a header field with the name
1395 |Sec-WebSocket-Key|. The value of this header field MUST be a nonce
1396 consisting of a randomly selected 16-byte value that has been
1397 base64-encoded (see Section 4 of [RFC4648]). The nonce MUST be
1398 selected randomly for each connection. */
1399 "Sec-WebSocket-Key", NULL,
1400 }
1401 };
1402 heads[2].val = &keyval[0];
1404 /* 16 bytes random */
1405 result = Curl_rand(data, rand, sizeof(rand));
1406 if(result)
1407 return result;
1408 result = curlx_base64_encode(rand, sizeof(rand), &randstr, &randlen);
1409 if(result)
1410 return result;
1411 DEBUGASSERT(randlen < sizeof(keyval));
1412 if(randlen >= sizeof(keyval)) {
1413 curlx_free(randstr);
1414 return CURLE_FAILED_INIT;
1415 }
1416 curlx_strcopy(keyval, sizeof(keyval), randstr, randlen);
1417 curlx_free(randstr);
1418 for(i = 0; !result && (i < CURL_ARRAYSIZE(heads)); i++) {
1419 if(!Curl_checkheaders(data, heads[i].name, strlen(heads[i].name))) {
1420 result = curlx_dyn_addf(req, "%s: %s\r\n", heads[i].name, heads[i].val);
1421 }
1422 }
1423 data->state.http_hd_upgrade = TRUE;
1424 k->upgr101 = UPGR101_WS;
1425 data->conn->bits.upgrade_in_progress = TRUE;
1426 return result;
1427}
1429static void ws_conn_dtor(const void *key, size_t klen, void *entry)
1430{
1431 struct websocket *ws = entry;
1432 (void)key;
1433 (void)klen;
1434 Curl_bufq_free(&ws->recvbuf);
1435 Curl_bufq_free(&ws->sendbuf);
1436 curlx_free(ws);
1437}
1439/*
1440 * 'nread' is number of bytes of websocket data already in the buffer at
1441 * 'mem'.
1442 */
1443CURLcode Curl_ws_accept(struct Curl_easy *data,
1444 const char *mem, size_t nread)
1445{
1446 struct SingleRequest *k = &data->req;
1447 struct websocket *ws;
1448 struct Curl_cwriter *ws_dec_writer = NULL;
1449 struct Curl_creader *ws_enc_reader = NULL;
1450 CURLcode result;
1452 DEBUGASSERT(data->conn);
1453 ws = Curl_conn_meta_get(data->conn, CURL_META_PROTO_WS_CONN);
1454 if(!ws) {
1455 size_t chunk_size = WS_CHUNK_SIZE;
1456 ws = curlx_calloc(1, sizeof(*ws));
1457 if(!ws)
1458 return CURLE_OUT_OF_MEMORY;
1459#ifdef DEBUGBUILD
1460 {
1461 const char *p = getenv("CURL_WS_CHUNK_SIZE");
1462 if(p) {
1463 curl_off_t l;
1464 if(!curlx_str_number(&p, &l, 1 * 1024 * 1024))
1465 chunk_size = (size_t)l;
1466 }
1467 }
1468#endif
1469 CURL_TRC_WS(data, "WS, using chunk size %zu", chunk_size);
1470 Curl_bufq_init2(&ws->recvbuf, chunk_size, WS_CHUNK_COUNT,
1471 BUFQ_OPT_SOFT_LIMIT);
1472 Curl_bufq_init2(&ws->sendbuf, chunk_size, WS_CHUNK_COUNT,
1473 BUFQ_OPT_SOFT_LIMIT);
1474 ws_dec_init(&ws->dec);
1475 ws_enc_init(&ws->enc);
1476 result = Curl_conn_meta_set(data->conn, CURL_META_PROTO_WS_CONN,
1477 ws, ws_conn_dtor);
1478 if(result)
1479 return result;
1480 }
1481 else {
1482 Curl_bufq_reset(&ws->recvbuf);
1483 ws_dec_reset(&ws->dec);
1484 ws_enc_reset(&ws->enc);
1485 }
1486 /* Verify the Sec-WebSocket-Accept response.
1488 The sent value is the base64 encoded version of a SHA-1 hash done on the
1489 |Sec-WebSocket-Key| header field concatenated with
1490 the string "258EAFA5-E914-47DA-95CA-C5AB0DC85B11". */
1492 /* If the response includes a |Sec-WebSocket-Extensions| header field and
1493 this header field indicates the use of an extension that was not present
1494 in the client's handshake (the server has indicated an extension not
1495 requested by the client), the client MUST Fail the WebSocket Connection.
1496 */
1498 /* If the response includes a |Sec-WebSocket-Protocol| header field
1499 and this header field indicates the use of a subprotocol that was
1500 not present in the client's handshake (the server has indicated a
1501 subprotocol not requested by the client), the client MUST Fail
1502 the WebSocket Connection. */
1504 infof(data, "[WS] Received 101, switch to WebSocket");
1506 /* Install our client writer that decodes WS frames payload */
1507 result = Curl_cwriter_create(&ws_dec_writer, data, &ws_cw_decode,
1508 CURL_CW_CONTENT_DECODE);
1509 if(result)
1510 goto out;
1511 result = Curl_cwriter_add(data, ws_dec_writer);
1512 if(result)
1513 goto out;
1514 ws_dec_writer = NULL; /* owned by transfer now */
1516 k->header = FALSE; /* we will not get more response headers */
1518 if(data->set.connect_only) {
1519 /* In CONNECT_ONLY setup, the payloads from `mem` need to be received
1520 * when using `curl_ws_recv/curl_easy_recv` later on, after this transfer
1521 * is already marked as DONE.
1522 * Since `curl_easy_recv()` is also supposed to work, we need
1523 * to buffer the data at connection level. See #22107 */
1524 if(nread) {
1525 result = Curl_cf_recvbuf_add(data, data->conn, FIRSTSOCKET,
1526 (const uint8_t *)mem, nread);
1527 if(result)
1528 goto out;
1529 }
1530 CURL_REQ_CLEAR_RECV(data); /* read no more content */
1531 }
1532 else { /* !connect_only */
1533 if(data->set.method == HTTPREQ_PUT) {
1534 CURL_TRC_WS(data, "UPLOAD set, add ws-encode reader");
1535 result = Curl_creader_set_fread(data, -1);
1536 if(result)
1537 goto out;
1539 if(!data->set.ws_raw_mode) {
1540 /* Add our client reader encoding WS BINARY frames */
1541 result = Curl_creader_create(&ws_enc_reader, data, &ws_cr_encode,
1542 CURL_CR_CONTENT_ENCODE);
1543 if(result)
1544 goto out;
1545 result = Curl_creader_add(data, ws_enc_reader);
1546 if(result)
1547 goto out;
1548 ws_enc_reader = NULL; /* owned by transfer now */
1549 ws->using_reader = TRUE;
1550 }
1552 /* start over with sending */
1553 data->req.eos_read = FALSE;
1554 data->req.upload_done = FALSE;
1555 CURL_REQ_SET_SEND(data);
1556 }
1558 /* Then pass any additional data to the writers */
1559 if(nread) {
1560 result = Curl_client_write(data, CLIENTWRITE_BODY, mem, nread);
1561 if(result)
1562 goto out;
1563 }
1564 }
1566 k->upgr101 = UPGR101_RECEIVED;
1567 k->header = FALSE; /* we will not get more responses */
1569out:
1570 if(ws_dec_writer)
1571 Curl_cwriter_free(data, ws_dec_writer);
1572 if(ws_enc_reader)
1573 Curl_creader_free(data, ws_enc_reader);
1574 if(result)
1575 CURL_TRC_WS(data, "Curl_ws_accept() failed -> %d", (int)result);
1576 else
1577 CURL_TRC_WS(data, "websocket established, %s mode",
1578 data->set.connect_only ? "connect-only" : "callback");
1579 return result;
1580}
1582struct ws_collect {
1583 struct Curl_easy *data;
1584 struct websocket *ws;
1585 uint8_t *buffer;
1586 size_t buflen;
1587 size_t bufidx;
1588 int frame_age;
1589 int frame_flags;
1590 curl_off_t payload_offset;
1591 curl_off_t payload_len;
1592 bool written;
1593};
1595static CURLcode ws_client_collect(const uint8_t *buf, size_t buflen,
1596 int frame_age, int frame_flags,
1597 curl_off_t payload_offset,
1598 curl_off_t payload_len,
1599 void *userp,
1600 size_t *pnwritten)
1601{
1602 struct ws_collect *ctx = userp;
1603 struct Curl_easy *data = ctx->data;
1604 bool auto_pong = !data->set.ws_raw_mode && !data->set.ws_no_auto_pong;
1605 curl_off_t remain;
1606 CURLcode result = CURLE_OK;
1608 *pnwritten = 0;
1609 remain = ws_payload_remain(payload_len, payload_offset, buflen);
1610 if(remain < 0) {
1611 DEBUGASSERT(0); /* parameter mismatch */
1612 return CURLE_BAD_FUNCTION_ARGUMENT;
1613 }
1615 if(!ctx->bufidx) {
1616 /* first write */
1617 ctx->frame_age = frame_age;
1618 ctx->frame_flags = frame_flags;
1619 ctx->payload_offset = payload_offset;
1620 ctx->payload_len = payload_len;
1621 }
1623 if(auto_pong && (frame_flags & CURLWS_PING) && !remain) {
1624 /* auto-respond to PINGs, only works for single-frame payloads atm */
1625 CURL_TRC_WS(data, "auto PONG to [PING payload=%" FMT_OFF_T
1626 "/%" FMT_OFF_T "]", payload_offset, payload_len);
1627 /* send back the exact same content as a PONG */
1628 result = ws_enc_add_cntrl(ctx->data, ctx->ws, buf, buflen, CURLWS_PONG);
1629 if(result)
1630 return result;
1631 *pnwritten = buflen;
1632 }
1633 else {
1634 size_t write_len;
1636 ctx->written = TRUE;
1637 DEBUGASSERT(ctx->buflen >= ctx->bufidx);
1638 write_len = CURLMIN(buflen, ctx->buflen - ctx->bufidx);
1639 if(!write_len) {
1640 if(!buflen) /* 0 length write, we accept that */
1641 return CURLE_OK;
1642 return CURLE_AGAIN; /* no more space */
1643 }
1644 memcpy(ctx->buffer + ctx->bufidx, buf, write_len);
1645 ctx->bufidx += write_len;
1646 *pnwritten = write_len;
1647 }
1648 return result;
1649}
1651static CURLcode nw_in_recv(void *reader_ctx,
1652 uint8_t *buf, size_t buflen,
1653 size_t *pnread)
1654{
1655 struct Curl_easy *data = reader_ctx;
1656 return Curl_easy_recv(data, buf, buflen, pnread);
1657}
1659CURLcode curl_ws_recv(CURL *curl, void *buffer,
1660 size_t buflen, size_t *recv,
1661 const struct curl_ws_frame **metap)
1662{
1663 struct Curl_eapi_guard guard;
1664 CURLcode result = CURLE_OK;
1666 if(CURL_EAPI_ENTER(&guard, curl, ws_recv, &result)) {
1667 struct Curl_easy *data = curl;
1668 struct connectdata *conn;
1669 struct websocket *ws;
1670 struct ws_collect ctx;
1672 if(!recv || !metap || (buflen && !buffer)) {
1673 result = CURLE_BAD_FUNCTION_ARGUMENT;
1674 goto out;
1675 }
1677 *recv = 0;
1678 *metap = NULL;
1680 conn = data->conn;
1681 if(!conn) {
1682 /* Unhappy hack with lifetimes of transfers and connection */
1683 if(!data->set.connect_only) {
1684 failf(data, "[WS] CONNECT_ONLY is required");
1685 result = CURLE_UNSUPPORTED_PROTOCOL;
1686 goto out;
1687 }
1689 Curl_getconnectinfo(data, &conn);
1690 if(!conn) {
1691 failf(data, "[WS] connection not found");
1692 result = CURLE_BAD_FUNCTION_ARGUMENT;
1693 goto out;
1694 }
1695 }
1696 ws = Curl_conn_meta_get(conn, CURL_META_PROTO_WS_CONN);
1697 if(!ws) {
1698 failf(data, "[WS] connection is not setup for websocket");
1699 result = CURLE_BAD_FUNCTION_ARGUMENT;
1700 goto out;
1701 }
1703 memset(&ctx, 0, sizeof(ctx));
1704 ctx.data = data;
1705 ctx.ws = ws;
1706 ctx.buffer = buffer;
1707 ctx.buflen = buflen;
1709 while(1) {
1710 /* receive more when our buffer is empty */
1711 if(Curl_bufq_is_empty(&ws->recvbuf)) {
1712 size_t n;
1713 result = Curl_bufq_slurp(&ws->recvbuf, nw_in_recv, data, &n);
1714 if(result)
1715 goto out;
1716 else if(n == 0) {
1717 /* connection closed */
1718 infof(data, "[WS] connection expectedly closed?");
1719 result = CURLE_GOT_NOTHING;
1720 goto out;
1721 }
1722 CURL_TRC_WS(data, "curl_ws_recv, added %zu bytes from network",
1723 Curl_bufq_len(&ws->recvbuf));
1724 }
1726 result = ws_dec_pass(&ws->dec, data, &ws->recvbuf,
1727 ws_client_collect, &ctx);
1728 if(result == CURLE_AGAIN) {
1729 if(!ctx.written) {
1730 ws_dec_info(&ws->dec, data, "need more input");
1731 continue; /* nothing written, try more input */
1732 }
1733 break;
1734 }
1735 else if(result) {
1736 goto out;
1737 }
1738 else if(ctx.written) {
1739 /* The decoded frame is passed back to our caller.
1740 * There are frames like PING were we auto-respond to and
1741 * that we do not return. For these `ctx.written` is not set. */
1742 break;
1743 }
1744 }
1746 /* update frame information to be passed back */
1747 update_meta(ws, ctx.frame_age, ctx.frame_flags, ctx.payload_offset,
1748 ctx.payload_len, ctx.bufidx);
1749 *metap = &ws->recvframe;
1750 *recv = ws->recvframe.len;
1751 CURL_TRC_WS(data, "curl_ws_recv(len=%zu) -> %zu bytes (frame at %"
1752 FMT_OFF_T ", %" FMT_OFF_T " left)",
1753 buflen, *recv, ws->recvframe.offset,
1754 ws->recvframe.bytesleft);
1755 /* all's well, try to send any pending control. we do not know
1756 * when the application will call `curl_ws_send()` again. */
1757 if(!data->set.ws_raw_mode && !ws->using_reader && ws->pending.type) {
1758 CURLcode r2 = ws_enc_add_pending(data, ws);
1759 if(!r2)
1760 (void)ws_flush(data, ws, Curl_api_is_in_callback(data));
1761 }
1762 result = CURLE_OK;
1763 }
1764out:
1765 CURL_EAPI_LEAVE(&guard);
1766 return result;
1767}
1769static CURLcode ws_flush(struct Curl_easy *data, struct websocket *ws,
1770 bool blocking)
1771{
1772 CURLcode result;
1774 /* If there is space, add any pending control frame */
1775 if(Curl_bufq_len(&ws->sendbuf) < ws->sendbuf.chunk_size) {
1776 result = ws_enc_add_pending(data, ws);
1777 if(result && (result != CURLE_AGAIN))
1778 return result;
1779 }
1781 if(!Curl_bufq_is_empty(&ws->sendbuf)) {
1782 const uint8_t *out;
1783 size_t outlen, n;
1784#ifdef DEBUGBUILD
1785 /* Simulate a blocking send after this chunk has been sent */
1786 bool eagain_next = FALSE;
1787 size_t chunk_egain = 0;
1788 const char *p = getenv("CURL_WS_CHUNK_EAGAIN");
1789 if(p) {
1790 curl_off_t l;
1791 if(!curlx_str_number(&p, &l, 1 * 1024 * 1024))
1792 chunk_egain = (size_t)l;
1793 }
1794#endif
1796 while(Curl_bufq_peek(&ws->sendbuf, &out, &outlen)) {
1797#ifdef DEBUGBUILD
1798 if(eagain_next)
1799 return CURLE_AGAIN;
1800 if(chunk_egain && (outlen > chunk_egain)) {
1801 outlen = chunk_egain;
1802 eagain_next = TRUE;
1803 }
1804#endif
1805 if(blocking) {
1806 result = ws_send_raw_blocking(data, ws, (const char *)out, outlen);
1807 n = result ? 0 : outlen;
1808 }
1809 else if(data->set.connect_only || Curl_api_is_in_callback(data))
1810 result = Curl_senddata(data, out, outlen, &n);
1811 else {
1812 result = Curl_xfer_send(data, out, outlen, FALSE, &n);
1813 if(!result && !n && outlen)
1814 result = CURLE_AGAIN;
1815 }
1817 if(result == CURLE_AGAIN) {
1818 CURL_TRC_WS(data, "flush EAGAIN, %zu bytes remain in buffer",
1819 Curl_bufq_len(&ws->sendbuf));
1820 return result;
1821 }
1822 else if(result) {
1823 failf(data, "[WS] flush, write error %d", (int)result);
1824 return result;
1825 }
1826 else {
1827 CURL_TRC_WS(data, "flushed %zu bytes", n);
1828 Curl_bufq_skip(&ws->sendbuf, n);
1829 }
1830 }
1831 }
1832 return CURLE_OK;
1833}
1835static CURLcode ws_send_raw_blocking(struct Curl_easy *data,
1836 struct websocket *ws,
1837 const char *buffer, size_t buflen)
1838{
1839 CURLcode result = CURLE_OK;
1840 size_t nwritten;
1842 if(!data)
1843 return result;
1845 (void)ws;
1846 while(buflen) {
1847 result = Curl_xfer_send(data, buffer, buflen, FALSE, &nwritten);
1848 if(result)
1849 return result;
1850 DEBUGASSERT(nwritten <= buflen);
1851 buffer += nwritten;
1852 buflen -= nwritten;
1853 if(buflen) {
1854 curl_socket_t sock = data->conn->sock[FIRSTSOCKET];
1855 timediff_t left_ms;
1856 int ev;
1858 CURL_TRC_WS(data, "ws_send_raw_blocking() partial, %zu left to send",
1859 buflen);
1860 left_ms = Curl_timeleft_ms(data);
1861 if(left_ms < 0) {
1862 failf(data, "[WS] Timeout waiting for socket becoming writable");
1863 return CURLE_SEND_ERROR;
1864 }
1866 /* POLLOUT socket */
1867 if(sock == CURL_SOCKET_BAD)
1868 return CURLE_SEND_ERROR;
1869 ev = SOCKET_WRITABLE(sock, left_ms ? left_ms : 500);
1870 if(ev < 0) {
1871 failf(data, "[WS] Error while waiting for socket becoming writable");
1872 return CURLE_SEND_ERROR;
1873 }
1874 }
1875 }
1876 return result;
1877}
1879static CURLcode ws_send_raw(struct Curl_easy *data, const void *buffer,
1880 size_t buflen, size_t *pnwritten)
1881{
1882 struct websocket *ws;
1883 CURLcode result;
1885 ws = Curl_conn_meta_get(data->conn, CURL_META_PROTO_WS_CONN);
1886 if(!ws) {
1887 failf(data, "[WS] Not a websocket transfer");
1888 return CURLE_SEND_ERROR;
1889 }
1890 if(!buflen)
1891 return CURLE_OK;
1893 if(Curl_api_is_in_callback(data)) {
1894 /* When invoked from inside callbacks, we do a blocking send as the
1895 * callback will probably not implement partial writes that may then
1896 * mess up the ws framing subsequently.
1897 * We need any pending data to be flushed before sending. */
1898 result = ws_flush(data, ws, TRUE);
1899 if(result)
1900 return result;
1901 result = ws_send_raw_blocking(data, ws, buffer, buflen);
1902 if(!result)
1903 *pnwritten = buflen;
1904 }
1905 else {
1906 /* We need any pending data to be sent or EAGAIN this call. */
1907 result = ws_flush(data, ws, FALSE);
1908 if(result)
1909 return result;
1910 result = Curl_senddata(data, buffer, buflen, pnwritten);
1911 }
1913 CURL_TRC_WS(data, "ws_send_raw(len=%zu) -> %d, %zu",
1914 buflen, (int)result, *pnwritten);
1915 return result;
1916}
1918CURLcode curl_ws_send(CURL *curl, const void *buffer_arg,
1919 size_t buflen, size_t *sent,
1920 curl_off_t fragsize,
1921 unsigned int flags)
1922{
1923 struct Curl_eapi_guard guard;
1924 CURLcode result = CURLE_OK;
1926 if(CURL_EAPI_ENTER(&guard, curl, ws_send, &result)) {
1927 struct websocket *ws;
1928 const uint8_t *buffer = buffer_arg;
1929 struct Curl_easy *data = curl;
1930 size_t ndummy;
1931 size_t *pnsent = sent ? sent : &ndummy;
1933 CURL_TRC_WS(data, "curl_ws_send(len=%zu, fragsize=%" FMT_OFF_T
1934 ", flags=%x), raw=%d",
1935 buflen, fragsize, flags, data->set.ws_raw_mode);
1937 *pnsent = 0;
1939 if(!buffer && buflen) {
1940 failf(data, "[WS] buffer is NULL when buflen is not");
1941 result = CURLE_BAD_FUNCTION_ARGUMENT;
1942 goto out;
1943 }
1945 if(!data->conn && data->set.connect_only) {
1946 result = Curl_connect_only_attach(data);
1947 if(result)
1948 goto out;
1949 }
1950 if(!data->conn) {
1951 failf(data, "[WS] No associated connection");
1952 result = CURLE_SEND_ERROR;
1953 goto out;
1954 }
1955 ws = Curl_conn_meta_get(data->conn, CURL_META_PROTO_WS_CONN);
1956 if(!ws) {
1957 failf(data, "[WS] Not a websocket transfer");
1958 result = CURLE_SEND_ERROR;
1959 goto out;
1960 }
1962 if(data->set.ws_raw_mode) {
1963 /* In raw mode, we write directly to the connection */
1964 /* try flushing any content still waiting to be sent. */
1965 result = ws_flush(data, ws, FALSE);
1966 if(result)
1967 goto out;
1969 if(!buffer) {
1970 failf(data, "[WS] buffer is NULL in raw mode");
1971 result = CURLE_BAD_FUNCTION_ARGUMENT;
1972 goto out;
1973 }
1974 if(!sent) {
1975 failf(data, "[WS] sent is NULL in raw mode");
1976 result = CURLE_BAD_FUNCTION_ARGUMENT;
1977 goto out;
1978 }
1979 if(fragsize || flags) {
1980 failf(data, "[WS] fragsize and flags must be zero in raw mode");
1981 result = CURLE_BAD_FUNCTION_ARGUMENT;
1982 goto out;
1983 }
1984 result = ws_send_raw(data, buffer, buflen, pnsent);
1985 goto out;
1986 }
1988 /* Not RAW mode, we do the frame encoding */
1989 result = ws_enc_send(data, ws, buffer, buflen, fragsize, flags, pnsent);
1990 CURL_TRC_WS(data, "curl_ws_send(len=%zu, fragsize=%" FMT_OFF_T
1991 ", flags=%x, raw=%d) -> %d, %zu",
1992 buflen, fragsize, flags, data->set.ws_raw_mode, (int)result,
1993 *pnsent);
1994 }
1995out:
1996 CURL_EAPI_LEAVE(&guard);
1997 return result;
1998}
2000static CURLcode ws_setup_conn(struct Curl_easy *data,
2001 struct connectdata *conn)
2002{
2003 (void)conn;
2004 /* WebSocket is 1.1 only (for now) */
2005 data->state.http_neg.accept_09 = FALSE;
2006 data->state.http_neg.only_10 = FALSE;
2007 data->state.http_neg.wanted = CURL_HTTP_V1x;
2008 data->state.http_neg.allowed = CURL_HTTP_V1x;
2009 return Curl_http_setup_conn(data, conn);
2010}
2012const struct curl_ws_frame *curl_ws_meta(CURL *curl)
2013{
2014 /* we only return something for websocket, called from within the callback
2015 when not using raw mode */
2016 struct Curl_easy *data = curl;
2017 if(GOOD_EASY_HANDLE(data) && Curl_api_is_in_callback(data) &&
2018 data->conn && !data->set.ws_raw_mode) {
2019 struct websocket *ws;
2020 ws = Curl_conn_meta_get(data->conn, CURL_META_PROTO_WS_CONN);
2021 if(ws)
2022 return &ws->recvframe;
2023 }
2024 return NULL;
2025}
2027CURL_EXTERN CURLcode curl_ws_start_frame(CURL *curl,
2028 unsigned int flags,
2029 curl_off_t frame_len)
2030{
2031 struct Curl_eapi_guard guard;
2032 CURLcode result = CURLE_OK;
2034 if(CURL_EAPI_ENTER(&guard, curl, ws_start_frame, &result)) {
2035 struct Curl_easy *data = curl;
2036 struct websocket *ws;
2038 if(data->set.ws_raw_mode) {
2039 failf(data, "cannot curl_ws_start_frame() with CURLWS_RAW_MODE enabled");
2040 result = CURLE_FAILED_INIT;
2041 goto out;
2042 }
2044 CURL_TRC_WS(data, "curl_ws_start_frame(flags=%x, frame_len=%" FMT_OFF_T,
2045 flags, frame_len);
2047 if(!data->conn) {
2048 failf(data, "[WS] No associated connection");
2049 result = CURLE_SEND_ERROR;
2050 goto out;
2051 }
2052 ws = Curl_conn_meta_get(data->conn, CURL_META_PROTO_WS_CONN);
2053 if(!ws) {
2054 failf(data, "[WS] Not a websocket transfer");
2055 result = CURLE_SEND_ERROR;
2056 goto out;
2057 }
2059 if(ws->enc.payload_remain) {
2060 failf(data, "[WS] previous frame not finished");
2061 result = CURLE_SEND_ERROR;
2062 goto out;
2063 }
2065 result = ws_enc_write_head(data, ws, &ws->enc, flags, frame_len,
2066 &ws->sendbuf);
2067 if(result)
2068 CURL_TRC_WS(data, "curl_start_frame(), error adding frame head %d",
2069 (int)result);
2070 }
2071out:
2072 CURL_EAPI_LEAVE(&guard);
2073 return result;
2074}
2076const struct Curl_protocol Curl_protocol_ws = {
2077 ws_setup_conn, /* setup_connection */
2078 Curl_http_setup_filters, /* setup_filters */
2079 Curl_http, /* do_it */
2080 Curl_http_done, /* done */
2081 ZERO_NULL, /* do_more */
2082 ZERO_NULL, /* connect_it */
2083 ZERO_NULL, /* connecting */
2084 ZERO_NULL, /* doing */
2085 ZERO_NULL, /* proto_pollset */
2086 Curl_http_doing_pollset, /* doing_pollset */
2087 ZERO_NULL, /* domore_pollset */
2088 Curl_http_perform_pollset, /* perform_pollset */
2089 ZERO_NULL, /* disconnect */
2090 Curl_http_write_resp, /* write_resp */
2091 Curl_http_write_resp_hd, /* write_resp_hd */
2092 ZERO_NULL, /* connection_is_dead */
2093 ZERO_NULL, /* attach connection */
2094 Curl_http_follow, /* follow */
2095};
2097#else
2099CURLcode curl_ws_recv(CURL *curl, void *buffer, size_t buflen,
2100 size_t *recv,
2101 const struct curl_ws_frame **metap)
2102{
2103 (void)curl;
2104 (void)buffer;
2105 (void)buflen;
2106 (void)recv;
2107 (void)metap;
2108 return CURLE_NOT_BUILT_IN;
2109}
2111CURLcode curl_ws_send(CURL *curl, const void *buffer,
2112 size_t buflen, size_t *sent,
2113 curl_off_t fragsize,
2114 unsigned int flags)
2115{
2116 (void)curl;
2117 (void)buffer;
2118 (void)buflen;
2119 (void)sent;
2120 (void)fragsize;
2121 (void)flags;
2122 return CURLE_NOT_BUILT_IN;
2123}
2125const struct curl_ws_frame *curl_ws_meta(CURL *data)
2126{
2127 (void)data;
2128 return NULL;
2129}
2131CURL_EXTERN CURLcode curl_ws_start_frame(CURL *curl,
2132 unsigned int flags,
2133 curl_off_t frame_len)
2134{
2135 (void)curl;
2136 (void)flags;
2137 (void)frame_len;
2138 return CURLE_NOT_BUILT_IN;
2139}
2141#endif /* !CURL_DISABLE_WEBSOCKETS */
Diagnostics4 git calls · 31 ms
CallStatusSizeTime031 ms
discover200152 B2 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=2 git.response.bytes=152 git.server.agent=gitty/1.0 git.server.object_format=sha1 git.server.caps=agent ls-refs fetch object-format git.server.fetch=shallow filter sideband-all git.protocol.version=2 git.pkt.frames=8 git.pkt.data=6 git.pkt.flush=2 git.pkt.delim=0 git.pkt.bytes=152 git.pkt.payload.max=34
ls-refs200149 B · hit2 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=2 git.response.bytes=149 git.response.cache=HIT git.response.duration_ms=2 git.protocol.version=2 git.pkt.frames=3 git.pkt.data=2 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=149 git.pkt.payload.max=78 git.ls_refs.count=2 git.ls_refs.head=refs/heads/master
fetchblob:none · deepen 10200287 KiB · hit4 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=4 git.response.bytes=293470 git.response.cache=HIT git.response.duration_ms=4 git.fetch.filter=blob:none git.fetch.filter.requested=tree:0 git.fetch.filter.fallback=blob:none git.fetch.filter.learned=false git.fetch.wants=31c911efe5652725e930f4d2e60c9060e5f6646d git.fetch.haves.count=0 git.fetch.deepen=10 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=10 git.pkt.data=8 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=293470 git.pkt.payload.max=65516 git.sideband.band1.bytes=293354 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=87 git.pack.bytes=293354 git.pack.ofs_delta=0 git.pack.ref_delta=1 git.pack.chain.max=1 git.pack.trailer=6a646bcda6740bab42e321b51998b52ea15146c0 git.pack.full=86Open pack map
fetch20017 KiB · hit25 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=25 git.response.bytes=17625 git.response.cache=HIT git.response.duration_ms=25 git.fetch.wants=74d6ef0678592592ba63d67a7302745ae4e5efa9 git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=3 git.pkt.data=2 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=17625 git.pkt.payload.max=17604 git.sideband.band1.bytes=17603 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0
Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.
- Remote
- https://5ad2236b39de4c8bd8f6270ea63f3ea9.artifacts.cloudflare.net/git/public-v0/curl.git
- Ref
- refs/heads/master
- Commit
- 31c911efe5652725e930f4d2e60c9060e5f6646d
- cf-ray
- a5e19f7f59d63cd0
- Request
- 0d1bf600…
- Protocol
- v2 · sha1
- Agent
- gitty/1.0
- Filter
- advertised
- Fetch
- shallow filter sideband-all
- Capabilities
- agent ls-refs fetch object-format