Coverage Report

Created: 2025-07-23 06:58

/src/PROJ/curl/lib/ws.c
Line
Count
Source (jump to first uncovered line)
1
/***************************************************************************
2
 *                                  _   _ ____  _
3
 *  Project                     ___| | | |  _ \| |
4
 *                             / __| | | | |_) | |
5
 *                            | (__| |_| |  _ <| |___
6
 *                             \___|\___/|_| \_\_____|
7
 *
8
 * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
9
 *
10
 * This software is licensed as described in the file COPYING, which
11
 * you should have received as part of this distribution. The terms
12
 * are also available at https://curl.se/docs/copyright.html.
13
 *
14
 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15
 * copies of the Software, and permit persons to whom the Software is
16
 * furnished to do so, under the terms of the COPYING file.
17
 *
18
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19
 * KIND, either express or implied.
20
 *
21
 * SPDX-License-Identifier: curl
22
 *
23
 ***************************************************************************/
24
#include "curl_setup.h"
25
#include <curl/curl.h>
26
27
#if !defined(CURL_DISABLE_WEBSOCKETS) && !defined(CURL_DISABLE_HTTP)
28
29
#include "urldata.h"
30
#include "url.h"
31
#include "bufq.h"
32
#include "curlx/dynbuf.h"
33
#include "rand.h"
34
#include "curlx/base64.h"
35
#include "connect.h"
36
#include "sendf.h"
37
#include "multiif.h"
38
#include "ws.h"
39
#include "easyif.h"
40
#include "transfer.h"
41
#include "select.h"
42
#include "curlx/nonblock.h"
43
#include "curlx/strparse.h"
44
45
/* The last 3 #include files should be in this order */
46
#include "curl_printf.h"
47
#include "curl_memory.h"
48
#include "memdebug.h"
49
50
51
/***
52
    RFC 6455 Section 5.2
53
54
      0 1 2 3 4 5 6 7
55
     +-+-+-+-+-------+
56
     |F|R|R|R| opcode|
57
     |I|S|S|S|  (4)  |
58
     |N|V|V|V|       |
59
     | |1|2|3|       |
60
*/
61
0
#define WSBIT_FIN  (0x80)
62
0
#define WSBIT_RSV1 (0x40)
63
0
#define WSBIT_RSV2 (0x20)
64
0
#define WSBIT_RSV3 (0x10)
65
0
#define WSBIT_RSV_MASK (WSBIT_RSV1 | WSBIT_RSV2 | WSBIT_RSV3)
66
0
#define WSBIT_OPCODE_CONT  (0x0)
67
0
#define WSBIT_OPCODE_TEXT  (0x1)
68
0
#define WSBIT_OPCODE_BIN   (0x2)
69
0
#define WSBIT_OPCODE_CLOSE (0x8)
70
0
#define WSBIT_OPCODE_PING  (0x9)
71
0
#define WSBIT_OPCODE_PONG  (0xa)
72
0
#define WSBIT_OPCODE_MASK  (0xf)
73
74
0
#define WSBIT_MASK 0x80
75
76
/* buffer dimensioning */
77
0
#define WS_CHUNK_SIZE 65535
78
0
#define WS_CHUNK_COUNT 2
79
80
81
/* a client-side WS frame decoder, parsing frame headers and
82
 * payload, keeping track of current position and stats */
83
enum ws_dec_state {
84
  WS_DEC_INIT,
85
  WS_DEC_HEAD,
86
  WS_DEC_PAYLOAD
87
};
88
89
struct ws_decoder {
90
  int frame_age;        /* zero */
91
  int frame_flags;      /* See the CURLWS_* defines */
92
  curl_off_t payload_offset;   /* the offset parsing is at */
93
  curl_off_t payload_len;
94
  unsigned char head[10];
95
  int head_len, head_total;
96
  enum ws_dec_state state;
97
  int cont_flags;
98
};
99
100
/* a client-side WS frame encoder, generating frame headers and
101
 * converting payloads, tracking remaining data in current frame */
102
struct ws_encoder {
103
  curl_off_t payload_len;  /* payload length of current frame */
104
  curl_off_t payload_remain;  /* remaining payload of current */
105
  unsigned int xori; /* xor index */
106
  unsigned char mask[4]; /* 32-bit mask for this connection */
107
  unsigned char firstbyte; /* first byte of frame we encode */
108
  BIT(contfragment); /* set TRUE if the previous fragment sent was not final */
109
};
110
111
/* A websocket connection with en- and decoder that treat frames
112
 * and keep track of boundaries. */
113
struct websocket {
114
  struct Curl_easy *data; /* used for write callback handling */
115
  struct ws_decoder dec;  /* decode of we frames */
116
  struct ws_encoder enc;  /* decode of we frames */
117
  struct bufq recvbuf;    /* raw data from the server */
118
  struct bufq sendbuf;    /* raw data to be sent to the server */
119
  struct curl_ws_frame frame;  /* the current WS FRAME received */
120
  size_t sendbuf_payload; /* number of payload bytes in sendbuf */
121
};
122
123
124
static const char *ws_frame_name_of_op(unsigned char firstbyte)
125
0
{
126
0
  switch(firstbyte & WSBIT_OPCODE_MASK) {
127
0
    case WSBIT_OPCODE_CONT:
128
0
      return "CONT";
129
0
    case WSBIT_OPCODE_TEXT:
130
0
      return "TEXT";
131
0
    case WSBIT_OPCODE_BIN:
132
0
      return "BIN";
133
0
    case WSBIT_OPCODE_CLOSE:
134
0
      return "CLOSE";
135
0
    case WSBIT_OPCODE_PING:
136
0
      return "PING";
137
0
    case WSBIT_OPCODE_PONG:
138
0
      return "PONG";
139
0
    default:
140
0
      return "???";
141
0
  }
142
0
}
143
144
static int ws_frame_firstbyte2flags(struct Curl_easy *data,
145
                                    unsigned char firstbyte, int cont_flags)
146
0
{
147
0
  switch(firstbyte) {
148
    /* 0x00 - intermediate TEXT/BINARY fragment */
149
0
    case WSBIT_OPCODE_CONT:
150
0
      if(!(cont_flags & CURLWS_CONT)) {
151
0
        failf(data, "[WS] no ongoing fragmented message to resume");
152
0
        return 0;
153
0
      }
154
0
      return cont_flags | CURLWS_CONT;
155
    /* 0x80 - final TEXT/BIN fragment */
156
0
    case (WSBIT_OPCODE_CONT | WSBIT_FIN):
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
    /* 0x01 - first TEXT fragment */
163
0
    case WSBIT_OPCODE_TEXT:
164
0
      if(cont_flags & CURLWS_CONT) {
165
0
        failf(data, "[WS] fragmented message interrupted by new TEXT msg");
166
0
        return 0;
167
0
      }
168
0
      return CURLWS_TEXT | CURLWS_CONT;
169
    /* 0x81 - unfragmented TEXT msg */
170
0
    case (WSBIT_OPCODE_TEXT | WSBIT_FIN):
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;
176
    /* 0x02 - first BINARY fragment */
177
0
    case WSBIT_OPCODE_BIN:
178
0
      if(cont_flags & CURLWS_CONT) {
179
0
        failf(data, "[WS] fragmented message interrupted by new BINARY msg");
180
0
        return 0;
181
0
      }
182
0
      return CURLWS_BINARY | CURLWS_CONT;
183
    /* 0x82 - unfragmented BINARY msg */
184
0
    case (WSBIT_OPCODE_BIN | WSBIT_FIN):
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;
190
    /* 0x08 - first CLOSE fragment */
191
0
    case WSBIT_OPCODE_CLOSE:
192
0
      failf(data, "[WS] invalid fragmented CLOSE frame");
193
0
      return 0;
194
    /* 0x88 - unfragmented CLOSE */
195
0
    case (WSBIT_OPCODE_CLOSE | WSBIT_FIN):
196
0
      return CURLWS_CLOSE;
197
    /* 0x09 - first PING fragment */
198
0
    case WSBIT_OPCODE_PING:
199
0
      failf(data, "[WS] invalid fragmented PING frame");
200
0
      return 0;
201
    /* 0x89 - unfragmented PING */
202
0
    case (WSBIT_OPCODE_PING | WSBIT_FIN):
203
0
      return CURLWS_PING;
204
    /* 0x0a - first PONG fragment */
205
0
    case WSBIT_OPCODE_PONG:
206
0
      failf(data, "[WS] invalid fragmented PONG frame");
207
0
      return 0;
208
    /* 0x8a - unfragmented PONG */
209
0
    case (WSBIT_OPCODE_PONG | WSBIT_FIN):
210
0
      return CURLWS_PONG;
211
    /* invalid first byte */
212
0
    default:
213
0
      if(firstbyte & WSBIT_RSV_MASK)
214
        /* any of the reserved bits 0x40/0x20/0x10 are set */
215
0
        failf(data, "[WS] invalid reserved bits: %02x", firstbyte);
216
0
      else
217
        /* any of the reserved opcodes 0x3-0x7 or 0xb-0xf is used */
218
0
        failf(data, "[WS] invalid opcode: %02x", firstbyte);
219
0
      return 0;
220
0
  }
221
0
}
222
223
static unsigned char ws_frame_flags2firstbyte(struct Curl_easy *data,
224
                                              unsigned int flags,
225
                                              bool contfragment,
226
                                              CURLcode *err)
