Coverage Report

Created: 2026-10-15 06:20

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
220
#define WSBIT_FIN          0x80
56
21
#define WSBIT_RSV1         0x40
57
21
#define WSBIT_RSV2         0x20
58
21
#define WSBIT_RSV3         0x10
59
21
#define WSBIT_RSV_MASK     (WSBIT_RSV1 | WSBIT_RSV2 | WSBIT_RSV3)
60
1.11k
#define WSBIT_OPCODE_CONT  0x0
61
63
#define WSBIT_OPCODE_TEXT  0x1
62
140
#define WSBIT_OPCODE_BIN   0x2
63
19
#define WSBIT_OPCODE_CLOSE 0x8
64
55
#define WSBIT_OPCODE_PING  0x9
65
82
#define WSBIT_OPCODE_PONG  0xa
66
#ifdef CURLVERBOSE
67
0
#define WSBIT_OPCODE_MASK  0xf
68
#endif
69
70
1.44k
#define WSBIT_MASK 0x80
71
72
/* buffer dimensioning */
73
376
#define WS_CHUNK_SIZE  65535
74
376
#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
189
#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
1.44k
{
154
1.44k
  switch(firstbyte) {
155
  /* 0x00 - intermediate TEXT/BINARY fragment */
156
1.08k
  case WSBIT_OPCODE_CONT:
157
1.08k
    if(!(cont_flags & CURLWS_CONT)) {
158
3
      failf(data, "[WS] no ongoing fragmented message to resume");
159
3
      return 0;
160
3
    }
161
1.08k
    return cont_flags | CURLWS_CONT;
162
  /* 0x80 - final TEXT/BIN fragment */
163
22
  case (WSBIT_OPCODE_CONT | WSBIT_FIN):
164
22
    if(!(cont_flags & CURLWS_CONT)) {
165
2
      failf(data, "[WS] no ongoing fragmented message to resume");
166
2
      return 0;
167
2
    }
168
20
    return cont_flags & ~CURLWS_CONT;
169
  /* 0x01 - first TEXT fragment */
170
45
  case WSBIT_OPCODE_TEXT:
171
45
    if(cont_flags & CURLWS_CONT) {
172
3
      failf(data, "[WS] fragmented message interrupted by new TEXT msg");
173
3
      return 0;
174
3
    }
175
42
    return CURLWS_TEXT | CURLWS_CONT;
176
  /* 0x81 - unfragmented TEXT msg */
177
18
  case (WSBIT_OPCODE_TEXT | WSBIT_FIN):
178
18
    if(cont_flags & CURLWS_CONT) {
179
2
      failf(data, "[WS] fragmented message interrupted by new TEXT msg");
180
2
      return 0;
181
2
    }
182
16
    return CURLWS_TEXT;
183
  /* 0x02 - first BINARY fragment */
184
113
  case WSBIT_OPCODE_BIN:
185
113
    if(cont_flags & CURLWS_CONT) {
186
1
      failf(data, "[WS] fragmented message interrupted by new BINARY msg");
187
1
      return 0;
188
1
    }
189
112
    return CURLWS_BINARY | CURLWS_CONT;
190
  /* 0x82 - unfragmented BINARY msg */
191
15
  case (WSBIT_OPCODE_BIN | WSBIT_FIN):
192
15
    if(cont_flags & CURLWS_CONT) {
193
1
      failf(data, "[WS] fragmented message interrupted by new BINARY msg");
194
1
      return 0;
195
1
    }
196
14
    return CURLWS_BINARY;
197
  /* 0x08 - first CLOSE fragment */
198
1
  case WSBIT_OPCODE_CLOSE:
199
1
    failf(data, "[WS] invalid fragmented CLOSE frame");
200
1
    return 0;
201
  /* 0x88 - unfragmented CLOSE */
202
18
  case (WSBIT_OPCODE_CLOSE | WSBIT_FIN):
203
18
    return CURLWS_CLOSE;
204
  /* 0x09 - first PING fragment */
205
1
  case WSBIT_OPCODE_PING:
206
1
    failf(data, "[WS] invalid fragmented PING frame");
207
1
    return 0;
208
  /* 0x89 - unfragmented PING */
209
54
  case (WSBIT_OPCODE_PING | WSBIT_FIN):
210
54
    return CURLWS_PING;
211
  /* 0x0a - first PONG fragment */
212
1
  case WSBIT_OPCODE_PONG:
213
1
    failf(data, "[WS] invalid fragmented PONG frame");
214
1
    return 0;
215
  /* 0x8a - unfragmented PONG */
216
48
  case (WSBIT_OPCODE_PONG | WSBIT_FIN):
217
48
    return CURLWS_PONG;
218
  /* invalid first byte */
219
21
  default:
220
21
    if(firstbyte & WSBIT_RSV_MASK)
221
      /* any of the reserved bits 0x40/0x20/0x10 are set */
222
19
      failf(data, "[WS] invalid reserved bits: %02x", firstbyte);
223
2
    else
224
      /* any of the reserved opcodes 0x3-0x7 or 0xb-0xf is used */
225
2
      failf(data, "[WS] invalid opcode: %02x", firstbyte);
226
21
    return 0;
227
1.44k
  }
228
1.44k
}
229
230
static CURLcode ws_frame_flags2firstbyte(struct Curl_easy *data,
231
                                         unsigned int flags,
232
                                         bool contfragment,
233
                                         uint8_t *pfirstbyte)
