Coverage Report

Created: 2025-08-26 07:08

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