227
0
{
228
0
  switch(flags & ~CURLWS_OFFSET) {
229
0
    case 0:
230
0
      if(contfragment) {
231
0
        infof(data, "[WS] no flags given; interpreting as continuation "
232
0
                    "fragment for compatibility");
233
0
        return (WSBIT_OPCODE_CONT | WSBIT_FIN);
234
0
      }
235
0
      failf(data, "[WS] no flags given");
236
0
      *err = CURLE_BAD_FUNCTION_ARGUMENT;
237
0
      return 0xff;
238
0
    case CURLWS_CONT:
239
0
      if(contfragment) {
240
0
        infof(data, "[WS] setting CURLWS_CONT flag without message type is "
241
0
                    "supported for compatibility but highly discouraged");
242
0
        return WSBIT_OPCODE_CONT;
243
0
      }
244
0
      failf(data, "[WS] No ongoing fragmented message to continue");
245
0
      *err = CURLE_BAD_FUNCTION_ARGUMENT;
246
0
      return 0xff;
247
0
    case CURLWS_TEXT:
248
0
      return contfragment ? (WSBIT_OPCODE_CONT | WSBIT_FIN)
249
0
                          : (WSBIT_OPCODE_TEXT | WSBIT_FIN);
250
0
    case (CURLWS_TEXT | CURLWS_CONT):
251
0
      return contfragment ? WSBIT_OPCODE_CONT : WSBIT_OPCODE_TEXT;
252
0
    case CURLWS_BINARY:
253
0
      return contfragment ? (WSBIT_OPCODE_CONT | WSBIT_FIN)
254
0
                          : (WSBIT_OPCODE_BIN | WSBIT_FIN);
255
0
    case (CURLWS_BINARY | CURLWS_CONT):
256
0
      return contfragment ? WSBIT_OPCODE_CONT : WSBIT_OPCODE_BIN;
257
0
    case CURLWS_CLOSE:
258
0
      return WSBIT_OPCODE_CLOSE | WSBIT_FIN;
259
0
    case (CURLWS_CLOSE | CURLWS_CONT):
260
0
      failf(data, "[WS] CLOSE frame must not be fragmented");
261
0
      *err = CURLE_BAD_FUNCTION_ARGUMENT;
262
0
      return 0xff;
263
0
    case CURLWS_PING:
264
0
      return WSBIT_OPCODE_PING | WSBIT_FIN;
265
0
    case (CURLWS_PING | CURLWS_CONT):
266
0
      failf(data, "[WS] PING frame must not be fragmented");
267
0
      *err = CURLE_BAD_FUNCTION_ARGUMENT;
268
0
      return 0xff;
269
0
    case CURLWS_PONG:
270
0
      return WSBIT_OPCODE_PONG | WSBIT_FIN;
271
0
    case (CURLWS_PONG | CURLWS_CONT):
272
0
      failf(data, "[WS] PONG frame must not be fragmented");
273
0
      *err = CURLE_BAD_FUNCTION_ARGUMENT;
274
0
      return 0xff;
275
0
    default:
276
0
      failf(data, "[WS] unknown flags: %x", flags);
277
0
      *err = CURLE_BAD_FUNCTION_ARGUMENT;
278
0
      return 0xff;
279
0
  }
280
0
}
281
282
static void ws_dec_info(struct ws_decoder *dec, struct Curl_easy *data,
283
                        const char *msg)
284
0
{
285
0
  switch(dec->head_len) {
286
0
  case 0:
287
0
    break;
288
0
  case 1:
289
0
    CURL_TRC_WS(data, "decoded %s [%s%s]", msg,
290
0
                ws_frame_name_of_op(dec->head[0]),
291
0
                (dec->head[0] & WSBIT_FIN) ? "" : " NON-FINAL");
292
0
    break;
293
0
  default:
294
0
    if(dec->head_len < dec->head_total) {
295
0
      CURL_TRC_WS(data, "decoded %s [%s%s](%d/%d)", msg,
296
0
                  ws_frame_name_of_op(dec->head[0]),
297
0
                  (dec->head[0] & WSBIT_FIN) ? "" : " NON-FINAL",
298
0
                  dec->head_len, dec->head_total);
299
0
    }
300
0
    else {
301
0
      CURL_TRC_WS(data, "decoded %s [%s%s payload=%"
302
0
                  FMT_OFF_T "/%" FMT_OFF_T "]",
303
0
                  msg, ws_frame_name_of_op(dec->head[0]),
304
0
                  (dec->head[0] & WSBIT_FIN) ? "" : " NON-FINAL",
305
0
                  dec->payload_offset, dec->payload_len);
306
0
    }
307
0
    break;
308
0
  }
309
0
}
310
311
static CURLcode ws_send_raw_blocking(struct Curl_easy *data,
312
                                     struct websocket *ws,
313
                                     const char *buffer, size_t buflen);
314
315
typedef ssize_t ws_write_payload(const unsigned char *buf, size_t buflen,
316
                                 int frame_age, int frame_flags,
317
                                 curl_off_t payload_offset,
318
                                 curl_off_t payload_len,
319
                                 void *userp,
320
                                 CURLcode *err);
321
322
static void ws_dec_next_frame(struct ws_decoder *dec)
323
0
{
324
0
  dec->frame_age = 0;
325
0
  dec->frame_flags = 0;
326
0
  dec->payload_offset = 0;
327
0
  dec->payload_len = 0;
328
0
  dec->head_len = dec->head_total = 0;
329
0
  dec->state = WS_DEC_INIT;
330
  /* dec->cont_flags must be carried over to next frame */
331
0
}
332
333
static void ws_dec_reset(struct ws_decoder *dec)
334
0
{
335
0
  dec->frame_age = 0;
336
0
  dec->frame_flags = 0;
337
0
  dec->payload_offset = 0;
338
0
  dec->payload_len = 0;
339
0
  dec->head_len = dec->head_total = 0;
340
0
  dec->state = WS_DEC_INIT;
341
0
  dec->cont_flags = 0;
342
0
}
343
344
static void ws_dec_init(struct ws_decoder *dec)
345
0
{
346
0
  ws_dec_reset(dec);
347
0
}
348
349
static CURLcode ws_dec_read_head(struct ws_decoder *dec,
350
                                 struct Curl_easy *data,
351
                                 struct bufq *inraw)