234
45
{
235
45
  *pfirstbyte = 0;
236
45
  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
12
  case CURLWS_BINARY:
263
12
    *pfirstbyte = contfragment ? (WSBIT_OPCODE_CONT | WSBIT_FIN)
264
12
                               : (WSBIT_OPCODE_BIN | WSBIT_FIN);
265
12
    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
33
  case CURLWS_PONG:
282
33
    *pfirstbyte = WSBIT_OPCODE_PONG | WSBIT_FIN;
283
33
    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
45
  }
291
45
}
292
293
static void ws_dec_info(struct ws_decoder *dec, struct Curl_easy *data,
294
                        const char *msg)
295
1.82k
{
296
1.82k
  NOVERBOSE((void)msg);
297
1.82k
  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
1.82k
  default:
306
1.82k
    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
1.82k
    else {
313
1.82k
      CURL_TRC_WS(data, "decoded %s [%s%s payload=%"
314
1.82k
                  FMT_OFF_T "/%" FMT_OFF_T "]",
315
1.82k
                  msg, ws_frame_name_of_op(dec->head[0]),
316
1.82k
                  (dec->head[0] & WSBIT_FIN) ? "" : " NON-FINAL",
317
1.82k
                  dec->payload_offset, dec->payload_len);
318
1.82k
    }
319
1.82k
    break;
320
1.82k
  }
321
1.82k
}
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
1.44k
{
336
1.44k
  dec->frame_age = 0;
337
1.44k
  dec->frame_flags = 0;
338
1.44k
  dec->payload_offset = 0;
339
1.44k
  dec->payload_len = 0;
340
1.44k
  dec->head_len = dec->head_total = 0;
341
1.44k
  dec->state = WS_DEC_INIT;
342
  /* dec->cont_flags must be carried over to next frame */
343
1.44k
}
344
345
static void ws_dec_reset(struct ws_decoder *dec)
346
230
{
347
230
  dec->frame_age = 0;
348
230
  dec->frame_flags = 0;
349
230
  dec->payload_offset = 0;
350
230
  dec->payload_len = 0;
351
230
  dec->head_len = dec->head_total = 0;
352
230
  dec->state = WS_DEC_INIT;
353
230
  dec->cont_flags = 0;
354
230
}
355
356
static void ws_dec_init(struct ws_decoder *dec)
357
188
{
358
188
  ws_dec_reset(dec);
359
188
}
360
361
static CURLcode ws_dec_read_head(struct ws_decoder *dec,
362
                                 struct Curl_easy *data,
363
                                 struct bufq *inraw)
364
1.46k
{
365
1.46k
  const uint8_t *inbuf;
366
1.46k
  size_t inlen;
367
368
4.15k
  while(Curl_bufq_peek(inraw, &inbuf, &inlen)) {
369
4.11k
    if(dec->head_len == 0) {
370
1.44k
      dec->head[0] = *inbuf;
371
1.44k
      Curl_bufq_skip(inraw, 1);
372
373
1.44k
      dec->frame_flags = ws_frame_firstbyte2flags(data, dec->head[0],
374
1.44k
                                                  dec->cont_flags);
375
1.44k
      if(!dec->frame_flags) {
376
36
        ws_dec_reset(dec);
377
36
        return CURLE_RECV_ERROR;
378
36
      }
379
380
      /* fragmentation only applies to data frames (text/binary);
381
       * control frames (close/ping/pong) do not affect the CONT status */
382
1.40k
      if(dec->frame_flags & (CURLWS_TEXT | CURLWS_BINARY)) {
383
1.28k
        dec->cont_flags = dec->frame_flags;
384
1.28k
      }
385
386
1.40k
      dec->head_len = 1;
387
#if 0
388
      ws_dec_info(dec, data, "seeing opcode");
389
#endif
390
1.40k
      continue;
391
1.44k
    }
392
2.66k
    else if(dec->head_len == 1) {
393
1.40k
      dec->head[1] = *inbuf;
394
1.40k
      Curl_bufq_skip(inraw, 1);
395
1.40k
      dec->head_len = 2;
396
397
1.40k
      if(dec->head[1] & WSBIT_MASK) {
398
        /* A client MUST close a connection if it detects a masked frame. */
399
3
        failf(data, "[WS] masked input frame");
400
3
        ws_dec_reset(dec);
401
3
        return CURLE_RECV_ERROR;
402
3
      }
403
1.39k
      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
1
        failf(data, "[WS] received PING frame is too big");
407
1
        ws_dec_reset(dec);
408
1
        return CURLE_RECV_ERROR;
409
1
      }
410
1.39k
      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
1
        failf(data, "[WS] received PONG frame is too big");
413
1
        ws_dec_reset(dec);
414
1
        return CURLE_RECV_ERROR;
415
1
      }
416
1.39k
      if(dec->frame_flags & CURLWS_CLOSE && dec->head[1] > WS_MAX_CNTRL_LEN) {
417
1
        failf(data, "[WS] received CLOSE frame is too big");
418
1
        ws_dec_reset(dec);
419
1
        return CURLE_RECV_ERROR;
420
1
      }
421
422
      /* How long is the frame head? */
423
1.39k
      if(dec->head[1] == 126) {
424
10
        dec->head_total = 4;
425
10
        continue;
426
10
      }
427
1.38k
      else if(dec->head[1] == 127) {
428
161
        dec->head_total = 10;
429
161
        continue;
430
161
      }
431
1.22k
      else {
432
1.22k
        dec->head_total = 2;
433
1.22k
      }
434
1.39k
    }
