Coverage Report

Created: 2026-10-15 06:17

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