352
0
{
353
0
  const unsigned char *inbuf;
354
0
  size_t inlen;
355
356
0
  while(Curl_bufq_peek(inraw, &inbuf, &inlen)) {
357
0
    if(dec->head_len == 0) {
358
0
      dec->head[0] = *inbuf;
359
0
      Curl_bufq_skip(inraw, 1);
360
361
0
      dec->frame_flags = ws_frame_firstbyte2flags(data, dec->head[0],
362
0
                                                  dec->cont_flags);
363
0
      if(!dec->frame_flags) {
364
0
        ws_dec_reset(dec);
365
0
        return CURLE_RECV_ERROR;
366
0
      }
367
368
      /* fragmentation only applies to data frames (text/binary);
369
       * control frames (close/ping/pong) do not affect the CONT status */
370
0
      if(dec->frame_flags & (CURLWS_TEXT | CURLWS_BINARY)) {
371
0
        dec->cont_flags = dec->frame_flags;
372
0
      }
373
374
0
      dec->head_len = 1;
375
      /* ws_dec_info(dec, data, "seeing opcode"); */
376
0
      continue;
377
0
    }
378
0
    else if(dec->head_len == 1) {
379
0
      dec->head[1] = *inbuf;
380
0
      Curl_bufq_skip(inraw, 1);
381
0
      dec->head_len = 2;
382
383
0
      if(dec->head[1] & WSBIT_MASK) {
384
        /* A client MUST close a connection if it detects a masked frame. */
385
0
        failf(data, "[WS] masked input frame");
386
0
        ws_dec_reset(dec);
387
0
        return CURLE_RECV_ERROR;
388
0
      }
389
0
      if(dec->frame_flags & CURLWS_PING && dec->head[1] > 125) {
390
        /* The maximum valid size of PING frames is 125 bytes.
391
           Accepting overlong pings would mean sending equivalent pongs! */
392
0
        failf(data, "[WS] received PING frame is too big");
393
0
        ws_dec_reset(dec);
394
0
        return CURLE_RECV_ERROR;
395
0
      }
396
0
      if(dec->frame_flags & CURLWS_PONG && dec->head[1] > 125) {
397
        /* The maximum valid size of PONG frames is 125 bytes. */
398
0
        failf(data, "[WS] received PONG frame is too big");
399
0
        ws_dec_reset(dec);
400
0
        return CURLE_RECV_ERROR;
401
0
      }
402
0
      if(dec->frame_flags & CURLWS_CLOSE && dec->head[1] > 125) {
403
        /* The maximum valid size of CLOSE frames is 125 bytes. */
404
0
        failf(data, "[WS] received CLOSE frame is too big");
405
0
        ws_dec_reset(dec);
406
0
        return CURLE_RECV_ERROR;
407
0
      }
408
409
      /* How long is the frame head? */
410
0
      if(dec->head[1] == 126) {
411
0
        dec->head_total = 4;
412
0
        continue;
413
0
      }
414
0
      else if(dec->head[1] == 127) {
415
0
        dec->head_total = 10;
416
0
        continue;
417
0
      }
418
0
      else {
419
0
        dec->head_total = 2;
420
0
      }
421
0
    }
422
423
0
    if(dec->head_len < dec->head_total) {
424
0
      dec->head[dec->head_len] = *inbuf;
425
0
      Curl_bufq_skip(inraw, 1);
426
0
      ++dec->head_len;
427
0
      if(dec->head_len < dec->head_total) {
428
        /* ws_dec_info(dec, data, "decoding head"); */
429
0
        continue;
430
0
      }
431
0
    }
432
    /* got the complete frame head */
433
0
    DEBUGASSERT(dec->head_len == dec->head_total);
434
0
    switch(dec->head_total) {
435
0
    case 2:
436
0
      dec->payload_len = dec->head[1];
437
0
      break;
438
0
    case 4:
439
0
      dec->payload_len = (dec->head[2] << 8) | dec->head[3];
440
0
      break;
441
0
    case 10:
442
0
      if(dec->head[2] > 127) {
443
0
        failf(data, "[WS] frame length longer than 64 signed not supported");
444
0
        return CURLE_RECV_ERROR;
445
0
      }
446
0
      dec->payload_len = ((curl_off_t)dec->head[2] << 56) |
447
0
        (curl_off_t)dec->head[3] << 48 |
448
0
        (curl_off_t)dec->head[4] << 40 |
449
0
        (curl_off_t)dec->head[5] << 32 |
450
0
        (curl_off_t)dec->head[6] << 24 |
451
0
        (curl_off_t)dec->head[7] << 16 |
452
0
        (curl_off_t)dec->head[8] << 8 |
453
0
        dec->head[9];
454
0
      break;
455
0
    default:
456
      /* this should never happen */
457
0
      DEBUGASSERT(0);
458
0
      failf(data, "[WS] unexpected frame header length");
459
0
      return CURLE_RECV_ERROR;
460
0
    }
461
462
0
    dec->frame_age = 0;
463
0
    dec->payload_offset = 0;
464
0
    ws_dec_info(dec, data, "decoded");
465
0
    return CURLE_OK;
466
0
  }
467
0
  return CURLE_AGAIN;
468
0
}
469
470
static CURLcode ws_dec_pass_payload(struct ws_decoder *dec,
471
                                    struct Curl_easy *data,
472
                                    struct bufq *inraw,
473
                                    ws_write_payload *write_payload,
474
                                    void *write_ctx)
475
0
{
476
0
  const unsigned char *inbuf;
477
0
  size_t inlen;
478
0
  ssize_t nwritten;
479
0
  CURLcode result;
480
0
  curl_off_t remain = dec->payload_len - dec->payload_offset;
481
482
0
  (void)data;
483
0
  while(remain && Curl_bufq_peek(inraw, &inbuf, &inlen)) {
484
0
    if((curl_off_t)inlen > remain)
485
0
      inlen = (size_t)remain;
486
0
    nwritten = write_payload(inbuf, inlen, dec->frame_age, dec->frame_flags,
487
0
                             dec->payload_offset, dec->payload_len,
488
0
                             write_ctx, &result);
489
0
    if(nwritten < 0)
490
0
      return result;
491
0
    Curl_bufq_skip(inraw, (size_t)nwritten);
492
0
    dec->payload_offset += (curl_off_t)nwritten;
493
0
    remain = dec->payload_len - dec->payload_offset;
494
0
    CURL_TRC_WS(data, "passed %zd bytes payload, %"
495
0
                FMT_OFF_T " remain", nwritten, remain);
496
0
  }
497
498
0
  return remain ? CURLE_AGAIN : CURLE_OK;
499
0
}
500
501
static CURLcode ws_dec_pass(struct ws_decoder *dec,
502
                            struct Curl_easy *data,
503
                            struct bufq *inraw,
504
                            ws_write_payload *write_payload,
505
                            void *write_ctx)
506
0
{
507
0
  CURLcode result;
508
509
0
  if(Curl_bufq_is_empty(inraw))
510
0
    return CURLE_AGAIN;
511
512
0
  switch(dec->state) {
513
0
  case WS_DEC_INIT:
514
0
    ws_dec_next_frame(dec);
515
0
    dec->state = WS_DEC_HEAD;
516
0
    FALLTHROUGH();
517
0
  case WS_DEC_HEAD:
518
0
    result = ws_dec_read_head(dec, data, inraw);
519
0
    if(result) {
520
0
      if(result != CURLE_AGAIN) {
521
0
        infof(data, "[WS] decode error %d", (int)result);
522
0
        break;  /* real error */
523
0
      }
524
      /* incomplete ws frame head */
525
0
      DEBUGASSERT(Curl_bufq_is_empty(inraw));
526
0
      break;
527
0
    }
528
    /* head parsing done */
529
0
    dec->state = WS_DEC_PAYLOAD;
530
0
    if(dec->payload_len == 0) {
531
0
      ssize_t nwritten;
532
0
      const unsigned char tmp = '\0';
533
      /* special case of a 0 length frame, need to write once */
534
0
      nwritten = write_payload(&tmp, 0, dec->frame_age, dec->frame_flags,
535
0
                               0, 0, write_ctx, &result);
536
0
      if(nwritten < 0)
537
0
        return result;
538
0
      dec->state = WS_DEC_INIT;
539
0
      break;
540
0
    }
541
0
    FALLTHROUGH();
542
0
  case WS_DEC_PAYLOAD:
543
0
    result = ws_dec_pass_payload(dec, data, inraw, write_payload, write_ctx);
544
0
    ws_dec_info(dec, data, "passing");
545
0
    if(result)
546
0
      return result;
547
    /* payload parsing done */
548
0
    dec->state = WS_DEC_INIT;
549
0
    break;
550
0
  default:
551
    /* we covered all enums above, but some code analyzers are whimps */
552
0
    result = CURLE_FAILED_INIT;
553
0
  }
554
0
  return result;
555
0
}
556
557
static void update_meta(struct websocket *ws,
558
                        int frame_age, int frame_flags,
559
                        curl_off_t payload_offset,
560
                        curl_off_t payload_len,
561
                        size_t cur_len)
562
0
{
563
0
  curl_off_t bytesleft = (payload_len - payload_offset - cur_len);
564
565
0
  ws->frame.age = frame_age;
566
0
  ws->frame.flags = frame_flags;
567
0
  ws->frame.offset = payload_offset;
568
0
  ws->frame.len = cur_len;
569
0
  ws->frame.bytesleft = bytesleft;
570
0
}
571
572
/* WebSockets decoding client writer */
573
struct ws_cw_ctx {
574
  struct Curl_cwriter super;
575
  struct bufq buf;
576
};
577
578
static CURLcode ws_cw_init(struct Curl_easy *data,
579
                           struct Curl_cwriter *writer)
580
0
{
581
0
  struct ws_cw_ctx *ctx = writer->ctx;
582
0
  (void)data;
583
0
  Curl_bufq_init2(&ctx->buf, WS_CHUNK_SIZE, 1, BUFQ_OPT_SOFT_LIMIT);
584
0
  return CURLE_OK;
585
0
}
586
587
static void ws_cw_close(struct Curl_easy *data, struct Curl_cwriter *writer)
588
0
{
589
0
  struct ws_cw_ctx *ctx = writer->ctx;
590
0
  (void) data;
591
0
  Curl_bufq_free(&ctx->buf);
592
0
}
593
594
struct ws_cw_dec_ctx {
595
  struct Curl_easy *data;
596
  struct websocket *ws;
597
  struct Curl_cwriter *next_writer;
598
  int cw_type;
599
};
600
601
static ssize_t ws_cw_dec_next(const unsigned char *buf, size_t buflen,
602
                              int frame_age, int frame_flags,
603
                              curl_off_t payload_offset,
604
                              curl_off_t payload_len,
605
                              void *user_data,
606
                              CURLcode *err)
607
0
{
608
0
  struct ws_cw_dec_ctx *ctx = user_data;
609
0
  struct Curl_easy *data = ctx->data;
610
0
  struct websocket *ws = ctx->ws;
611
0
  bool auto_pong = !data->set.ws_no_auto_pong;
612
0
  curl_off_t remain = (payload_len - (payload_offset + buflen));
613
614
0
  (void)frame_age;
615
616
0
  if(auto_pong && (frame_flags & CURLWS_PING) && !remain) {
617
    /* auto-respond to PINGs, only works for single-frame payloads atm */
618
0
    size_t bytes;
619
0
    infof(data, "[WS] auto-respond to PING with a PONG");
620
    /* send back the exact same content as a PONG */
621
0
    *err = curl_ws_send(data, buf, buflen, &bytes, 0, CURLWS_PONG);
622
0
    if(*err)
623
0
      return -1;
624
0
  }
625
0
  else if(buflen || !remain) {
626
    /* forward the decoded frame to the next client writer. */
627
0
    update_meta(ws, frame_age, frame_flags, payload_offset,
628
0
                payload_len, buflen);
629
630
0
    *err = Curl_cwriter_write(data, ctx->next_writer, ctx->cw_type,
631
0
                              (const char *)buf, buflen);
632
0
    if(*err)
633
0
      return -1;
634
0
  }
635
0
  *err = CURLE_OK;
636
0
  return (ssize_t)buflen;
637
0
}
638
639
static CURLcode ws_cw_write(struct Curl_easy *data,
640
                            struct Curl_cwriter *writer, int type,
641
                            const char *buf, size_t nbytes)