435
436
2.49k
    if(dec->head_len < dec->head_total) {
437
1.26k
      dec->head[dec->head_len] = *inbuf;
438
1.26k
      Curl_bufq_skip(inraw, 1);
439
1.26k
      ++dec->head_len;
440
1.26k
      if(dec->head_len < dec->head_total) {
441
#if 0
442
        ws_dec_info(dec, data, "decoding head");
443
#endif
444
1.10k
        continue;
445
1.10k
      }
446
1.26k
    }
447
    /* got the complete frame head */
448
1.38k
    DEBUGASSERT(dec->head_len == dec->head_total);
449
1.38k
    switch(dec->head_total) {
450
1.22k
    case 2:
451
1.22k
      dec->payload_len = dec->head[1];
452
1.22k
      break;
453
10
    case 4:
454
10
      dec->payload_len = (dec->head[2] << 8) | dec->head[3];
455
10
      break;
456
150
    case 10:
457
150
      if(dec->head[2] > 127) {
458
1
        failf(data, "[WS] frame length longer than 63 bits not supported");
459
1
        return CURLE_RECV_ERROR;
460
1
      }
461
149
      dec->payload_len =
462
149
        (curl_off_t)dec->head[2] << 56 |
463
149
        (curl_off_t)dec->head[3] << 48 |
464
149
        (curl_off_t)dec->head[4] << 40 |
465
149
        (curl_off_t)dec->head[5] << 32 |
466
149
        (curl_off_t)dec->head[6] << 24 |
467
149
        (curl_off_t)dec->head[7] << 16 |
468
149
        (curl_off_t)dec->head[8] <<  8 |
469
149
        dec->head[9];
470
149
      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
1.38k
    }
477
478
1.38k
    dec->frame_age = 0;
479
1.38k
    dec->payload_offset = 0;
480
1.38k
    ws_dec_info(dec, data, "head");
481
1.38k
    return CURLE_OK;
482
1.38k
  }
483
37
  return CURLE_AGAIN;
484
1.46k
}
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
442
{
492
442
  const uint8_t *inbuf;
493
442
  size_t inlen;
494
442
  size_t nwritten;
495
442
  CURLcode result;
496
442
  size_t remain = curlx_sotouz_range(dec->payload_len - dec->payload_offset,
497
442
                                     0, SIZE_MAX);
498
499
882
  while(remain && Curl_bufq_peek(inraw, &inbuf, &inlen) &&
500
441
        !Curl_cwriter_is_paused(data)) {
501
441
    if(inlen > remain)
502
240
      inlen = remain;
503
441
    result = write_cb(inbuf, inlen, dec->frame_age, dec->frame_flags,
504
441
                      dec->payload_offset, dec->payload_len,
505
441
                      write_ctx, &nwritten);
506
441
    if(result)
507
1
      return result;
508
440
    Curl_bufq_skip(inraw, nwritten);
509
440
    dec->payload_offset += nwritten;
510
440
    remain = curlx_sotouz_range(dec->payload_len - dec->payload_offset,
511
440
                                0, SIZE_MAX);
512
440
    CURL_TRC_WS(data, "passed %zu bytes payload, %zu remain",
513
440
                nwritten, remain);
514
440
  }
515
516
441
  return remain ? CURLE_AGAIN : CURLE_OK;
517
442
}
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
1.55k
{
525
1.55k
  CURLcode result;
526
527
1.55k
  if(Curl_bufq_is_empty(inraw))
528
0
    return CURLE_AGAIN;
529
530
1.55k
  switch(dec->state) {
531
1.44k
  case WS_DEC_INIT:
532
1.44k
    ws_dec_next_frame(dec);
533
1.44k
    dec->state = WS_DEC_HEAD;
534
1.44k
    FALLTHROUGH();
535
1.46k
  case WS_DEC_HEAD:
536
1.46k
    result = ws_dec_read_head(dec, data, inraw);
537
1.46k
    if(result) {
538
80
      if(result != CURLE_AGAIN) {
539
43
        failf(data, "[WS] decode frame error %d", (int)result);
540
43
        break;  /* real error */
541
43
      }
542
      /* incomplete ws frame head */
543
37
      DEBUGASSERT(Curl_bufq_is_empty(inraw));
544
37
      break;
545
37
    }
546
    /* head parsing done */
547
1.38k
    dec->state = WS_DEC_PAYLOAD;
548
1.38k
    if(dec->payload_len == 0) {
549
1.03k
      size_t nwritten;
550
1.03k
      const uint8_t tmp = '\0';
551
      /* special case of a 0 length frame, need to write once */
552
1.03k
      result = write_cb(&tmp, 0, dec->frame_age, dec->frame_flags,
553
1.03k
                        0, 0, write_ctx, &nwritten);
554
1.03k
      if(result)
555
0
        return result;
556
1.03k
      dec->state = WS_DEC_INIT;
557
1.03k
      break;
558
1.03k
    }
559
352
    FALLTHROUGH();
560
442
  case WS_DEC_PAYLOAD:
561
442
    result = ws_dec_pass_payload(dec, data, inraw, write_cb, write_ctx);
562
442
    ws_dec_info(dec, data, "passing");
563
442
    if(result)
564
198
      return result;
565
    /* payload parsing done */
566
244
    dec->state = WS_DEC_INIT;
567
244
    break;
568
0
  default:
569
    /* we covered all enums above, but some code analyzers are wimps */
570
0
    result = CURLE_FAILED_INIT;
571
1.55k
  }
572
1.35k
  return result;
573
1.55k
}
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
1.42k
{
581
1.42k
  curl_off_t bytesleft = (payload_len - payload_offset - cur_len);
582
583
1.42k
  ws->recvframe.age = frame_age;
584
1.42k
  ws->recvframe.flags = frame_flags;
585
1.42k
  ws->recvframe.offset = payload_offset;
586
1.42k
  ws->recvframe.len = cur_len;
587
1.42k
  ws->recvframe.bytesleft = bytesleft;
588
1.42k
}
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
188
{
599
188
  struct ws_cw_ctx *ctx = writer->ctx;
600
188
  (void)data;
601
188
  Curl_bufq_init2(&ctx->buf, WS_CHUNK_SIZE, 1, BUFQ_OPT_SOFT_LIMIT);
602
188
  return CURLE_OK;
603
188
}
604
605
static void ws_cw_close(struct Curl_easy *data, struct Curl_cwriter *writer)
606
188
{
607
188
  struct ws_cw_ctx *ctx = writer->ctx;
608
188
  (void)data;
609
188
  Curl_bufq_free(&ctx->buf);
610
188
}
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
43
{
630
43
  (void)data;
631
43
  DEBUGASSERT(plen <= WS_MAX_CNTRL_LEN);
632
43
  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
43
  ws->pending.type = frame_type;
638
43
  ws->pending.payload_len = plen;
639
43
  memcpy(ws->pending.payload, payload, plen);
640
43
  return CURLE_OK;
641
43
}
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
1.47k
{
647
1.47k
  curl_off_t buffered, remain = payload_total - payload_offset;
648
1.47k
  if((payload_total < 0) || (payload_offset < 0) || (remain < 0))
649
0
    return -1;
650
1.47k
  buffered = curlx_uztoso(payload_buffered);
651
1.47k
  if(remain < buffered)
652
0
    return -1;
653
1.47k
  return remain - buffered;
654
1.47k
}
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
1.47k
{
663
1.47k
  struct ws_cw_dec_ctx *ctx = user_data;
664
1.47k
  struct Curl_easy *data = ctx->data;
665
1.47k
  struct websocket *ws = ctx->ws;
666
1.47k
  bool auto_pong = !data->set.ws_raw_mode && !data->set.ws_no_auto_pong;
667
1.47k
  curl_off_t remain;
668
1.47k
  CURLcode result;
669
670
1.47k
  (void)frame_age;
671
1.47k
  *pnwritten = 0;
672
1.47k
  remain = ws_payload_remain(payload_len, payload_offset, buflen);
673
1.47k
  if(remain < 0) {
674
0
    DEBUGASSERT(0); /* parameter mismatch */
675
0
    return CURLE_BAD_FUNCTION_ARGUMENT;
676
0
  }
677
678
1.47k
  if(auto_pong && (frame_flags & CURLWS_PING) && !remain) {
679
    /* auto-respond to PINGs, only works for single-frame payloads atm */
680
43
    CURL_TRC_WS(data, "auto PONG to [PING payload=%" FMT_OFF_T
681
43
                "/%" FMT_OFF_T "]", payload_offset, payload_len);
682
    /* send back the exact same content as a PONG */
683
43
    result = ws_enc_add_cntrl(data, ws, buf, buflen, CURLWS_PONG);
684
43
    if(result)
685
0
      return result;
686
43
  }
687
1.42k
  else if(buflen || !remain) {
688
    /* forward the decoded frame to the next client writer. */
689
1.42k
    update_meta(ws, frame_age, frame_flags, payload_offset,
690
1.42k
                payload_len, buflen);
691
692
1.42k
    CURL_TRC_WRITE(data, "[WS] pass %zu decoded bytes", buflen);
693
1.42k
    result = Curl_cwriter_write(data, ctx->next_writer,
694
1.42k
                                (ctx->cw_type | CLIENTWRITE_0LEN),
695
1.42k
                                (const char *)buf, buflen);
696
1.42k
    if(result)
697
1
      return result;
698
1.42k
  }
699
1.47k
  *pnwritten = buflen;
700
1.47k
  return CURLE_OK;
701
1.47k
}
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
434
{
707
434
  struct ws_cw_ctx *ctx = writer->ctx;
708
434
  struct websocket *ws;
709
434
  CURLcode result = CURLE_OK;
710
711
434
  CURL_TRC_WRITE(data, "[WS] write(len=%zu, type=%d)", nbytes, type);
712
434
  if(!(type & CLIENTWRITE_BODY) || data->set.ws_raw_mode)
713
23
    return Curl_cwriter_write(data, writer->next, type, buf, nbytes);
714
715
411
  ws = Curl_conn_meta_get(data->conn, CURL_META_PROTO_WS_CONN);
716
411
  if(!ws) {
717
0
    failf(data, "[WS] not a websocket transfer");
718
0
    return CURLE_FAILED_INIT;
719
0
  }
720
721
411
  if(nbytes) {
722
285
    size_t nwritten;
723
285
    result = Curl_bufq_write(&ctx->buf, (const uint8_t *)buf,
724
285
                             nbytes, &nwritten);
725
285
    if(result) {
726
0
      infof(data, "[WS] error adding data to buffer %d", (int)result);
727
0
      return result;
728
0
    }
729
285
  }
730
731
411
  result = Curl_cwriter_flush(data, writer->next);
732
411
  if(result)
733
0
    goto out;
734
735
1.68k
  while(!Curl_bufq_is_empty(&ctx->buf) && !Curl_cwriter_is_paused(data)) {
736
1.55k
    struct ws_cw_dec_ctx pass_ctx;
737
1.55k
    pass_ctx.data = data;
738
1.55k
    pass_ctx.ws = ws;
739
1.55k
    pass_ctx.next_writer = writer->next;
740
1.55k
    pass_ctx.cw_type = type;
741
1.55k
    result = ws_dec_pass(&ws->dec, data, &ctx->buf,
742
1.55k
                         ws_cw_dec_next, &pass_ctx);
743
1.55k
    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
234
      result = CURLE_OK;
747
234
      goto out;
748
234
    }
749
1.31k
    else if(result) {
750
44
      failf(data, "[WS] decode payload error %d", (int)result);
751
44
      Curl_bufq_reset(&ctx->buf);
752
44
      goto out;
753
44
    }
754
1.55k
  }