642
0
{
643
0
  struct ws_cw_ctx *ctx = writer->ctx;
644
0
  struct websocket *ws;
645
0
  CURLcode result;
646
647
0
  if(!(type & CLIENTWRITE_BODY) || data->set.ws_raw_mode)
648
0
    return Curl_cwriter_write(data, writer->next, type, buf, nbytes);
649
650
0
  ws = Curl_conn_meta_get(data->conn, CURL_META_PROTO_WS_CONN);
651
0
  if(!ws) {
652
0
    failf(data, "[WS] not a websocket transfer");
653
0
    return CURLE_FAILED_INIT;
654
0
  }
655
656
0
  if(nbytes) {
657
0
    size_t nwritten;
658
0
    result = Curl_bufq_write(&ctx->buf, (const unsigned char *)buf,
659
0
                             nbytes, &nwritten);
660
0
    if(result) {
661
0
      infof(data, "WS: error adding data to buffer %d", result);
662
0
      return result;
663
0
    }
664
0
  }
665
666
0
  while(!Curl_bufq_is_empty(&ctx->buf)) {
667
0
    struct ws_cw_dec_ctx pass_ctx;
668
0
    pass_ctx.data = data;
669
0
    pass_ctx.ws = ws;
670
0
    pass_ctx.next_writer = writer->next;
671
0
    pass_ctx.cw_type = type;
672
0
    result = ws_dec_pass(&ws->dec, data, &ctx->buf,
673
0
                         ws_cw_dec_next, &pass_ctx);
674
0
    if(result == CURLE_AGAIN) {
675
      /* insufficient amount of data, keep it for later.
676
       * we pretend to have written all since we have a copy */
677
0
      CURL_TRC_WS(data, "buffered incomplete frame head");
678
0
      return CURLE_OK;
679
0
    }
680
0
    else if(result) {
681
0
      infof(data, "[WS] decode error %d", (int)result);
682
0
      return result;
683
0
    }
684
0
  }
685
686
0
  if((type & CLIENTWRITE_EOS) && !Curl_bufq_is_empty(&ctx->buf)) {
687
0
    failf(data, "[WS] decode ending with %zd frame bytes remaining",
688
0
          Curl_bufq_len(&ctx->buf));
689
0
    return CURLE_RECV_ERROR;
690
0
  }
691
692
0
  return CURLE_OK;
693
0
}
694
695
/* WebSocket payload decoding client writer. */
696
static const struct Curl_cwtype ws_cw_decode = {
697
  "ws-decode",
698
  NULL,
699
  ws_cw_init,
700
  ws_cw_write,
701
  ws_cw_close,
702
  sizeof(struct ws_cw_ctx)
703
};
704
705
706
static void ws_enc_info(struct ws_encoder *enc, struct Curl_easy *data,
707
                        const char *msg)
708
0
{
709
0
  CURL_TRC_WS(data, "WS-ENC: %s [%s%s payload=%"
710
0
              FMT_OFF_T "/%" FMT_OFF_T "]",
711
0
              msg, ws_frame_name_of_op(enc->firstbyte),
712
0
              (enc->firstbyte & WSBIT_FIN) ? "" : " NON-FIN",
713
0
              enc->payload_len - enc->payload_remain, enc->payload_len);
714
0
}
715
716
static void ws_enc_reset(struct ws_encoder *enc)
717
0
{
718
0
  enc->payload_remain = 0;
719
0
  enc->xori = 0;
720
0
  enc->contfragment = FALSE;
721
0
}
722
723
static void ws_enc_init(struct ws_encoder *enc)
724
0
{
725
0
  ws_enc_reset(enc);
726
0
}
727
728
/***
729
    RFC 6455 Section 5.2
730
731
      0                   1                   2                   3
732
      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
733
     +-+-+-+-+-------+-+-------------+-------------------------------+
734
     |F|R|R|R| opcode|M| Payload len |    Extended payload length    |
735
     |I|S|S|S|  (4)  |A|     (7)     |             (16/64)           |
736
     |N|V|V|V|       |S|             |   (if payload len==126/127)   |
737
     | |1|2|3|       |K|             |                               |
738
     +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
739
     |     Extended payload length continued, if payload len == 127  |
740
     + - - - - - - - - - - - - - - - +-------------------------------+
741
     |                               |Masking-key, if MASK set to 1  |
742
     +-------------------------------+-------------------------------+
743
     | Masking-key (continued)       |          Payload Data         |
744
     +-------------------------------- - - - - - - - - - - - - - - - +
745
     :                     Payload Data continued ...                :
746
     + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
747
     |                     Payload Data continued ...                |
748
     +---------------------------------------------------------------+
749
*/
750
751
static ssize_t ws_enc_write_head(struct Curl_easy *data,
752
                                 struct ws_encoder *enc,
753
                                 unsigned int flags,
754
                                 curl_off_t payload_len,
755
                                 struct bufq *out,
756
                                 CURLcode *err)
757
0
{
758
0
  unsigned char firstbyte = 0;
759
0
  unsigned char head[14];
760
0
  size_t hlen, n;
761
762
0
  if(payload_len < 0) {
763
0
    failf(data, "[WS] starting new frame with negative payload length %"
764
0
                FMT_OFF_T, payload_len);
765
0
    *err = CURLE_SEND_ERROR;
766
0
    return -1;
767
0
  }
768
769
0
  if(enc->payload_remain > 0) {
770
    /* trying to write a new frame before the previous one is finished */
771
0
    failf(data, "[WS] starting new frame with %zd bytes from last one "
772
0
                "remaining to be sent", (ssize_t)enc->payload_remain);
773
0
    *err = CURLE_SEND_ERROR;
774
0
    return -1;
775
0
  }
776
777
0
  firstbyte = ws_frame_flags2firstbyte(data, flags, enc->contfragment, err);
778
0
  if(*err) {
779
0
    return -1;
780
0
  }
781
782
  /* fragmentation only applies to data frames (text/binary);
783
   * control frames (close/ping/pong) do not affect the CONT status */
784
0
  if(flags & (CURLWS_TEXT | CURLWS_BINARY)) {
785
0
    enc->contfragment = (flags & CURLWS_CONT) ? (bit)TRUE : (bit)FALSE;
786
0
  }
787
788
0
  if(flags & CURLWS_PING && payload_len > 125) {
789
    /* The maximum valid size of PING frames is 125 bytes. */
790
0
    failf(data, "[WS] given PING frame is too big");
791
0
    *err = CURLE_TOO_LARGE;
792
0
    return -1;
793
0
  }
794
0
  if(flags & CURLWS_PONG && payload_len > 125) {
795
    /* The maximum valid size of PONG frames is 125 bytes. */
796
0
    failf(data, "[WS] given PONG frame is too big");
797
0
    *err = CURLE_TOO_LARGE;
798
0
    return -1;
799
0
  }
800
0
  if(flags & CURLWS_CLOSE && payload_len > 125) {
801
    /* The maximum valid size of CLOSE frames is 125 bytes. */
802
0
    failf(data, "[WS] given CLOSE frame is too big");
803
0
    *err = CURLE_TOO_LARGE;
804
0
    return -1;
805
0
  }
806
807
0
  head[0] = enc->firstbyte = firstbyte;
808
0
  if(payload_len > 65535) {
809
0
    head[1] = 127 | WSBIT_MASK;
810
0
    head[2] = (unsigned char)((payload_len >> 56) & 0xff);
811
0
    head[3] = (unsigned char)((payload_len >> 48) & 0xff);
812
0
    head[4] = (unsigned char)((payload_len >> 40) & 0xff);
813
0
    head[5] = (unsigned char)((payload_len >> 32) & 0xff);
814
0
    head[6] = (unsigned char)((payload_len >> 24) & 0xff);
815
0
    head[7] = (unsigned char)((payload_len >> 16) & 0xff);
816
0
    head[8] = (unsigned char)((payload_len >> 8) & 0xff);
817
0
    head[9] = (unsigned char)(payload_len & 0xff);
818
0
    hlen = 10;
819
0
  }
820
0
  else if(payload_len >= 126) {
821
0
    head[1] = 126 | WSBIT_MASK;
822
0
    head[2] = (unsigned char)((payload_len >> 8) & 0xff);
823
0
    head[3] = (unsigned char)(payload_len & 0xff);
824
0
    hlen = 4;
825
0
  }
826
0
  else {
827
0
    head[1] = (unsigned char)payload_len | WSBIT_MASK;
828
0
    hlen = 2;
829
0
  }
830
831
0
  enc->payload_remain = enc->payload_len = payload_len;
832
0
  ws_enc_info(enc, data, "sending");
833
834
  /* add 4 bytes mask */
835
0
  memcpy(&head[hlen], &enc->mask, 4);
836
0
  hlen += 4;
837
  /* reset for payload to come */
838
0
  enc->xori = 0;
839
840
0
  *err = Curl_bufq_write(out, head, hlen, &n);
841
0
  if(*err)
842
0
    return -1;
843
0
  if(n != hlen) {
844
    /* We use a bufq with SOFT_LIMIT, writing should always succeed */
845
0
    DEBUGASSERT(0);
846
0
    *err = CURLE_SEND_ERROR;
847
0
    return -1;
848
0
  }
849
0
  return (ssize_t)n;
850
0
}
851
852
static ssize_t ws_enc_write_payload(struct ws_encoder *enc,
853
                                    struct Curl_easy *data,
854
                                    const unsigned char *buf, size_t buflen,
855
                                    struct bufq *out, CURLcode *err)