755
756
411
out:
757
411
  if(!result && !ws->using_reader) {
758
331
    result = ws_flush(data, ws, Curl_api_is_in_callback(data));
759
331
    if(result == CURLE_AGAIN)
760
0
      result = CURLE_OK;
761
331
  }
762
763
411
  if(!result && (type & CLIENTWRITE_EOS) &&
764
126
     (!Curl_bufq_is_empty(&ctx->buf) || (ws->dec.state != WS_DEC_INIT))) {
765
121
    failf(data, "[WS] decode ended with incomplete frame");
766
121
    result = CURLE_RECV_ERROR;
767
121
  }
768
411
  return result;
769
411
}
770
771
static CURLcode ws_cw_flush(struct Curl_easy *data,
772
                            struct Curl_cwriter *writer)
773
188
{
774
188
  CURLcode result = CURLE_OK;
775
776
188
  CURL_TRC_WRITE(data, "[ws] flush");
777
188
  if(!data->set.ws_raw_mode) {
778
181
    struct ws_cw_ctx *ctx = writer->ctx;
779
181
    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
181
    result = Curl_cwriter_flush(data, writer->next);
785
181
    if(result)
786
0
      goto out;
787
788
181
    ws = Curl_conn_meta_get(data->conn, CURL_META_PROTO_WS_CONN);
789
181
    if(!ws) {
790
0
      failf(data, "[WS] not a websocket transfer");
791
0
      return CURLE_FAILED_INIT;
792
0
    }
793
794
181
    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
181
  }
815
816
188
out:
817
188
  if(!result)
818
188
    result = Curl_cwriter_flush(data, writer->next);
819
188
  return result;
820
188
}
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
90
{
837
90
  NOVERBOSE((void)enc);
838
90
  NOVERBOSE((void)msg);
839
90
  CURL_TRC_WS(data, "WS-ENC: %s [%s%s payload=%"
840
90
              FMT_OFF_T "/%" FMT_OFF_T "]",
841
90
              msg, ws_frame_name_of_op(enc->firstbyte),
842
90
              (enc->firstbyte & WSBIT_FIN) ? "" : " NON-FIN",
843
90
              enc->payload_len - enc->payload_remain, enc->payload_len);
844
90
}
845
846
static void ws_enc_reset(struct ws_encoder *enc)
847
188
{
848
188
  enc->payload_remain = 0;
849
188
  enc->xori = 0;
850
188
  enc->contfragment = FALSE;
851
188
}
852
853
static void ws_enc_init(struct ws_encoder *enc)
854
188
{
855
188
  ws_enc_reset(enc);
856
188
}
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
45
{
886
45
  uint8_t firstb = 0;
887
45
  uint8_t head[14];
888
45
  CURLcode result;
889
45
  size_t hlen, nwritten;
890
891
45
  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
45
  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
45
  result = ws_frame_flags2firstbyte(data, flags, (bool)enc->contfragment,
905
45
                                    &firstb);
906
45
  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
45
  if(flags & (CURLWS_TEXT | CURLWS_BINARY)) {
912
12
    enc->contfragment = (curl_bit)((flags & CURLWS_CONT) ? TRUE : FALSE);
913
12
  }
914
915
45
  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
45
  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
45
  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
45
  head[0] = enc->firstbyte = firstb;
929
45
  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
45
  else if(payload_len >= 126) {
942
1
    head[1] = 126 | WSBIT_MASK;
943
1
    head[2] = (uint8_t)((payload_len >> 8) & 0xff);
944
1
    head[3] = (uint8_t)(payload_len & 0xff);
945
1
    hlen = 4;
946
1
  }
947
44
  else {
948
44
    head[1] = (uint8_t)payload_len | WSBIT_MASK;
949
44
    hlen = 2;
950
44
  }
951
952
45
  enc->payload_remain = enc->payload_len = payload_len;
953
45
  ws_enc_info(enc, data, "sending");
954
955
  /* 4 bytes random */
956
957
45
  result = Curl_rand(data, (uint8_t *)&enc->mask, sizeof(enc->mask));
958
45
  if(result)
959
0
    return result;
960
961
45
#ifdef DEBUGBUILD
962
45
  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
45
#endif
966
967
  /* add 4 bytes mask */
968
45
  memcpy(&head[hlen], &enc->mask, 4);
969
45
  hlen += 4;
970
  /* reset for payload to come */
971
45
  enc->xori = 0;
972
973
45
  result = Curl_bufq_write(out, head, hlen, &nwritten);
974
45
  if(result)
975
0
    return result;
976
45
  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
45
  return CURLE_OK;
982
45
}
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
12
{
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
12
  if(ws->pending.type) {
994
2
    CURLcode result = ws_enc_add_pending(data, ws);
995
2
    if(result)
996
0
      return result;
997
2
  }
998
12
  return ws_enc_add_frame(data, enc, flags, payload_len, out);
999
12
}
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
45
{
1006
45
  CURLcode result;
1007
45
  size_t i, len, n, remain;
1008
1009
45
  *pnwritten = 0;
1010
45
  if(Curl_bufq_is_full(out))
1011
0
    return CURLE_AGAIN;
1012
1013
  /* not the most performant way to do this */
1014
45
  len = buflen;
1015
45
  remain = curlx_sotouz_range(enc->payload_remain, 0, SIZE_MAX);
1016
45
  if(remain < len)
1017
0
    len = remain;
1018
1019
964
  for(i = 0; i < len; ++i) {
1020
919
    uint8_t c = buf[i] ^ enc->mask[enc->xori];
1021
919
    result = Curl_bufq_write(out, &c, 1, &n);
1022
919
    if(result) {
1023
0
      if((result != CURLE_AGAIN) || !i)
1024
0
        return result;
1025
0
      break;
1026
0
    }
1027
919
    enc->xori++;
1028
919
    enc->xori &= 3;
1029
919
  }
1030
45
  *pnwritten = i;
1031
45
  enc->payload_remain -= (curl_off_t)i;
1032
45
  ws_enc_info(enc, data, "buffered");
1033
45
  return CURLE_OK;
1034
45
}
1035
1036
static CURLcode ws_enc_add_pending(struct Curl_easy *data,
1037
                                   struct websocket *ws)
1038
333
{
1039
333
  CURLcode result;
1040
333
  size_t n;
1041
1042
333
  if(!ws->pending.type) /* no pending frame here */
1043
300
    return CURLE_OK;
1044
33
  if(ws->enc.payload_remain) /* in the middle of another frame */
1045
0
    return CURLE_AGAIN;
1046
1047
33
  result = ws_enc_add_frame(data, &ws->enc, ws->pending.type,
1048
33
                            (curl_off_t)ws->pending.payload_len,
1049
33
                            &ws->sendbuf);
1050
33
  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
33
  result = ws_enc_write_payload(&ws->enc, data, ws->pending.payload,
1056
33
                                ws->pending.payload_len,
1057
33
                                &ws->sendbuf, &n);
1058
33
  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
33
  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
33
  DEBUGASSERT(!ws->enc.payload_remain);
1072
33
  memset(&ws->pending, 0, sizeof(ws->pending));
1073
1074
33
out:
1075
33
  return result;
1076
33
}
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
17
{
1185
17
  (void)data;
1186
17
  (void)reader;
1187
17
  return CURLE_OK;
1188
17
}
1189
1190
static void cr_ws_close(struct Curl_easy *data, struct Curl_creader *reader)
1191
17
{
1192
17
  (void)data;
1193
17
  (void)reader;
1194
17
}
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
23
{
1201
23
  struct cr_ws_ctx *ctx = reader->ctx;
1202
23
  CURLcode result = CURLE_OK;
1203
23
  size_t nread, n;
1204
23
  struct websocket *ws;
1205
23
  bool eos;
1206
1207
23
  *pnread = 0;
1208
23
  if(ctx->eos) {
1209
0
    *peos = TRUE;
1210
0
    return CURLE_OK;
1211
0
  }
1212
1213
23
  ws = Curl_conn_meta_get(data->conn, CURL_META_PROTO_WS_CONN);
1214
23
  if(!ws) {
1215
0
    failf(data, "[WS] not a websocket transfer");
1216
0
    return CURLE_FAILED_INIT;
1217
0
  }
1218
1219
23
  if(Curl_bufq_is_empty(&ws->sendbuf)) {
1220
23
    if(ctx->read_eos) {
1221
0
      ctx->eos = TRUE;
1222
0
      *peos = TRUE;
1223
0
      return CURLE_OK;
1224
0
    }
1225
1226
23
    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
23
    result = Curl_creader_read(data, reader->next, buf, blen, &nread, &eos);
1233
23
    if(result)
1234
1
      return result;
1235
22
    ctx->read_eos = eos;
1236
1237
22
    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
22
    else if(!nread) {
1243
      /* nothing to convert, return this right away */
1244
10
      if(ctx->read_eos)
1245
10
        ctx->eos = TRUE;
1246
10
      *pnread = nread;
1247
10
      *peos = (bool)ctx->eos;
1248
10
      goto out;
1249
10
    }
1250
1251
12
    if(!ws->enc.payload_remain && Curl_bufq_is_empty(&ws->sendbuf)) {
1252
      /* encode the data as a new BINARY frame */
1253
12
      result = ws_enc_write_head(data, ws, &ws->enc, CURLWS_BINARY, nread,
1254
12
                                 &ws->sendbuf);
1255
12
      if(result)
1256
0
        goto out;
1257
12
    }
1258
1259
12
    result = ws_enc_write_payload(&ws->enc, data, (uint8_t *)buf,
1260
12
                                  nread, &ws->sendbuf, &n);
1261
12
    if(result)
1262
0
      goto out;
1263
12
    CURL_TRC_READ(data, "cr_ws_read, added %zu payload, len=%zu", nread, n);
1264
12
  }
1265
1266
12
  DEBUGASSERT(!Curl_bufq_is_empty(&ws->sendbuf));
1267
12
  *peos = FALSE;
1268
12
  result = Curl_bufq_cread(&ws->sendbuf, buf, blen, pnread);
1269
12
  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
22
out:
1276
22
  CURL_TRC_READ(data, "cr_ws_read(len=%zu) -> %d, nread=%zu, eos=%d",
1277
22
                blen, (int)result, *pnread, *peos);
1278
22
  return result;
1279
12
}
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
218
{
1311
218
  unsigned int i;
1312
218
  CURLcode result = CURLE_OK;
1313
218
  uint8_t rand[16];
1314
218
  char *randstr;
1315
218
  size_t randlen;
1316
218
  char keyval[40];
1317
218
  struct SingleRequest *k = &data->req;
1318
218
  struct wsfield heads[] = {
1319
218
    {
1320
      /* The request MUST contain an |Upgrade| header field whose value
1321
         MUST include the "websocket" keyword. */
1322
218
      "Upgrade", "websocket"
1323
218
    },
1324
218
    {
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
218
      "Sec-WebSocket-Version", "13",
1329
218
    },
1330
218
    {
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
218
      "Sec-WebSocket-Key", NULL,
1337
218
    }
1338
218
  };
1339
218
  heads[2].val = &keyval[0];
1340
1341
  /* 16 bytes random */
1342
218
  result = Curl_rand(data, rand, sizeof(rand));
1343
218
  if(result)
1344
0
    return result;
1345
218
  result = curlx_base64_encode(rand, sizeof(rand), &randstr, &randlen);
1346
218
  if(result)
1347
0
    return result;
1348
218
  DEBUGASSERT(randlen < sizeof(keyval));
1349
218
  if(randlen >= sizeof(keyval)) {
1350
0
    curlx_free(randstr);
1351
0
    return CURLE_FAILED_INIT;
1352
0
  }
1353
218
  curlx_strcopy(keyval, sizeof(keyval), randstr, randlen);
1354
218
  curlx_free(randstr);
1355
872
  for(i = 0; !result && (i < CURL_ARRAYSIZE(heads)); i++) {
1356
654
    if(!Curl_checkheaders(data, heads[i].name, strlen(heads[i].name))) {
1357
654
      result = curlx_dyn_addf(req, "%s: %s\r\n", heads[i].name, heads[i].val);
1358
654
    }
1359
654
  }
1360
218
  data->state.http_hd_upgrade = TRUE;
1361
218
  k->upgr101 = UPGR101_WS;
1362
218
  data->conn->bits.upgrade_in_progress = TRUE;
1363
218
  return result;
1364
218
}
1365
1366
static void ws_conn_dtor(const void *key, size_t klen, void *entry)
1367
188
{
1368
188
  struct websocket *ws = entry;
1369
188
  (void)key;
1370
188
  (void)klen;
1371
188
  Curl_bufq_free(&ws->recvbuf);
1372
188
  Curl_bufq_free(&ws->sendbuf);
1373
188
  curlx_free(ws);
1374
188
}
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
188
{
1383
188
  struct SingleRequest *k = &data->req;
1384
188
  struct websocket *ws;
1385
188
  struct Curl_cwriter *ws_dec_writer = NULL;
1386
188
  struct Curl_creader *ws_enc_reader = NULL;
1387
188
  CURLcode result;
1388
1389
188
  DEBUGASSERT(data->conn);
1390
188
  ws = Curl_conn_meta_get(data->conn, CURL_META_PROTO_WS_CONN);
1391
188
  if(!ws) {
1392
188
    size_t chunk_size = WS_CHUNK_SIZE;
1393
188
    ws = curlx_calloc(1, sizeof(*ws));
1394
188
    if(!ws)
1395
0
      return CURLE_OUT_OF_MEMORY;
1396
188
#ifdef DEBUGBUILD
1397
188
    {
1398
188
      const char *p = getenv("CURL_WS_CHUNK_SIZE");
1399
188
      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
188
    }
1405
188
#endif
1406
188
    CURL_TRC_WS(data, "WS, using chunk size %zu", chunk_size);
1407
188
    Curl_bufq_init2(&ws->recvbuf, chunk_size, WS_CHUNK_COUNT,
1408
188
                    BUFQ_OPT_SOFT_LIMIT);
1409
188
    Curl_bufq_init2(&ws->sendbuf, chunk_size, WS_CHUNK_COUNT,
1410
188
                    BUFQ_OPT_SOFT_LIMIT);
1411
188
    ws_dec_init(&ws->dec);
1412
188
    ws_enc_init(&ws->enc);
1413
188
    result = Curl_conn_meta_set(data->conn, CURL_META_PROTO_WS_CONN,
1414
188
                                ws, ws_conn_dtor);
1415
188
    if(result)
1416
0
      return result;
1417
188
  }
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
188
  infof(data, "[WS] Received 101, switch to WebSocket");
1442
1443
  /* Install our client writer that decodes WS frames payload */
1444
188
  result = Curl_cwriter_create(&ws_dec_writer, data, &ws_cw_decode,
1445
188
                               CURL_CW_CONTENT_DECODE);
1446
188
  if(result)
1447
0
    goto out;
1448
188
  result = Curl_cwriter_add(data, ws_dec_writer);
1449
188
  if(result)
1450
0
    goto out;
1451
188
  ws_dec_writer = NULL; /* owned by transfer now */
1452
1453
188
  k->header = FALSE; /* we will not get more response headers */
1454
1455
188
  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
2
    if(nread) {
1462
1
      result = Curl_cf_recvbuf_add(data, data->conn, FIRSTSOCKET,
1463
1
                                   (const uint8_t *)mem, nread);
1464
1
      if(result)
1465
0
        goto out;
1466
1
    }
1467
2
    CURL_REQ_CLEAR_RECV(data); /* read no more content */
1468
2
  }