856
0
{
857
0
  size_t i, len, n;
858
859
0
  if(Curl_bufq_is_full(out)) {
860
0
    *err = CURLE_AGAIN;
861
0
    return -1;
862
0
  }
863
864
  /* not the most performant way to do this */
865
0
  len = buflen;
866
0
  if((curl_off_t)len > enc->payload_remain)
867
0
    len = (size_t)enc->payload_remain;
868
869
0
  for(i = 0; i < len; ++i) {
870
0
    unsigned char c = buf[i] ^ enc->mask[enc->xori];
871
0
    *err = Curl_bufq_write(out, &c, 1, &n);
872
0
    if(*err) {
873
0
      if((*err != CURLE_AGAIN) || !i)
874
0
        return -1;
875
0
      break;
876
0
    }
877
0
    enc->xori++;
878
0
    enc->xori &= 3;
879
0
  }
880
0
  enc->payload_remain -= (curl_off_t)i;
881
0
  ws_enc_info(enc, data, "buffered");
882
0
  return (ssize_t)i;
883
0
}
884
885
886
struct wsfield {
887
  const char *name;
888
  const char *val;
889
};
890
891
CURLcode Curl_ws_request(struct Curl_easy *data, struct dynbuf *req)
892
0
{
893
0
  unsigned int i;
894
0
  CURLcode result = CURLE_OK;
895
0
  unsigned char rand[16];
896
0
  char *randstr;
897
0
  size_t randlen;
898
0
  char keyval[40];
899
0
  struct SingleRequest *k = &data->req;
900
0
  struct wsfield heads[]= {
901
0
    {
902
      /* The request MUST contain an |Upgrade| header field whose value
903
         MUST include the "websocket" keyword. */
904
0
      "Upgrade", "websocket"
905
0
    },
906
0
    {
907
      /* The request MUST contain a |Connection| header field whose value
908
         MUST include the "Upgrade" token. */
909
0
      "Connection", "Upgrade",
910
0
    },
911
0
    {
912
      /* The request MUST include a header field with the name
913
         |Sec-WebSocket-Version|. The value of this header field MUST be
914
         13. */
915
0
      "Sec-WebSocket-Version", "13",
916
0
    },
917
0
    {
918
      /* The request MUST include a header field with the name
919
         |Sec-WebSocket-Key|. The value of this header field MUST be a nonce
920
         consisting of a randomly selected 16-byte value that has been
921
         base64-encoded (see Section 4 of [RFC4648]). The nonce MUST be
922
         selected randomly for each connection. */
923
0
      "Sec-WebSocket-Key", NULL,
924
0
    }
925
0
  };
926
0
  heads[3].val = &keyval[0];
927
928
  /* 16 bytes random */
929
0
  result = Curl_rand(data, (unsigned char *)rand, sizeof(rand));
930
0
  if(result)
931
0
    return result;
932
0
  result = curlx_base64_encode((char *)rand, sizeof(rand), &randstr, &randlen);
933
0
  if(result)
934
0
    return result;
935
0
  DEBUGASSERT(randlen < sizeof(keyval));
936
0
  if(randlen >= sizeof(keyval)) {
937
0
    free(randstr);
938
0
    return CURLE_FAILED_INIT;
939
0
  }
940
0
  strcpy(keyval, randstr);
941
0
  free(randstr);
942
0
  for(i = 0; !result && (i < CURL_ARRAYSIZE(heads)); i++) {
943
0
    if(!Curl_checkheaders(data, heads[i].name, strlen(heads[i].name))) {
944
0
      result = curlx_dyn_addf(req, "%s: %s\r\n", heads[i].name,
945
0
                              heads[i].val);
946
0
    }
947
0
  }
948
0
  k->upgr101 = UPGR101_WS;
949
0
  return result;
950
0
}
951
952
static void ws_conn_dtor(void *key, size_t klen, void *entry)
953
0
{
954
0
  struct websocket *ws = entry;
955
0
  (void)key;
956
0
  (void)klen;
957
0
  Curl_bufq_free(&ws->recvbuf);
958
0
  Curl_bufq_free(&ws->sendbuf);
959
0
  free(ws);
960
0
}
961
962
/*
963
 * 'nread' is number of bytes of websocket data already in the buffer at
964
 * 'mem'.
965
 */
966
CURLcode Curl_ws_accept(struct Curl_easy *data,
967
                        const char *mem, size_t nread)
968
0
{
969
0
  struct SingleRequest *k = &data->req;
970
0
  struct websocket *ws;
971
0
  struct Curl_cwriter *ws_dec_writer;
972
0
  CURLcode result;
973
974
0
  DEBUGASSERT(data->conn);
975
0
  ws = Curl_conn_meta_get(data->conn, CURL_META_PROTO_WS_CONN);
976
0
  if(!ws) {
977
0
    size_t chunk_size = WS_CHUNK_SIZE;
978
0
    ws = calloc(1, sizeof(*ws));
979
0
    if(!ws)
980
0
      return CURLE_OUT_OF_MEMORY;
981
#ifdef DEBUGBUILD
982
    {
983
      const char *p = getenv("CURL_WS_CHUNK_SIZE");
984
      if(p) {
985
        curl_off_t l;
986
        if(!curlx_str_number(&p, &l, 1*1024*1024))
987
          chunk_size = (size_t)l;
988
      }
989
    }
990
#endif
991
0
    CURL_TRC_WS(data, "WS, using chunk size %zu", chunk_size);
992
0
    Curl_bufq_init2(&ws->recvbuf, chunk_size, WS_CHUNK_COUNT,
993
0
                    BUFQ_OPT_SOFT_LIMIT);
994
0
    Curl_bufq_init2(&ws->sendbuf, chunk_size, WS_CHUNK_COUNT,
995
0
                    BUFQ_OPT_SOFT_LIMIT);
996
0
    ws_dec_init(&ws->dec);
997
0
    ws_enc_init(&ws->enc);
998
0
    result = Curl_conn_meta_set(data->conn, CURL_META_PROTO_WS_CONN,
999
0
                                ws, ws_conn_dtor);
1000
0
    if(result)
1001
0
      return result;
1002
0
  }
1003
0
  else {
1004
0
    Curl_bufq_reset(&ws->recvbuf);
1005
0
    ws_dec_reset(&ws->dec);
1006
0
    ws_enc_reset(&ws->enc);
1007
0
  }
1008
  /* Verify the Sec-WebSocket-Accept response.
1009
1010
     The sent value is the base64 encoded version of a SHA-1 hash done on the
1011
     |Sec-WebSocket-Key| header field concatenated with
1012
     the string "258EAFA5-E914-47DA-95CA-C5AB0DC85B11".
1013
  */
1014
1015
  /* If the response includes a |Sec-WebSocket-Extensions| header field and
1016
     this header field indicates the use of an extension that was not present
1017
     in the client's handshake (the server has indicated an extension not
1018
     requested by the client), the client MUST Fail the WebSocket Connection.
1019
  */
1020
1021
  /* If the response includes a |Sec-WebSocket-Protocol| header field
1022
     and this header field indicates the use of a subprotocol that was
1023
     not present in the client's handshake (the server has indicated a
1024
     subprotocol not requested by the client), the client MUST Fail
1025
     the WebSocket Connection. */
1026
1027
  /* 4 bytes random */
1028
1029
0
  result = Curl_rand(data, (unsigned char *)&ws->enc.mask,
1030
0
                     sizeof(ws->enc.mask));
1031
0
  if(result)
1032
0
    return result;
1033
1034
#ifdef DEBUGBUILD
1035
  if(getenv("CURL_WS_FORCE_ZERO_MASK"))
1036
    /* force the bit mask to 0x00000000, effectively disabling masking */
1037
    memset(ws->enc.mask, 0, sizeof(ws->enc.mask));
1038
#endif
1039
1040
0
  infof(data, "[WS] Received 101, switch to WebSocket; mask %02x%02x%02x%02x",
1041
0
        ws->enc.mask[0], ws->enc.mask[1], ws->enc.mask[2], ws->enc.mask[3]);
1042
1043
  /* Install our client writer that decodes WS frames payload */
1044
0
  result = Curl_cwriter_create(&ws_dec_writer, data, &ws_cw_decode,
1045
0
                               CURL_CW_CONTENT_DECODE);
1046
0
  if(result)
1047
0
    return result;
1048
1049
0
  result = Curl_cwriter_add(data, ws_dec_writer);
1050
0
  if(result) {
1051
0
    Curl_cwriter_free(data, ws_dec_writer);
1052
0
    return result;
1053
0
  }
1054
1055
0
  if(data->set.connect_only) {
1056
0
    size_t nwritten;
1057
    /* In CONNECT_ONLY setup, the payloads from `mem` need to be received
1058
     * when using `curl_ws_recv` later on after this transfer is already
1059
     * marked as DONE. */
1060
0
    result = Curl_bufq_write(&ws->recvbuf, (const unsigned char *)mem,
1061
0
                             nread, &nwritten);
1062
0
    if(result)
1063
0
      return result;
1064
0
    DEBUGASSERT(nread == nwritten);
1065
0
    infof(data, "%zu bytes websocket payload", nread);
1066
0
  }
1067
0
  else { /* !connect_only */
1068
    /* And pass any additional data to the writers */
1069
0
    if(nread) {
1070
0
      result = Curl_client_write(data, CLIENTWRITE_BODY, mem, nread);
1071
0
    }
1072
0
  }
1073
0
  k->upgr101 = UPGR101_RECEIVED;
1074
1075
0
  return result;
1076
0
}
1077
1078
struct ws_collect {
1079
  struct Curl_easy *data;
1080
  unsigned char *buffer;
1081
  size_t buflen;
1082
  size_t bufidx;
1083
  int frame_age;
1084
  int frame_flags;
1085
  curl_off_t payload_offset;
1086
  curl_off_t payload_len;
1087
  bool written;
1088
};
1089
1090
static ssize_t ws_client_collect(const unsigned char *buf, size_t buflen,
1091
                                 int frame_age, int frame_flags,
1092
                                 curl_off_t payload_offset,
1093
                                 curl_off_t payload_len,
1094
                                 void *userp,
1095
                                 CURLcode *err)
1096
0
{
1097
0
  struct ws_collect *ctx = userp;
1098
0
  struct Curl_easy *data = ctx->data;
1099
0
  bool auto_pong = !data->set.ws_no_auto_pong;
1100
0
  size_t nwritten;
1101
0
  curl_off_t remain = (payload_len - (payload_offset + buflen));
1102
1103
0
  if(!ctx->bufidx) {
1104
    /* first write */
1105
0
    ctx->frame_age = frame_age;
1106
0
    ctx->frame_flags = frame_flags;
1107
0
    ctx->payload_offset = payload_offset;
1108
0
    ctx->payload_len = payload_len;
1109
0
  }
1110
1111
0
  if(auto_pong && (frame_flags & CURLWS_PING) && !remain) {
1112
    /* auto-respond to PINGs, only works for single-frame payloads atm */
1113
0
    size_t bytes;
1114
0
    infof(ctx->data, "[WS] auto-respond to PING with a PONG");
1115
    /* send back the exact same content as a PONG */
1116
0
    *err = curl_ws_send(ctx->data, buf, buflen, &bytes, 0, CURLWS_PONG);
1117
0
    if(*err)
1118
0
      return -1;
1119
0
    nwritten = bytes;
1120
0
  }
1121
0
  else {
1122
0
    ctx->written = TRUE;
1123
0
    DEBUGASSERT(ctx->buflen >= ctx->bufidx);
1124
0
    nwritten = CURLMIN(buflen, ctx->buflen - ctx->bufidx);
1125
0
    if(!nwritten) {
1126
0
      if(!buflen) {  /* 0 length write, we accept that */
1127
0
        *err = CURLE_OK;
1128
0
        return 0;
1129
0
      }
1130
0
      *err = CURLE_AGAIN;  /* no more space */
1131
0
      return -1;
1132
0
    }
1133
0
    *err = CURLE_OK;
1134
0
    memcpy(ctx->buffer + ctx->bufidx, buf, nwritten);
1135
0
    ctx->bufidx += nwritten;
1136
0
  }
1137
0
  return nwritten;
1138
0
}
1139
1140
static CURLcode nw_in_recv(void *reader_ctx,
1141
                           unsigned char *buf, size_t buflen,
1142
                           size_t *pnread)
1143
0
{
1144
0
  struct Curl_easy *data = reader_ctx;
1145
0
  return curl_easy_recv(data, buf, buflen, pnread);
1146
0
}
1147
1148
CURLcode curl_ws_recv(CURL *d, void *buffer,
1149
                      size_t buflen, size_t *nread,
1150
                      const struct curl_ws_frame **metap)
1151
0
{
1152
0
  struct Curl_easy *data = d;
1153
0
  struct connectdata *conn = data->conn;
1154
0
  struct websocket *ws;
1155
0
  struct ws_collect ctx;
1156
1157
0
  *nread = 0;
1158
0
  *metap = NULL;
1159
0
  if(!GOOD_EASY_HANDLE(data))
1160
0
    return CURLE_BAD_FUNCTION_ARGUMENT;
1161
1162
0
  if(!conn) {
1163
    /* Unhappy hack with lifetimes of transfers and connection */
1164
0
    if(!data->set.connect_only) {
1165
0
      failf(data, "[WS] CONNECT_ONLY is required");
1166
0
      return CURLE_UNSUPPORTED_PROTOCOL;
1167
0
    }
1168
1169
0
    Curl_getconnectinfo(data, &conn);
1170
0
    if(!conn) {
1171
0
      failf(data, "[WS] connection not found");
1172
0
      return CURLE_BAD_FUNCTION_ARGUMENT;
1173
0
    }
1174
0
  }
1175
0
  ws = Curl_conn_meta_get(conn, CURL_META_PROTO_WS_CONN);
1176
0
  if(!ws) {
1177
0
    failf(data, "[WS] connection is not setup for websocket");
1178
0
    return CURLE_BAD_FUNCTION_ARGUMENT;
1179
0
  }
1180
1181
1182
0
  memset(&ctx, 0, sizeof(ctx));
1183
0
  ctx.data = data;
1184
0
  ctx.buffer = buffer;
1185
0
  ctx.buflen = buflen;
1186
1187
0
  while(1) {
1188
0
    CURLcode result;
1189
1190
    /* receive more when our buffer is empty */
1191
0
    if(Curl_bufq_is_empty(&ws->recvbuf)) {
1192
0
      size_t n;
1193
0
      result = Curl_bufq_slurp(&ws->recvbuf, nw_in_recv, data, &n);
1194
0
      if(result)
1195
0
        return result;
1196
0
      else if(n == 0) {
1197
        /* connection closed */
1198
0
        infof(data, "[WS] connection expectedly closed?");
1199
0
        return CURLE_GOT_NOTHING;
1200
0
      }
1201
0
      CURL_TRC_WS(data, "curl_ws_recv, added %zu bytes from network",
1202
0
                  Curl_bufq_len(&ws->recvbuf));
1203
0
    }
1204
1205
0
    result = ws_dec_pass(&ws->dec, data, &ws->recvbuf,
1206
0
                         ws_client_collect, &ctx);
1207
0
    if(result == CURLE_AGAIN) {
1208
0
      if(!ctx.written) {
1209
0
        ws_dec_info(&ws->dec, data, "need more input");
1210
0
        continue;  /* nothing written, try more input */
1211
0
      }
1212
0
      break;
1213
0
    }
1214
0
    else if(result) {
1215
0
      return result;
1216
0
    }
1217
0
    else if(ctx.written) {
1218
      /* The decoded frame is passed back to our caller.
1219
       * There are frames like PING were we auto-respond to and
1220
       * that we do not return. For these `ctx.written` is not set. */
1221
0
      break;
1222
0
    }
1223
0
  }
1224
1225
  /* update frame information to be passed back */
1226
0
  update_meta(ws, ctx.frame_age, ctx.frame_flags, ctx.payload_offset,
1227
0
              ctx.payload_len, ctx.bufidx);
1228
0
  *metap = &ws->frame;
1229
0
  *nread = ws->frame.len;
1230
0
  CURL_TRC_WS(data, "curl_ws_recv(len=%zu) -> %zu bytes (frame at %"
1231
0
               FMT_OFF_T ", %" FMT_OFF_T " left)",
1232
0
               buflen, *nread, ws->frame.offset, ws->frame.bytesleft);
1233
0
  return CURLE_OK;
1234
0
}
1235
1236
static CURLcode ws_flush(struct Curl_easy *data, struct websocket *ws,
1237
                         bool blocking)