1469
186
  else { /* !connect_only */
1470
186
    if(data->set.method == HTTPREQ_PUT) {
1471
19
      CURL_TRC_WS(data, "UPLOAD set, add ws-encode reader");
1472
19
      result = Curl_creader_set_fread(data, -1);
1473
19
      if(result)
1474
0
        goto out;
1475
1476
19
      if(!data->set.ws_raw_mode) {
1477
        /* Add our client reader encoding WS BINARY frames */
1478
17
        result = Curl_creader_create(&ws_enc_reader, data, &ws_cr_encode,
1479
17
                                     CURL_CR_CONTENT_ENCODE);
1480
17
        if(result)
1481
0
          goto out;
1482
17
        result = Curl_creader_add(data, ws_enc_reader);
1483
17
        if(result)
1484
0
          goto out;
1485
17
        ws_enc_reader = NULL; /* owned by transfer now */
1486
17
        ws->using_reader = TRUE;
1487
17
      }
1488
1489
      /* start over with sending */
1490
19
      data->req.eos_read = FALSE;
1491
19
      data->req.upload_done = FALSE;
1492
19
      CURL_REQ_SET_SEND(data);
1493
19
    }
1494
1495
    /* Then pass any additional data to the writers */
1496
186
    if(nread) {
1497
174
      result = Curl_client_write(data, CLIENTWRITE_BODY, mem, nread);
1498
174
      if(result)
1499
30
        goto out;
1500
174
    }
1501
186
  }