1238
0
{
1239
0
  if(!Curl_bufq_is_empty(&ws->sendbuf)) {
1240
0
    CURLcode result;
1241
0
    const unsigned char *out;
1242
0
    size_t outlen, n;
1243
#ifdef DEBUGBUILD
1244
    /* Simulate a blocking send after this chunk has been sent */
1245
    bool eagain_next = FALSE;
1246
    size_t chunk_egain = 0;
1247
    const char *p = getenv("CURL_WS_CHUNK_EAGAIN");
1248
    if(p) {
1249
      curl_off_t l;
1250
      if(!curlx_str_number(&p, &l, 1*1024*1024))
1251
        chunk_egain = (size_t)l;
1252
    }
1253
#endif
1254
1255
0
    while(Curl_bufq_peek(&ws->sendbuf, &out, &outlen)) {
1256
#ifdef DEBUGBUILD
1257
      if(eagain_next)
1258
        return CURLE_AGAIN;
1259
      if(chunk_egain && (outlen > chunk_egain)) {
1260
        outlen = chunk_egain;
1261
        eagain_next = TRUE;
1262
      }
1263
#endif
1264
0
      if(blocking) {
1265
0
        result = ws_send_raw_blocking(data, ws, (const char *)out, outlen);
1266
0
        n = result ? 0 : outlen;
1267
0
      }
1268
0
      else if(data->set.connect_only || Curl_is_in_callback(data))
1269
0
        result = Curl_senddata(data, out, outlen, &n);
1270
0
      else {
1271
0
        result = Curl_xfer_send(data, out, outlen, FALSE, &n);
1272
0
        if(!result && !n && outlen)
1273
0
          result = CURLE_AGAIN;
1274
0
      }
1275
1276
0
      if(result == CURLE_AGAIN) {
1277
0
        CURL_TRC_WS(data, "flush EAGAIN, %zu bytes remain in buffer",
1278
0
                    Curl_bufq_len(&ws->sendbuf));
1279
0
        return result;
1280
0
      }
1281
0
      else if(result) {
1282
0
        failf(data, "[WS] flush, write error %d", result);
1283
0
        return result;
1284
0
      }
1285
0
      else {
1286
0
        CURL_TRC_WS(data, "flushed %zu bytes", n);
1287
0
        Curl_bufq_skip(&ws->sendbuf, n);
1288
0
      }
1289
0
    }
1290
0
  }
1291
0
  return CURLE_OK;
1292
0
}
1293
1294
static CURLcode ws_send_raw_blocking(struct Curl_easy *data,
1295
                                     struct websocket *ws,
1296
                                     const char *buffer, size_t buflen)
1297
0
{
1298
0
  CURLcode result = CURLE_OK;
1299
0
  size_t nwritten;
1300
1301
0
  (void)ws;
1302
0
  while(buflen) {
1303
0
    result = Curl_xfer_send(data, buffer, buflen, FALSE, &nwritten);
1304
0
    if(result)
1305
0
      return result;
1306
0
    DEBUGASSERT(nwritten <= buflen);
1307
0
    buffer += nwritten;
1308
0
    buflen -= nwritten;
1309
0
    if(buflen) {
1310
0
      curl_socket_t sock = data->conn->sock[FIRSTSOCKET];
1311
0
      timediff_t left_ms;
1312
0
      int ev;
1313
1314
0
      CURL_TRC_WS(data, "ws_send_raw_blocking() partial, %zu left to send",
1315
0
                  buflen);
1316
0
      left_ms = Curl_timeleft(data, NULL, FALSE);
1317
0
      if(left_ms < 0) {
1318
0
        failf(data, "[WS] Timeout waiting for socket becoming writable");
1319
0
        return CURLE_SEND_ERROR;
1320
0
      }
1321
1322
      /* POLLOUT socket */
1323
0
      if(sock == CURL_SOCKET_BAD)
1324
0
        return CURLE_SEND_ERROR;
1325
0
      ev = Curl_socket_check(CURL_SOCKET_BAD, CURL_SOCKET_BAD, sock,
1326
0
                             left_ms ? left_ms : 500);
1327
0
      if(ev < 0) {
1328
0
        failf(data, "[WS] Error while waiting for socket becoming writable");
1329
0
        return CURLE_SEND_ERROR;
1330
0
      }
1331
0
    }
1332
0
  }
1333
0
  return result;
1334
0
}
1335
1336
static CURLcode ws_send_raw(struct Curl_easy *data, const void *buffer,
1337
                            size_t buflen, size_t *pnwritten)
1338
0
{
1339
0
  struct websocket *ws;
1340
0
  CURLcode result;
1341
1342
0
  ws = Curl_conn_meta_get(data->conn, CURL_META_PROTO_WS_CONN);
1343
0
  if(!ws) {
1344
0
    failf(data, "[WS] Not a websocket transfer");
1345
0
    return CURLE_SEND_ERROR;
1346
0
  }
1347
0
  if(!buflen)
1348
0
    return CURLE_OK;
1349
1350
0
  if(Curl_is_in_callback(data)) {
1351
    /* When invoked from inside callbacks, we do a blocking send as the
1352
     * callback will probably not implement partial writes that may then
1353
     * mess up the ws framing subsequently.
1354
     * We need any pending data to be flushed before sending. */
1355
0
    result = ws_flush(data, ws, TRUE);
1356
0
    if(result)
1357
0
      return result;
1358
0
    result = ws_send_raw_blocking(data, ws, buffer, buflen);
1359
0
  }
1360
0
  else {
1361
    /* We need any pending data to be sent or EAGAIN this call. */
1362
0
    result = ws_flush(data, ws, FALSE);
1363
0
    if(result)
1364
0
      return result;
1365
0
    result = Curl_senddata(data, buffer, buflen, pnwritten);
1366
0
  }
1367
1368
0
  CURL_TRC_WS(data, "ws_send_raw(len=%zu) -> %d, %zu",
1369
0
              buflen, result, *pnwritten);
1370
0
  return result;
1371
0
}
1372
1373
CURLcode curl_ws_send(CURL *d, const void *buffer_arg,
1374
                      size_t buflen, size_t *sent,
1375
                      curl_off_t fragsize,
1376
                      unsigned int flags)