1502
1503
158
  k->upgr101 = UPGR101_RECEIVED;
1504
158
  k->header = FALSE; /* we will not get more responses */
1505
1506
188
out:
1507
188
  if(ws_dec_writer)
1508
0
    Curl_cwriter_free(data, ws_dec_writer);
1509
188
  if(ws_enc_reader)
1510
0
    Curl_creader_free(data, ws_enc_reader);
1511
188
  if(result)
1512
30
    CURL_TRC_WS(data, "Curl_ws_accept() failed -> %d", (int)result);
1513
158
  else
1514
158
    CURL_TRC_WS(data, "websocket established, %s mode",
1515
188
                data->set.connect_only ? "connect-only" : "callback");
1516
188
  return result;
1517
158
}
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
331
{
1709
331
  CURLcode result;
1710
1711
  /* If there is space, add any pending control frame */
1712
331
  if(Curl_bufq_len(&ws->sendbuf) < ws->sendbuf.chunk_size) {
1713
331
    result = ws_enc_add_pending(data, ws);
1714
331
    if(result && (result != CURLE_AGAIN))
1715
0
      return result;
1716
331
  }
1717
1718
331
  if(!Curl_bufq_is_empty(&ws->sendbuf)) {
1719
31
    const uint8_t *out;
1720
31
    size_t outlen, n;
1721
31
#ifdef DEBUGBUILD
1722
    /* Simulate a blocking send after this chunk has been sent */
1723
31
    bool eagain_next = FALSE;
1724
31
    size_t chunk_egain = 0;
1725
31
    const char *p = getenv("CURL_WS_CHUNK_EAGAIN");
1726
31
    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
31
#endif
1732
1733
62
    while(Curl_bufq_peek(&ws->sendbuf, &out, &outlen)) {
1734
31
#ifdef DEBUGBUILD
1735
31
      if(eagain_next)
1736
0
        return CURLE_AGAIN;
1737
31
      if(chunk_egain && (outlen > chunk_egain)) {
1738
0
        outlen = chunk_egain;
1739
0
        eagain_next = TRUE;
1740
0
      }
1741
31
#endif
1742
31
      if(blocking) {
1743
0
        result = ws_send_raw_blocking(data, ws, (const char *)out, outlen);
1744
0
        n = result ? 0 : outlen;
1745
0
      }
1746
31
      else if(data->set.connect_only || Curl_api_is_in_callback(data))
1747
0
        result = Curl_senddata(data, out, outlen, &n);
1748
31
      else {
1749
31
        result = Curl_xfer_send(data, out, outlen, FALSE, &n);
1750
31
        if(!result && !n && outlen)
1751
0
          result = CURLE_AGAIN;
1752
31
      }
1753
1754
31
      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
31
      else if(result) {
1760
0
        failf(data, "[WS] flush, write error %d", (int)result);
1761
0
        return result;
1762
0
      }
1763
31
      else {
1764
31
        CURL_TRC_WS(data, "flushed %zu bytes", n);
1765
31
        Curl_bufq_skip(&ws->sendbuf, n);
1766
31
      }
1767
31
    }
1768
31
  }
1769
331
  return CURLE_OK;
1770
331
}
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
226
{
1940
  /* WebSocket is 1.1 only (for now) */
1941
226
  data->state.http_neg.accept_09 = FALSE;
1942
226
  data->state.http_neg.only_10 = FALSE;
1943
226
  data->state.http_neg.wanted = CURL_HTTP_V1x;
1944
226
  data->state.http_neg.allowed = CURL_HTTP_V1x;
1945
226
  return Curl_http_setup_conn(data, conn);
1946
226
}
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 */