1377
0
{
1378
0
  struct websocket *ws;
1379
0
  const unsigned char *buffer = buffer_arg;
1380
0
  ssize_t n;
1381
0
  CURLcode result = CURLE_OK;
1382
0
  struct Curl_easy *data = d;
1383
1384
0
  if(!GOOD_EASY_HANDLE(data))
1385
0
    return CURLE_BAD_FUNCTION_ARGUMENT;
1386
0
  CURL_TRC_WS(data, "curl_ws_send(len=%zu, fragsize=%" FMT_OFF_T
1387
0
              ", flags=%x), raw=%d",
1388
0
              buflen, fragsize, flags, data->set.ws_raw_mode);
1389
0
  *sent = 0;
1390
0
  if(!data->conn && data->set.connect_only) {
1391
0
    result = Curl_connect_only_attach(data);
1392
0
    if(result)
1393
0
      goto out;
1394
0
  }
1395
0
  if(!data->conn) {
1396
0
    failf(data, "[WS] No associated connection");
1397
0
    result = CURLE_SEND_ERROR;
1398
0
    goto out;
1399
0
  }
1400
0
  ws = Curl_conn_meta_get(data->conn, CURL_META_PROTO_WS_CONN);
1401
0
  if(!ws) {
1402
0
    failf(data, "[WS] Not a websocket transfer");
1403
0
    result = CURLE_SEND_ERROR;
1404
0
    goto out;
1405
0
  }
1406
1407
0
  if(data->set.ws_raw_mode) {
1408
    /* In raw mode, we write directly to the connection */
1409
    /* try flushing any content still waiting to be sent. */
1410
0
    result = ws_flush(data, ws, FALSE);
1411
0
    if(result)
1412
0
      goto out;
1413
1414
0
    if(fragsize || flags) {
1415
0
      failf(data, "[WS] fragsize and flags must be zero in raw mode");
1416
0
      return CURLE_BAD_FUNCTION_ARGUMENT;
1417
0
    }
1418
0
    result = ws_send_raw(data, buffer, buflen, sent);
1419
0
    goto out;
1420
0
  }
1421
1422
  /* Not RAW mode, buf we do the frame encoding */
1423
1424
0
  if(ws->enc.payload_remain || !Curl_bufq_is_empty(&ws->sendbuf)) {
1425
    /* a frame is ongoing with payload buffered or more payload
1426
     * that needs to be encoded into the buffer */
1427
0
    if(buflen < ws->sendbuf_payload) {
1428
      /* We have been called with LESS buffer data than before. This
1429
       * is not how it's supposed too work. */
1430
0
      failf(data, "[WS] curl_ws_send() called with smaller 'buflen' than "
1431
0
            "bytes already buffered in previous call, %zu vs %zu",
1432
0
            buflen, ws->sendbuf_payload);
1433
0
      result = CURLE_BAD_FUNCTION_ARGUMENT;
1434
0
      goto out;
1435
0
    }
1436
0
    if((curl_off_t)buflen >
1437
0
       (ws->enc.payload_remain + (curl_off_t)ws->sendbuf_payload)) {
1438
      /* too large buflen beyond payload length of frame */
1439
0
      failf(data, "[WS] unaligned frame size (sending %zu instead of %"
1440
0
                  FMT_OFF_T ")",
1441
0
            buflen, ws->enc.payload_remain + ws->sendbuf_payload);
1442
0
      result = CURLE_BAD_FUNCTION_ARGUMENT;
1443
0
      goto out;
1444
0
    }
1445
0
  }
1446
0
  else {
1447
    /* starting a new frame, we want a clean sendbuf */
1448
0
    curl_off_t payload_len = (flags & CURLWS_OFFSET) ?
1449
0
                             fragsize : (curl_off_t)buflen;
1450
0
    result = ws_flush(data, ws, Curl_is_in_callback(data));
1451
0
    if(result)
1452
0
      goto out;
1453
1454
0
    n = ws_enc_write_head(data, &ws->enc, flags, payload_len,
1455
0
                          &ws->sendbuf, &result);
1456
0
    if(n < 0)
1457
0
      goto out;
1458
0
  }
1459
1460
  /* While there is either sendbuf to flush OR more payload to encode... */
1461
0
  while(!Curl_bufq_is_empty(&ws->sendbuf) || (buflen > ws->sendbuf_payload)) {
1462
    /* Try to add more payload to sendbuf */
1463
0
    if(buflen > ws->sendbuf_payload) {
1464
0
      size_t prev_len = Curl_bufq_len(&ws->sendbuf);
1465
0
      n = ws_enc_write_payload(&ws->enc, data,
1466
0
                               buffer + ws->sendbuf_payload,
1467
0
                               buflen - ws->sendbuf_payload,
1468
0
                               &ws->sendbuf, &result);
1469
0
      if(n < 0 && (result != CURLE_AGAIN))
1470
0
        goto out;
1471
0
      ws->sendbuf_payload += Curl_bufq_len(&ws->sendbuf) - prev_len;
1472
0
      if(!ws->sendbuf_payload) {
1473
0
        result = CURLE_AGAIN;
1474
0
        goto out;
1475
0
      }
1476
0
    }
1477
1478
    /* flush, blocking when in callback */
1479
0
    result = ws_flush(data, ws, Curl_is_in_callback(data));
1480
0
    if(!result && ws->sendbuf_payload > 0) {
1481
0
      *sent += ws->sendbuf_payload;
1482
0
      buffer += ws->sendbuf_payload;
1483
0
      buflen -= ws->sendbuf_payload;
1484
0
      ws->sendbuf_payload = 0;
1485
0
    }
1486
0
    else if(result == CURLE_AGAIN) {
1487
0
      if(ws->sendbuf_payload > Curl_bufq_len(&ws->sendbuf)) {
1488
        /* blocked, part of payload bytes remain, report length
1489
         * that we managed to send. */
1490
0
        size_t flushed = (ws->sendbuf_payload - Curl_bufq_len(&ws->sendbuf));
1491
0
        *sent += flushed;
1492
0
        ws->sendbuf_payload -= flushed;
1493
0
        result = CURLE_OK;
1494
0
        goto out;
1495
0
      }
1496
0
      else {
1497
        /* blocked before sending headers or 1st payload byte. We cannot report
1498
         * OK on 0-length send (caller counts only payload) and EAGAIN */
1499
0
        CURL_TRC_WS(data, "EAGAIN flushing sendbuf, payload_encoded: %zu/%zu",
1500
0
                    ws->sendbuf_payload, buflen);
1501
0
        DEBUGASSERT(*sent == 0);
1502
0
        result = CURLE_AGAIN;
1503
0
        goto out;
1504
0
      }
1505
0
    }
1506
0
    else
1507
0
      goto out;  /* real error sending the data */
1508
0
  }
1509
1510
0
out:
1511
0
  CURL_TRC_WS(data, "curl_ws_send(len=%zu, fragsize=%" FMT_OFF_T
1512
0
              ", flags=%x, raw=%d) -> %d, %zu",
1513
0
              buflen, fragsize, flags, data->set.ws_raw_mode, result, *sent);
1514
0
  return result;
1515
0
}
1516
1517
static CURLcode ws_setup_conn(struct Curl_easy *data,
1518
                              struct connectdata *conn)
1519
0
{
1520
  /* WebSockets is 1.1 only (for now) */
1521
0
  data->state.http_neg.accept_09 = FALSE;
1522
0
  data->state.http_neg.only_10 = FALSE;
1523
0
  data->state.http_neg.wanted = CURL_HTTP_V1x;
1524
0
  data->state.http_neg.allowed = CURL_HTTP_V1x;
1525
0
  return Curl_http_setup_conn(data, conn);
1526
0
}
1527
1528
1529
const struct curl_ws_frame *curl_ws_meta(CURL *d)
1530
0
{
1531
  /* we only return something for websocket, called from within the callback
1532
     when not using raw mode */
1533
0
  struct Curl_easy *data = d;
1534
0
  if(GOOD_EASY_HANDLE(data) && Curl_is_in_callback(data) &&
1535
0
     data->conn && !data->set.ws_raw_mode) {
1536
0
    struct websocket *ws;
1537
0
    ws = Curl_conn_meta_get(data->conn, CURL_META_PROTO_WS_CONN);
1538
0
    if(ws)
1539
0
      return &ws->frame;
1540
1541
0
  }
1542
0
  return NULL;
1543
0
}
1544
1545
const struct Curl_handler Curl_handler_ws = {
1546
  "WS",                                 /* scheme */
1547
  ws_setup_conn,                        /* setup_connection */
1548
  Curl_http,                            /* do_it */
1549
  Curl_http_done,                       /* done */
1550
  ZERO_NULL,                            /* do_more */
1551
  Curl_http_connect,                    /* connect_it */
1552
  ZERO_NULL,                            /* connecting */
1553
  ZERO_NULL,                            /* doing */
1554
  ZERO_NULL,                            /* proto_getsock */
1555
  Curl_http_getsock_do,                 /* doing_getsock */
1556
  ZERO_NULL,                            /* domore_getsock */
1557
  ZERO_NULL,                            /* perform_getsock */
1558
  ZERO_NULL,                            /* disconnect */
1559
  Curl_http_write_resp,                 /* write_resp */
1560
  Curl_http_write_resp_hd,              /* write_resp_hd */
1561
  ZERO_NULL,                            /* connection_check */
1562
  ZERO_NULL,                            /* attach connection */
1563
  Curl_http_follow,                     /* follow */
1564
  PORT_HTTP,                            /* defport */
1565
  CURLPROTO_WS,                         /* protocol */
1566
  CURLPROTO_HTTP,                       /* family */
1567
  PROTOPT_CREDSPERREQUEST |             /* flags */
1568
  PROTOPT_USERPWDCTRL
1569
};
1570
1571
#ifdef USE_SSL
1572
const struct Curl_handler Curl_handler_wss = {
1573
  "WSS",                                /* scheme */
1574
  ws_setup_conn,                        /* setup_connection */
1575
  Curl_http,                            /* do_it */
1576
  Curl_http_done,                       /* done */
1577
  ZERO_NULL,                            /* do_more */
1578
  Curl_http_connect,                    /* connect_it */
1579
  NULL,                                 /* connecting */
1580
  ZERO_NULL,                            /* doing */
1581
  NULL,                                 /* proto_getsock */
1582
  Curl_http_getsock_do,                 /* doing_getsock */
1583
  ZERO_NULL,                            /* domore_getsock */
1584
  ZERO_NULL,                            /* perform_getsock */
1585
  ZERO_NULL,                            /* disconnect */
1586
  Curl_http_write_resp,                 /* write_resp */
1587
  Curl_http_write_resp_hd,              /* write_resp_hd */
1588
  ZERO_NULL,                            /* connection_check */
1589
  ZERO_NULL,                            /* attach connection */
1590
  Curl_http_follow,                     /* follow */
1591
  PORT_HTTPS,                           /* defport */
1592
  CURLPROTO_WSS,                        /* protocol */
1593
  CURLPROTO_HTTP,                       /* family */
1594
  PROTOPT_SSL | PROTOPT_CREDSPERREQUEST | /* flags */
1595
  PROTOPT_USERPWDCTRL
1596
};
1597
#endif
1598
1599
1600
#else
1601
1602
CURLcode curl_ws_recv(CURL *curl, void *buffer, size_t buflen,
1603
                      size_t *nread,
1604
                      const struct curl_ws_frame **metap)
1605
{
1606
  (void)curl;
1607
  (void)buffer;
1608
  (void)buflen;
1609
  (void)nread;
1610
  (void)metap;
1611
  return CURLE_NOT_BUILT_IN;
1612
}
1613
1614
CURLcode curl_ws_send(CURL *curl, const void *buffer,
1615
                      size_t buflen, size_t *sent,
1616
                      curl_off_t fragsize,
1617
                      unsigned int flags)
1618
{
1619
  (void)curl;
1620
  (void)buffer;
1621
  (void)buflen;
1622
  (void)sent;
1623
  (void)fragsize;
1624
  (void)flags;
1625
  return CURLE_NOT_BUILT_IN;
1626
}
1627
1628
const struct curl_ws_frame *curl_ws_meta(CURL *data)
1629
{
1630
  (void)data;
1631
  return NULL;
1632
}
1633
#endif /* !CURL_DISABLE_WEBSOCKETS */