Coverage Report

Created: 2026-07-14 07:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/CMake/Utilities/cmcurl/lib/http2.c
Line
Count
Source
1
/***************************************************************************
2
 *                                  _   _ ____  _
3
 *  Project                     ___| | | |  _ \| |
4
 *                             / __| | | | |_) | |
5
 *                            | (__| |_| |  _ <| |___
6
 *                             \___|\___/|_| \_\_____|
7
 *
8
 * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
9
 *
10
 * This software is licensed as described in the file COPYING, which
11
 * you should have received as part of this distribution. The terms
12
 * are also available at https://curl.se/docs/copyright.html.
13
 *
14
 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15
 * copies of the Software, and permit persons to whom the Software is
16
 * furnished to do so, under the terms of the COPYING file.
17
 *
18
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19
 * KIND, either express or implied.
20
 *
21
 * SPDX-License-Identifier: curl
22
 *
23
 ***************************************************************************/
24
#include "curl_setup.h"
25
26
#if !defined(CURL_DISABLE_HTTP) && defined(USE_NGHTTP2)
27
#include <nghttp2/nghttp2.h>
28
29
#include "urldata.h"
30
#include "bufq.h"
31
#include "uint-hash.h"
32
#include "http1.h"
33
#include "http2.h"
34
#include "http.h"
35
#include "sendf.h"
36
#include "curl_trc.h"
37
#include "select.h"
38
#include "curlx/base64.h"
39
#include "multiif.h"
40
#include "progress.h"
41
#include "url.h"
42
#include "urlapi-int.h"
43
#include "cfilters.h"
44
#include "connect.h"
45
#include "transfer.h"
46
#include "bufref.h"
47
#include "curlx/dynbuf.h"
48
#include "headers.h"
49
50
#if NGHTTP2_VERSION_NUM < 0x010f00
51
#error "nghttp2 1.15.0 or greater required"
52
#endif
53
54
#define NGHTTP2_HAS_SET_LOCAL_WINDOW_SIZE 1
55
56
/* buffer dimensioning:
57
 * use 16K as chunk size, as that fits H2 DATA frames well */
58
0
#define H2_CHUNK_SIZE           (16 * 1024)
59
/* connection window size */
60
0
#define H2_CONN_WINDOW_SIZE     (10 * 1024 * 1024)
61
/* on receiving from TLS, we prep for holding a full stream window */
62
0
#define H2_NW_RECV_CHUNKS       (H2_CONN_WINDOW_SIZE / H2_CHUNK_SIZE)
63
/* on send into TLS, we want to accumulate small frames */
64
0
#define H2_NW_SEND_CHUNKS       1
65
/* this is how much we want "in flight" for a stream, unthrottled */
66
0
#define H2_STREAM_WINDOW_SIZE_MAX   (10 * 1024 * 1024)
67
/* this is how much we want "in flight" for a stream, initially, IFF
68
 * nghttp2 allows us to tweak the local window size. */
69
#if NGHTTP2_HAS_SET_LOCAL_WINDOW_SIZE
70
0
#define H2_STREAM_WINDOW_SIZE_INITIAL  (64 * 1024)
71
#else
72
#define H2_STREAM_WINDOW_SIZE_INITIAL H2_STREAM_WINDOW_SIZE_MAX
73
#endif
74
/* keep smaller stream upload buffer (default h2 window size) to have
75
 * our progress bars and "upload done" reporting closer to reality */
76
0
#define H2_STREAM_SEND_CHUNKS   ((64 * 1024) / H2_CHUNK_SIZE)
77
/* spare chunks we keep for a full window */
78
0
#define H2_STREAM_POOL_SPARES   (H2_CONN_WINDOW_SIZE / H2_CHUNK_SIZE)
79
80
/* We need to accommodate the max number of streams with their window sizes on
81
 * the overall connection. Streams might become PAUSED which will block their
82
 * received QUOTA in the connection window. If we run out of space, the server
83
 * is blocked from sending us any data. See #10988 for an issue with this. */
84
0
#define HTTP2_HUGE_WINDOW_SIZE (100 * H2_STREAM_WINDOW_SIZE_MAX)
85
86
#define H2_SETTINGS_IV_LEN 3
87
0
#define H2_BINSETTINGS_LEN 80
88
89
struct cf_h2_ctx {
90
  nghttp2_session *h2;
91
  /* The easy handle used in the current filter call, cleared at return */
92
  struct cf_call_data call_data;
93
94
  struct bufq inbufq;           /* network input */
95
  struct bufq outbufq;          /* network output */
96
  struct bufc_pool stream_bufcp; /* spares for stream buffers */
97
  struct dynbuf scratch;        /* scratch buffer for temp use */
98
99
  struct uint_hash streams; /* hash of `data->mid` to `h2_stream_ctx` */
100
  size_t drain_total; /* sum of all stream's UrlState drain */
101
  uint32_t initial_win_size; /* current initial window size (settings) */
102
  uint32_t max_concurrent_streams;
103
  uint32_t goaway_error;        /* goaway error code from server */
104
  int32_t remote_max_sid;       /* max id processed by server */
105
  int32_t local_max_sid;        /* max id processed by us */
106
  BIT(initialized);
107
  BIT(via_h1_upgrade);
108
  BIT(conn_closed);
109
  BIT(rcvd_goaway);
110
  BIT(sent_goaway);
111
  BIT(enable_push);
112
  BIT(nw_out_blocked);
113
};
114
115
/* How to access `call_data` from a cf_h2 filter */
116
#undef CF_CTX_CALL_DATA
117
0
#define CF_CTX_CALL_DATA(cf) ((struct cf_h2_ctx *)(cf)->ctx)->call_data
118
119
/**
120
 * All about the H2 internals of a stream
121
 */
122
struct h2_stream_ctx {
123
  struct bufq sendbuf; /* request buffer */
124
  struct h1_req_parser h1; /* parsing the request */
125
  struct dynhds resp_trailers; /* response trailer fields */
126
  size_t resp_hds_len; /* amount of response header bytes in recvbuf */
127
  curl_off_t nrcvd_data;  /* number of DATA bytes received */
128
129
  char **push_headers;       /* allocated array */
130
  size_t push_headers_used;  /* number of entries filled in */
131
  size_t push_headers_alloc; /* number of entries allocated */
132
133
  int status_code; /* HTTP response status code */
134
  uint32_t error; /* stream error code */
135
  CURLcode xfer_result; /* Result of writing out response */
136
  int32_t local_window_size; /* the local recv window size */
137
  int32_t id; /* HTTP/2 protocol identifier for stream */
138
  BIT(resp_hds_complete); /* we have a complete, final response */
139
  BIT(closed); /* TRUE on stream close */
140
  BIT(reset);  /* TRUE on stream reset */
141
  BIT(reset_by_server);  /* TRUE on stream reset by server */
142
  BIT(close_handled); /* TRUE if stream closure is handled by libcurl */
143
  BIT(bodystarted);
144
  BIT(body_eos);    /* the complete body has been added to `sendbuf` and
145
                     * is being/has been processed from there. */
146
  BIT(write_paused);  /* stream write is paused */
147
};
148
149
static void free_push_headers(struct h2_stream_ctx *stream)
150
0
{
151
0
  size_t i;
152
0
  for(i = 0; i < stream->push_headers_used; i++)
153
0
    curlx_free(stream->push_headers[i]);
154
0
  curlx_safefree(stream->push_headers);
155
0
  stream->push_headers_used = 0;
156
0
}
157
158
static void h2_stream_ctx_free(struct h2_stream_ctx *stream)
159
0
{
160
0
  Curl_bufq_free(&stream->sendbuf);
161
0
  Curl_h1_req_parse_free(&stream->h1);
162
0
  Curl_dynhds_free(&stream->resp_trailers);
163
0
  free_push_headers(stream);
164
0
  curlx_free(stream);
165
0
}
166
167
static void h2_stream_hash_free(unsigned int id, void *stream)
168
0
{
169
0
  (void)id;
170
0
  DEBUGASSERT(stream);
171
0
  h2_stream_ctx_free((struct h2_stream_ctx *)stream);
172
0
}
173
174
static void cf_h2_ctx_init(struct cf_h2_ctx *ctx, bool via_h1_upgrade)
175
0
{
176
0
  Curl_bufcp_init(&ctx->stream_bufcp, H2_CHUNK_SIZE, H2_STREAM_POOL_SPARES);
177
0
  Curl_bufq_initp(&ctx->inbufq, &ctx->stream_bufcp, H2_NW_RECV_CHUNKS, 0);
178
0
  Curl_bufq_initp(&ctx->outbufq, &ctx->stream_bufcp, H2_NW_SEND_CHUNKS, 0);
179
0
  curlx_dyn_init(&ctx->scratch, CURL_MAX_HTTP_HEADER);
180
0
  Curl_uint32_hash_init(&ctx->streams, 63, h2_stream_hash_free);
181
0
  ctx->remote_max_sid = 2147483647;
182
0
  ctx->via_h1_upgrade = via_h1_upgrade;
183
0
  ctx->initialized = TRUE;
184
0
}
185
186
static void cf_h2_ctx_free(struct cf_h2_ctx *ctx)
187
0
{
188
0
  if(ctx && ctx->initialized) {
189
0
    if(ctx->h2)
190
0
      nghttp2_session_del(ctx->h2);
191
0
    Curl_bufq_free(&ctx->inbufq);
192
0
    Curl_bufq_free(&ctx->outbufq);
193
0
    Curl_bufcp_free(&ctx->stream_bufcp);
194
0
    curlx_dyn_free(&ctx->scratch);
195
0
    Curl_uint32_hash_destroy(&ctx->streams);
196
0
    memset(ctx, 0, sizeof(*ctx));
197
0
  }
198
0
  curlx_free(ctx);
199
0
}
200
201
static uint32_t cf_h2_initial_win_size(struct Curl_easy *data)
202
0
{
203
0
#if NGHTTP2_HAS_SET_LOCAL_WINDOW_SIZE
204
  /* If the transfer has a rate-limit lower than the default initial
205
   * stream window size, use that. It needs to be at least 8k or servers
206
   * may be unhappy. */
207
0
  curl_off_t rps = Curl_rlimit_per_step(&data->progress.dl.rlimit);
208
0
  if((rps > 0) && (rps < H2_STREAM_WINDOW_SIZE_INITIAL))
209
0
    return CURLMAX((uint32_t)rps, 8192);
210
0
#endif
211
0
  return H2_STREAM_WINDOW_SIZE_INITIAL;
212
0
}
213
214
static size_t populate_settings(nghttp2_settings_entry *iv,
215
                                struct Curl_easy *data,
216
                                struct cf_h2_ctx *ctx)
217
0
{
218
0
  iv[0].settings_id = NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS;
219
0
  iv[0].value = Curl_multi_max_concurrent_streams(data->multi);
220
221
0
  iv[1].settings_id = NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE;
222
0
  iv[1].value = cf_h2_initial_win_size(data);
223
0
  if(ctx)
224
0
    ctx->initial_win_size = iv[1].value;
225
0
  iv[2].settings_id = NGHTTP2_SETTINGS_ENABLE_PUSH;
226
0
  iv[2].value = !!data->multi->push_cb;
227
228
0
  return 3;
229
0
}
230
231
static ssize_t populate_binsettings(uint8_t *binsettings,
232
                                    struct Curl_easy *data)
233
0
{
234
0
  nghttp2_settings_entry iv[H2_SETTINGS_IV_LEN];
235
0
  size_t ivlen;
236
237
0
  ivlen = populate_settings(iv, data, NULL);
238
  /* this returns number of bytes it wrote or a negative number on error. */
239
0
  return nghttp2_pack_settings_payload(binsettings, H2_BINSETTINGS_LEN,
240
0
                                       iv, ivlen);
241
0
}
242
243
static CURLcode cf_h2_update_settings(struct cf_h2_ctx *ctx,
244
                                      uint32_t initial_win_size)
245
0
{
246
0
  nghttp2_settings_entry entry;
247
0
  entry.settings_id = NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE;
248
0
  entry.value = initial_win_size;
249
0
  if(nghttp2_submit_settings(ctx->h2, NGHTTP2_FLAG_NONE, &entry, 1))
250
0
    return CURLE_SEND_ERROR;
251
0
  ctx->initial_win_size = initial_win_size;
252
0
  return CURLE_OK;
253
0
}
254
255
#define H2_STREAM_CTX(ctx, data)                                         \
256
0
  ((struct h2_stream_ctx *)(                                             \
257
0
    (data) ? Curl_uint32_hash_get(&(ctx)->streams, (data)->mid) : NULL))
258
259
static struct h2_stream_ctx *h2_stream_ctx_create(struct cf_h2_ctx *ctx)
260
0
{
261
0
  struct h2_stream_ctx *stream;
262
263
0
  (void)ctx;
264
0
  stream = curlx_calloc(1, sizeof(*stream));
265
0
  if(!stream)
266
0
    return NULL;
267
268
0
  stream->id = -1;
269
0
  Curl_bufq_initp(&stream->sendbuf, &ctx->stream_bufcp,
270
0
                  H2_STREAM_SEND_CHUNKS, BUFQ_OPT_NONE);
271
0
  Curl_h1_req_parse_init(&stream->h1, H1_PARSE_DEFAULT_MAX_LINE_LEN);
272
0
  Curl_dynhds_init(&stream->resp_trailers, 0, DYN_HTTP_REQUEST);
273
0
  stream->bodystarted = FALSE;
274
0
  stream->status_code = -1;
275
0
  stream->closed = FALSE;
276
0
  stream->close_handled = FALSE;
277
0
  stream->error = NGHTTP2_NO_ERROR;
278
0
  stream->local_window_size = H2_STREAM_WINDOW_SIZE_INITIAL;
279
0
  stream->nrcvd_data = 0;
280
0
  return stream;
281
0
}
282
283
#ifdef NGHTTP2_HAS_SET_LOCAL_WINDOW_SIZE
284
static int32_t cf_h2_get_desired_local_win(struct Curl_cfilter *cf,
285
                                           struct Curl_easy *data)
286
0
{
287
0
  curl_off_t avail = Curl_rlimit_avail(&data->progress.dl.rlimit,
288
0
                                       Curl_pgrs_now(data));
289
290
0
  (void)cf;
291
0
  if(avail < CURL_OFF_T_MAX) { /* limit in place */
292
0
    if(avail <= 0)
293
0
      return 0;
294
0
    else if(avail < INT32_MAX)
295
0
      return (int32_t)avail;
296
0
  }
297
0
  return H2_STREAM_WINDOW_SIZE_MAX;
298
0
}
299
300
static CURLcode cf_h2_update_local_win(struct Curl_cfilter *cf,
301
                                       struct Curl_easy *data,
302
                                       struct h2_stream_ctx *stream)
303
0
{
304
0
  struct cf_h2_ctx *ctx = cf->ctx;
305
0
  int32_t dwsize;
306
0
  int rv;
307
308
0
  dwsize = (stream->write_paused || stream->xfer_result) ?
309
0
           0 : cf_h2_get_desired_local_win(cf, data);
310
0
  if(dwsize != stream->local_window_size) {
311
0
    int32_t wsize = nghttp2_session_get_stream_effective_local_window_size(
312
0
                      ctx->h2, stream->id);
313
0
    if(dwsize > wsize) {
314
0
      rv = nghttp2_session_set_local_window_size(ctx->h2, NGHTTP2_FLAG_NONE,
315
0
                                                 stream->id, dwsize);
316
0
      if(rv) {
317
0
        failf(data, "[%d] nghttp2 set_local_window_size(%d) failed: "
318
0
              "%s(%d)", stream->id, dwsize, nghttp2_strerror(rv), rv);
319
0
        return CURLE_HTTP2;
320
0
      }
321
0
      rv = nghttp2_submit_window_update(ctx->h2, NGHTTP2_FLAG_NONE,
322
0
                                        stream->id, dwsize - wsize);
323
0
      if(rv) {
324
0
        failf(data, "[%d] nghttp2_submit_window_update() failed: "
325
0
              "%s(%d)", stream->id, nghttp2_strerror(rv), rv);
326
0
        return CURLE_HTTP2;
327
0
      }
328
0
      stream->local_window_size = dwsize;
329
0
      CURL_TRC_CF(data, cf, "[%d] local window update by %d",
330
0
                  stream->id, dwsize - wsize);
331
0
    }
332
0
    else {
333
0
      rv = nghttp2_session_set_local_window_size(ctx->h2, NGHTTP2_FLAG_NONE,
334
0
                                                 stream->id, dwsize);
335
0
      if(rv) {
336
0
        failf(data, "[%d] nghttp2_session_set_local_window_size() failed: "
337
0
              "%s(%d)", stream->id, nghttp2_strerror(rv), rv);
338
0
        return CURLE_HTTP2;
339
0
      }
340
0
      stream->local_window_size = dwsize;
341
0
      CURL_TRC_CF(data, cf, "[%d] local window size now %d",
342
0
                  stream->id, dwsize);
343
0
    }
344
0
  }
345
0
  return CURLE_OK;
346
0
}
347
348
#else /* NGHTTP2_HAS_SET_LOCAL_WINDOW_SIZE */
349
350
static CURLcode cf_h2_update_local_win(struct Curl_cfilter *cf,
351
                                       struct Curl_easy *data,
352
                                       struct h2_stream_ctx *stream)
353
{
354
  (void)cf;
355
  (void)data;
356
  (void)stream;
357
  return CURLE_OK;
358
}
359
#endif /* !NGHTTP2_HAS_SET_LOCAL_WINDOW_SIZE */
360
361
static CURLcode http2_data_setup(struct Curl_cfilter *cf,
362
                                 struct Curl_easy *data,
363
                                 struct h2_stream_ctx **pstream)
364
0
{
365
0
  struct cf_h2_ctx *ctx = cf->ctx;
366
0
  struct h2_stream_ctx *stream;
367
368
0
  (void)cf;
369
0
  DEBUGASSERT(data);
370
371
0
  if(!data)
372
0
    return CURLE_BAD_FUNCTION_ARGUMENT;
373
374
0
  stream = H2_STREAM_CTX(ctx, data);
375
0
  if(stream) {
376
0
    *pstream = stream;
377
0
    return CURLE_OK;
378
0
  }
379
380
0
  stream = h2_stream_ctx_create(ctx);
381
0
  if(!stream)
382
0
    return CURLE_OUT_OF_MEMORY;
383
384
0
  if(!Curl_uint32_hash_set(&ctx->streams, data->mid, stream)) {
385
0
    h2_stream_ctx_free(stream);
386
0
    return CURLE_OUT_OF_MEMORY;
387
0
  }
388
389
0
  *pstream = stream;
390
0
  return CURLE_OK;
391
0
}
392
393
static CURLcode nw_out_flush(struct Curl_cfilter *cf,
394
                             struct Curl_easy *data)
395
0
{
396
0
  struct cf_h2_ctx *ctx = cf->ctx;
397
0
  size_t nwritten;
398
0
  CURLcode result;
399
400
0
  if(Curl_bufq_is_empty(&ctx->outbufq))
401
0
    return CURLE_OK;
402
403
0
  result = Curl_cf_send_bufq(cf->next, data, &ctx->outbufq, NULL, 0,
404
0
                             &nwritten);
405
0
  if(result) {
406
0
    if(result == CURLE_AGAIN) {
407
0
      CURL_TRC_CF(data, cf, "flush nw send buffer(%zu) -> EAGAIN",
408
0
                  Curl_bufq_len(&ctx->outbufq));
409
0
      ctx->nw_out_blocked = 1;
410
0
    }
411
0
    return result;
412
0
  }
413
0
  return Curl_bufq_is_empty(&ctx->outbufq) ? CURLE_OK : CURLE_AGAIN;
414
0
}
415
416
static void http2_data_done(struct Curl_cfilter *cf, struct Curl_easy *data)
417
0
{
418
0
  struct cf_h2_ctx *ctx = cf->ctx;
419
0
  struct h2_stream_ctx *stream = H2_STREAM_CTX(ctx, data);
420
421
0
  DEBUGASSERT(ctx);
422
0
  if(!stream || !ctx->initialized)
423
0
    return;
424
425
0
  if(ctx->h2) {
426
0
    bool flush_egress = FALSE;
427
    /* returns error if stream not known, which is fine here */
428
0
    (void)nghttp2_session_set_stream_user_data(ctx->h2, stream->id, NULL);
429
430
0
    if(!stream->closed && stream->id > 0) {
431
      /* RST_STREAM */
432
0
      CURL_TRC_CF(data, cf, "[%d] premature DATA_DONE, RST stream",
433
0
                  stream->id);
434
0
      stream->closed = TRUE;
435
0
      stream->reset = TRUE;
436
0
      nghttp2_submit_rst_stream(ctx->h2, NGHTTP2_FLAG_NONE,
437
0
                                stream->id, NGHTTP2_STREAM_CLOSED);
438
0
      flush_egress = TRUE;
439
0
    }
440
441
0
    if(flush_egress) {
442
0
      (void)nghttp2_session_send(ctx->h2);
443
0
      (void)nw_out_flush(cf, data);
444
0
    }
445
0
  }
446
447
0
  Curl_uint32_hash_remove(&ctx->streams, data->mid);
448
0
}
449
450
static int h2_client_new(struct Curl_cfilter *cf,
451
                         nghttp2_session_callbacks *cbs)
452
0
{
453
0
  struct cf_h2_ctx *ctx = cf->ctx;
454
0
  nghttp2_option *o;
455
0
  nghttp2_mem mem = { NULL, Curl_nghttp2_malloc, Curl_nghttp2_free,
456
0
                      Curl_nghttp2_calloc, Curl_nghttp2_realloc };
457
458
0
  int rc = nghttp2_option_new(&o);
459
0
  if(rc)
460
0
    return rc;
461
  /* We handle window updates ourself to enforce buffer limits */
462
0
  nghttp2_option_set_no_auto_window_update(o, 1);
463
0
#if NGHTTP2_VERSION_NUM >= 0x013200 /* with 1.50.0 */
464
  /* turn off RFC 9113 leading and trailing white spaces validation against
465
     HTTP field value. */
466
0
  nghttp2_option_set_no_rfc9113_leading_and_trailing_ws_validation(o, 1);
467
0
#endif
468
0
  rc = nghttp2_session_client_new3(&ctx->h2, cbs, cf, o, &mem);
469
0
  nghttp2_option_del(o);
470
0
  return rc;
471
0
}
472
473
/*
474
 * Returns nonzero if current HTTP/2 session should be closed.
475
 */
476
static int should_close_session(struct cf_h2_ctx *ctx)
477
0
{
478
0
  return ctx->drain_total == 0 && !nghttp2_session_want_read(ctx->h2) &&
479
0
    !nghttp2_session_want_write(ctx->h2);
480
0
}
481
482
/*
483
 * Processes pending input left in network input buffer.
484
 * This function returns 0 if it succeeds, or -1 and error code will
485
 * be assigned to *err.
486
 */
487
static CURLcode h2_process_pending_input(struct Curl_cfilter *cf,
488
                                         struct Curl_easy *data)
489
0
{
490
0
  struct cf_h2_ctx *ctx = cf->ctx;
491
0
  const unsigned char *buf;
492
0
  size_t blen, nread;
493
0
  ssize_t rv;
494
495
0
  while(Curl_bufq_peek(&ctx->inbufq, &buf, &blen)) {
496
0
    rv = nghttp2_session_mem_recv(ctx->h2, (const uint8_t *)buf, blen);
497
0
    if(!curlx_sztouz(rv, &nread)) {
498
0
      failf(data, "nghttp2 recv error %zd: %s", rv, nghttp2_strerror((int)rv));
499
0
      return CURLE_HTTP2;
500
0
    }
501
0
    Curl_bufq_skip(&ctx->inbufq, nread);
502
0
    if(Curl_bufq_is_empty(&ctx->inbufq)) {
503
0
      break;
504
0
    }
505
0
    else {
506
0
      CURL_TRC_CF(data, cf, "process_pending_input: %zu bytes left "
507
0
                  "in connection buffer", Curl_bufq_len(&ctx->inbufq));
508
0
    }
509
0
  }
510
511
0
  if(nghttp2_session_check_request_allowed(ctx->h2) == 0) {
512
    /* No more requests are allowed in the current session, so
513
       the connection may not be reused. This is set when a
514
       GOAWAY frame has been received or when the limit of stream
515
       identifiers has been reached. */
516
0
    connclose(cf->conn, "http/2: No new requests allowed");
517
0
  }
518
519
0
  return CURLE_OK;
520
0
}
521
522
/*
523
 * The server may send us data at any point (e.g. PING frames). Therefore, we
524
 * cannot assume that an HTTP/2 socket is dead because it is readable.
525
 *
526
 * Check the lower filters first and, if successful, peek at the socket
527
 * and distinguish between closed and data.
528
 */
529
static bool http2_connisalive(struct Curl_cfilter *cf, struct Curl_easy *data,
530
                              bool *input_pending)
531
0
{
532
0
  struct cf_h2_ctx *ctx = cf->ctx;
533
0
  bool alive = TRUE;
534
535
0
  *input_pending = FALSE;
536
0
  if(!cf->next || !cf->next->cft->is_alive(cf->next, data, input_pending))
537
0
    return FALSE;
538
539
0
  if(*input_pending) {
540
    /* This happens before we have sent off a request and the connection is
541
       not in use by any other transfer, there should not be any data here,
542
       only "protocol frames" */
543
0
    CURLcode result;
544
0
    size_t nread;
545
546
0
    *input_pending = FALSE;
547
0
    result = Curl_cf_recv_bufq(cf->next, data, &ctx->inbufq, 0, &nread);
548
0
    if(!result) {
549
0
      CURL_TRC_CF(data, cf, "%zu bytes stray data read before trying "
550
0
                  "h2 connection", nread);
551
0
      result = h2_process_pending_input(cf, data);
552
0
      if(result)
553
        /* immediate error, considered dead */
554
0
        alive = FALSE;
555
0
      else {
556
0
        alive = !should_close_session(ctx);
557
0
      }
558
0
    }
559
0
    else if(result != CURLE_AGAIN) {
560
      /* the read failed so let's say this is dead anyway */
561
0
      alive = FALSE;
562
0
    }
563
0
  }
564
565
0
  return alive;
566
0
}
567
568
static CURLcode http2_send_ping(struct Curl_cfilter *cf,
569
                                struct Curl_easy *data)
570
0
{
571
0
  struct cf_h2_ctx *ctx = cf->ctx;
572
0
  int rc;
573
574
0
  rc = nghttp2_submit_ping(ctx->h2, 0, ZERO_NULL);
575
0
  if(rc) {
576
0
    failf(data, "nghttp2_submit_ping() failed: %s(%d)",
577
0
          nghttp2_strerror(rc), rc);
578
0
    return CURLE_HTTP2;
579
0
  }
580
581
0
  rc = nghttp2_session_send(ctx->h2);
582
0
  if(rc) {
583
0
    failf(data, "nghttp2_session_send() failed: %s(%d)",
584
0
          nghttp2_strerror(rc), rc);
585
0
    return CURLE_SEND_ERROR;
586
0
  }
587
0
  return CURLE_OK;
588
0
}
589
590
/*
591
 * Store nghttp2 version info in this buffer.
592
 */
593
void Curl_http2_ver(char *p, size_t len)
594
0
{
595
0
  nghttp2_info *h2 = nghttp2_version(0);
596
0
  (void)curl_msnprintf(p, len, "nghttp2/%s", h2->version_str);
597
0
}
598
599
/*
600
 * The implementation of nghttp2_send_callback type. Here we write |data| with
601
 * size |length| to the network and return the number of bytes actually
602
 * written. See the documentation of nghttp2_send_callback for the details.
603
 */
604
static ssize_t send_callback(nghttp2_session *h2,
605
                             const uint8_t *buf, size_t blen, int flags,
606
                             void *userp)
607
0
{
608
0
  struct Curl_cfilter *cf = userp;
609
0
  struct cf_h2_ctx *ctx = cf->ctx;
610
0
  struct Curl_easy *data = CF_DATA_CURRENT(cf);
611
0
  size_t nwritten;
612
0
  CURLcode result = CURLE_OK;
613
614
0
  (void)h2;
615
0
  (void)flags;
616
0
  DEBUGASSERT(data);
617
618
0
  if(!cf->connected)
619
0
    result = Curl_bufq_write(&ctx->outbufq, buf, blen, &nwritten);
620
0
  else
621
0
    result = Curl_cf_send_bufq(cf->next, data, &ctx->outbufq, buf, blen,
622
0
                               &nwritten);
623
624
0
  if(result) {
625
0
    if(result == CURLE_AGAIN) {
626
0
      ctx->nw_out_blocked = 1;
627
0
      return NGHTTP2_ERR_WOULDBLOCK;
628
0
    }
629
0
    failf(data, "Failed sending HTTP2 data");
630
0
    return NGHTTP2_ERR_CALLBACK_FAILURE;
631
0
  }
632
633
0
  if(!nwritten) {
634
0
    ctx->nw_out_blocked = 1;
635
0
    return NGHTTP2_ERR_WOULDBLOCK;
636
0
  }
637
0
  return (nwritten > SSIZE_MAX) ?
638
0
    NGHTTP2_ERR_CALLBACK_FAILURE : (ssize_t)nwritten;
639
0
}
640
641
/* We pass a pointer to this struct in the push callback, but the contents of
642
   the struct are hidden from the user. */
643
struct curl_pushheaders {
644
  struct Curl_easy *data;
645
  struct h2_stream_ctx *stream;
646
  const nghttp2_push_promise *frame;
647
};
648
649
/*
650
 * push header access function. Only to be used from within the push callback
651
 */
652
char *curl_pushheader_bynum(struct curl_pushheaders *h, size_t num)
653
0
{
654
  /* Verify that we got a good easy handle in the push header struct, mostly to
655
     detect rubbish input fast(er). */
656
0
  if(!h || !GOOD_EASY_HANDLE(h->data))
657
0
    return NULL;
658
0
  else {
659
0
    if(h->stream && num < h->stream->push_headers_used)
660
0
      return h->stream->push_headers[num];
661
0
  }
662
0
  return NULL;
663
0
}
664
665
/*
666
 * push header access function. Only to be used from within the push callback
667
 */
668
char *curl_pushheader_byname(struct curl_pushheaders *h, const char *name)
669
0
{
670
0
  struct h2_stream_ctx *stream;
671
0
  size_t len;
672
0
  size_t i;
673
  /* Verify that we got a good easy handle in the push header struct,
674
     mostly to detect rubbish input fast(er). Also empty header name
675
     is rubbish too. We have to allow ":" at the beginning of
676
     the header, but header == ":" must be rejected. If we have ':' in
677
     the middle of header, it could be matched in middle of the value,
678
     this is because we do prefix match.*/
679
0
  if(!h || !GOOD_EASY_HANDLE(h->data) || !name || !name[0] ||
680
0
     !strcmp(name, ":") || strchr(name + 1, ':'))
681
0
    return NULL;
682
683
0
  stream = h->stream;
684
0
  if(!stream)
685
0
    return NULL;
686
687
0
  len = strlen(name);
688
0
  for(i = 0; i < stream->push_headers_used; i++) {
689
0
    if(!strncmp(name, stream->push_headers[i], len)) {
690
      /* sub-match, make sure that it is followed by a colon */
691
0
      if(stream->push_headers[i][len] != ':')
692
0
        continue;
693
0
      return &stream->push_headers[i][len + 1];
694
0
    }
695
0
  }
696
0
  return NULL;
697
0
}
698
699
static struct Curl_easy *h2_duphandle(struct Curl_cfilter *cf,
700
                                      struct Curl_easy *data)
701
0
{
702
0
  struct Curl_easy *second = curl_easy_duphandle(data);
703
0
  if(second) {
704
0
    struct h2_stream_ctx *second_stream;
705
0
    http2_data_setup(cf, second, &second_stream);
706
0
    second->state.priority.weight = data->state.priority.weight;
707
0
  }
708
0
  return second;
709
0
}
710
711
static int set_transfer_url(struct Curl_easy *newhandle,
712
                            struct curl_pushheaders *hp,
713
                            struct Curl_easy *data)
714
0
{
715
0
  const char *v;
716
0
  CURLUcode uc;
717
0
  char *url = NULL;
718
0
  int rc = 0;
719
0
  CURLU *u = curl_url();
720
721
0
  if(!u)
722
0
    return 5;
723
724
0
  v = curl_pushheader_byname(hp, HTTP_PSEUDO_SCHEME);
725
0
  if(v) {
726
0
    uc = curl_url_set(u, CURLUPART_SCHEME, v, 0);
727
0
    if(uc) {
728
0
      rc = 1;
729
0
      goto fail;
730
0
    }
731
0
  }
732
733
0
  v = curl_pushheader_byname(hp, HTTP_PSEUDO_AUTHORITY);
734
0
  if(v) {
735
0
    uc = Curl_url_set_authority(u, v);
736
0
    if(uc) {
737
0
      rc = 2;
738
0
      goto fail;
739
0
    }
740
0
  }
741
742
0
  v = curl_pushheader_byname(hp, HTTP_PSEUDO_PATH);
743
0
  if(v) {
744
0
    uc = curl_url_set(u, CURLUPART_PATH, v, 0);
745
0
    if(uc) {
746
0
      rc = 3;
747
0
      goto fail;
748
0
    }
749
0
  }
750
751
  /* We can only allow PUSH of resource from the same origin, e.g.
752
   * scheme + hostname + port */
753
0
  if(!Curl_url_same_origin(data->state.uh, u)) {
754
0
    rc = 1;
755
0
    goto fail;
756
0
  }
757
758
0
  uc = curl_url_get(u, CURLUPART_URL, &url, 0);
759
0
  if(uc)
760
0
    rc = 4;
761
0
fail:
762
0
  curl_url_cleanup(u);
763
0
  if(rc)
764
0
    return rc;
765
766
0
  Curl_bufref_set(&newhandle->state.url, url, 0, curl_free);
767
0
  return 0;
768
0
}
769
770
static void discard_newhandle(struct Curl_cfilter *cf,
771
                              struct Curl_easy *newhandle)
772
0
{
773
0
  http2_data_done(cf, newhandle);
774
0
  (void)Curl_close(&newhandle);
775
0
}
776
777
static int push_promise(struct Curl_cfilter *cf,
778
                        struct Curl_easy *data,
779
                        const nghttp2_push_promise *frame)
780
0
{
781
0
  struct cf_h2_ctx *ctx = cf->ctx;
782
0
  int rv; /* one of the CURL_PUSH_* defines */
783
784
0
  CURL_TRC_CF(data, cf, "[%d] PUSH_PROMISE received",
785
0
              frame->promised_stream_id);
786
0
  if(data->multi->push_cb) {
787
0
    struct h2_stream_ctx *stream;
788
0
    struct h2_stream_ctx *newstream;
789
0
    struct curl_pushheaders heads;
790
0
    CURLMcode mresult;
791
0
    CURLcode result;
792
    /* clone the parent */
793
0
    struct Curl_easy *newhandle = h2_duphandle(cf, data);
794
0
    if(!newhandle) {
795
0
      infof(data, "failed to duplicate handle");
796
0
      rv = CURL_PUSH_DENY; /* FAIL HARD */
797
0
      goto fail;
798
0
    }
799
800
0
    stream = H2_STREAM_CTX(ctx, data);
801
0
    if(!stream) {
802
0
      failf(data, "Internal NULL stream");
803
0
      discard_newhandle(cf, newhandle);
804
0
      rv = CURL_PUSH_DENY;
805
0
      goto fail;
806
0
    }
807
808
0
    heads.data = data;
809
0
    heads.stream = stream;
810
0
    heads.frame = frame;
811
812
0
    rv = set_transfer_url(newhandle, &heads, data);
813
0
    if(rv) {
814
0
      CURL_TRC_CF(data, cf, "[%d] PUSH_PROMISE, failed to set URL -> %d",
815
0
                  frame->promised_stream_id, rv);
816
0
      discard_newhandle(cf, newhandle);
817
0
      rv = CURL_PUSH_DENY;
818
0
      goto fail;
819
0
    }
820
821
0
    Curl_set_in_callback(data, TRUE);
822
0
    rv = data->multi->push_cb(data, newhandle,
823
0
                              stream->push_headers_used, &heads,
824
0
                              data->multi->push_userp);
825
0
    Curl_set_in_callback(data, FALSE);
826
827
    /* free the headers again */
828
0
    free_push_headers(stream);
829
830
0
    if(rv) {
831
0
      DEBUGASSERT((rv > CURL_PUSH_OK) && (rv <= CURL_PUSH_ERROROUT));
832
      /* denied, kill off the new handle again */
833
0
      CURL_TRC_CF(data, cf, "[%d] PUSH_PROMISE, denied by application -> %d",
834
0
                  frame->promised_stream_id, rv);
835
0
      discard_newhandle(cf, newhandle);
836
0
      goto fail;
837
0
    }
838
839
    /* approved, add to the multi handle for processing. This
840
     * assigns newhandle->mid. For the new `mid` we assign the
841
     * h2_stream instance and remember the stream_id already known. */
842
0
    mresult = Curl_multi_add_perform(data->multi, newhandle, cf->conn);
843
0
    if(mresult) {
844
0
      infof(data, "failed to add handle to multi");
845
0
      discard_newhandle(cf, newhandle);
846
0
      rv = CURL_PUSH_DENY;
847
0
      goto fail;
848
0
    }
849
850
0
    result = http2_data_setup(cf, newhandle, &newstream);
851
0
    if(result) {
852
0
      failf(data, "error setting up stream: %d", (int)result);
853
0
      discard_newhandle(cf, newhandle);
854
0
      rv = CURL_PUSH_DENY;
855
0
      goto fail;
856
0
    }
857
858
0
    DEBUGASSERT(newstream);
859
0
    newstream->id = frame->promised_stream_id;
860
0
    newhandle->req.maxdownload = -1;
861
0
    newhandle->req.size = -1;
862
863
0
    CURL_TRC_CF(data, cf, "promise easy handle added to multi, mid=%u",
864
0
                newhandle->mid);
865
0
    rv = nghttp2_session_set_stream_user_data(ctx->h2,
866
0
                                              newstream->id,
867
0
                                              newhandle);
868
0
    if(rv) {
869
0
      infof(data, "failed to set user_data for stream %d",
870
0
            newstream->id);
871
0
      DEBUGASSERT(0);
872
0
      discard_newhandle(cf, newhandle);
873
0
      rv = CURL_PUSH_DENY;
874
0
      goto fail;
875
0
    }
876
877
    /* success, remember max stream id processed */
878
0
    if(newstream->id > ctx->local_max_sid)
879
0
      ctx->local_max_sid = newstream->id;
880
0
  }
881
0
  else {
882
0
    CURL_TRC_CF(data, cf, "Got PUSH_PROMISE, ignore it");
883
0
    rv = CURL_PUSH_DENY;
884
0
  }
885
0
fail:
886
0
  return rv;
887
0
}
888
889
static void h2_xfer_write_resp_hd(struct Curl_cfilter *cf,
890
                                  struct Curl_easy *data,
891
                                  struct h2_stream_ctx *stream,
892
                                  const char *buf, size_t blen, bool eos)
893
0
{
894
  /* If we already encountered an error, skip further writes */
895
0
  if(!stream->xfer_result) {
896
0
    stream->xfer_result = Curl_xfer_write_resp_hd(data, buf, blen, eos);
897
0
    if(!stream->xfer_result && !eos)
898
0
      stream->xfer_result = cf_h2_update_local_win(cf, data, stream);
899
0
    if(stream->xfer_result)
900
0
      CURL_TRC_CF(data, cf, "[%d] error %d writing %zu bytes of headers",
901
0
                  stream->id, (int)stream->xfer_result, blen);
902
0
  }
903
0
}
904
905
static void h2_xfer_write_resp(struct Curl_cfilter *cf,
906
                               struct Curl_easy *data,
907
                               struct h2_stream_ctx *stream,
908
                               const char *buf, size_t blen, bool eos)
909
0
{
910
  /* If we already encountered an error, skip further writes */
911
0
  if(!stream->xfer_result)
912
0
    stream->xfer_result = Curl_xfer_write_resp(data, buf, blen, eos);
913
  /* If the transfer write is errored, we do not want any more data */
914
0
  if(stream->xfer_result) {
915
0
    struct cf_h2_ctx *ctx = cf->ctx;
916
0
    CURL_TRC_CF(data, cf, "[%d] error %d writing %zu bytes of data, "
917
0
                "RST-ing stream",
918
0
                stream->id, (int)stream->xfer_result, blen);
919
0
    nghttp2_submit_rst_stream(ctx->h2, 0, stream->id,
920
0
                              (uint32_t)NGHTTP2_ERR_CALLBACK_FAILURE);
921
0
  }
922
0
  else if(!stream->write_paused && Curl_xfer_write_is_paused(data)) {
923
0
    CURL_TRC_CF(data, cf, "[%d] stream output paused", stream->id);
924
0
    stream->write_paused = TRUE;
925
0
  }
926
0
  else if(stream->write_paused && !Curl_xfer_write_is_paused(data)) {
927
0
    CURL_TRC_CF(data, cf, "[%d] stream output unpaused", stream->id);
928
0
    stream->write_paused = FALSE;
929
0
  }
930
931
0
  if(!stream->xfer_result && !eos)
932
0
    stream->xfer_result = cf_h2_update_local_win(cf, data, stream);
933
0
}
934
935
static CURLcode on_stream_frame(struct Curl_cfilter *cf,
936
                                struct Curl_easy *data,
937
                                const nghttp2_frame *frame)
938
0
{
939
0
  struct cf_h2_ctx *ctx = cf->ctx;
940
0
  struct h2_stream_ctx *stream = H2_STREAM_CTX(ctx, data);
941
0
  int32_t stream_id = frame->hd.stream_id;
942
0
  int rv;
943
944
0
  if(!stream) {
945
0
    CURL_TRC_CF(data, cf, "[%d] No stream_ctx set", stream_id);
946
0
    return CURLE_FAILED_INIT;
947
0
  }
948
949
0
  switch(frame->hd.type) {
950
0
  case NGHTTP2_DATA:
951
0
    CURL_TRC_CF(data, cf, "[%d] DATA, window=%d/%d",
952
0
                stream_id,
953
0
                nghttp2_session_get_stream_effective_recv_data_length(
954
0
                  ctx->h2, stream->id),
955
0
                nghttp2_session_get_stream_effective_local_window_size(
956
0
                  ctx->h2, stream->id));
957
    /* If !body started on this stream, then receiving DATA is illegal. */
958
0
    if(!stream->bodystarted) {
959
0
      rv = nghttp2_submit_rst_stream(ctx->h2, NGHTTP2_FLAG_NONE,
960
0
                                     stream_id, NGHTTP2_PROTOCOL_ERROR);
961
962
0
      if(nghttp2_is_fatal(rv)) {
963
0
        return CURLE_RECV_ERROR;
964
0
      }
965
0
    }
966
0
    break;
967
0
  case NGHTTP2_HEADERS:
968
0
    if(stream->bodystarted) {
969
      /* Only valid HEADERS after body started is trailer HEADERS. We
970
         buffer them in on_header callback. */
971
0
      break;
972
0
    }
973
974
    /* nghttp2 guarantees that :status is received, and we store it to
975
       stream->status_code. Fuzzing has proven this can still be reached
976
       without status code having been set. */
977
0
    if(stream->status_code == -1)
978
0
      return CURLE_RECV_ERROR;
979
980
    /* Only final status code signals the end of header */
981
0
    if(stream->status_code / 100 != 1)
982
0
      stream->bodystarted = TRUE;
983
0
    else
984
0
      stream->status_code = -1;
985
986
0
    h2_xfer_write_resp_hd(cf, data, stream, STRCONST("\r\n"),
987
0
                          (bool)stream->closed);
988
989
0
    if(stream->status_code / 100 != 1) {
990
0
      stream->resp_hds_complete = TRUE;
991
0
    }
992
0
    Curl_multi_mark_dirty(data);
993
0
    break;
994
0
  case NGHTTP2_PUSH_PROMISE:
995
0
    rv = push_promise(cf, data, &frame->push_promise);
996
0
    if(rv) { /* deny! */
997
0
      DEBUGASSERT((rv > CURL_PUSH_OK) && (rv <= CURL_PUSH_ERROROUT));
998
0
      rv = nghttp2_submit_rst_stream(ctx->h2, NGHTTP2_FLAG_NONE,
999
0
                                     frame->push_promise.promised_stream_id,
1000
0
                                     NGHTTP2_CANCEL);
1001
0
      if(nghttp2_is_fatal(rv))
1002
0
        return CURLE_SEND_ERROR;
1003
0
      else if(rv == CURL_PUSH_ERROROUT) {
1004
0
        CURL_TRC_CF(data, cf, "[%d] fail in PUSH_PROMISE received",
1005
0
                    stream_id);
1006
0
        return CURLE_RECV_ERROR;
1007
0
      }
1008
0
    }
1009
0
    break;
1010
0
  case NGHTTP2_RST_STREAM:
1011
0
    if(frame->rst_stream.error_code)
1012
0
      stream->reset_by_server = TRUE;
1013
0
    Curl_multi_mark_dirty(data);
1014
0
    break;
1015
0
  case NGHTTP2_WINDOW_UPDATE:
1016
0
    if(CURL_REQ_WANT_SEND(data) && Curl_bufq_is_empty(&stream->sendbuf)) {
1017
      /* need more data, force processing of transfer */
1018
0
      Curl_multi_mark_dirty(data);
1019
0
    }
1020
0
    else if(!Curl_bufq_is_empty(&stream->sendbuf)) {
1021
      /* resume the potentially suspended stream */
1022
0
      rv = nghttp2_session_resume_data(ctx->h2, stream->id);
1023
0
      if(nghttp2_is_fatal(rv))
1024
0
        return CURLE_SEND_ERROR;
1025
0
    }
1026
0
    break;
1027
0
  default:
1028
0
    break;
1029
0
  }
1030
1031
0
  if(frame->hd.flags & NGHTTP2_FLAG_END_STREAM) {
1032
0
    if(!stream->closed && !stream->body_eos &&
1033
0
       ((stream->status_code >= 400) || (stream->status_code < 200))) {
1034
      /* The server did not give us a positive response and we are not
1035
       * done uploading the request body. We need to stop doing that and
1036
       * also inform the server that we aborted our side. */
1037
0
      CURL_TRC_CF(data, cf, "[%d] EOS frame with unfinished upload and "
1038
0
                  "HTTP status %d, abort upload by RST",
1039
0
                  stream_id, stream->status_code);
1040
0
      nghttp2_submit_rst_stream(ctx->h2, NGHTTP2_FLAG_NONE,
1041
0
                                stream->id, NGHTTP2_STREAM_CLOSED);
1042
0
      stream->closed = TRUE;
1043
0
    }
1044
0
    Curl_multi_mark_dirty(data);
1045
0
  }
1046
0
  return CURLE_OK;
1047
0
}
1048
1049
#ifdef CURLVERBOSE
1050
int Curl_nghttp2_fr_print(const nghttp2_frame *frame, char *buffer,
1051
                          size_t blen)
1052
0
{
1053
0
  switch(frame->hd.type) {
1054
0
  case NGHTTP2_DATA: {
1055
0
    return curl_msnprintf(buffer, blen,
1056
0
                          "FRAME[DATA, len=%d, eos=%d, padlen=%d]",
1057
0
                          (int)frame->hd.length,
1058
0
                          !!(frame->hd.flags & NGHTTP2_FLAG_END_STREAM),
1059
0
                          (int)frame->data.padlen);
1060
0
  }
1061
0
  case NGHTTP2_HEADERS: {
1062
0
    return curl_msnprintf(buffer, blen,
1063
0
                          "FRAME[HEADERS, len=%d, hend=%d, eos=%d]",
1064
0
                          (int)frame->hd.length,
1065
0
                          !!(frame->hd.flags & NGHTTP2_FLAG_END_HEADERS),
1066
0
                          !!(frame->hd.flags & NGHTTP2_FLAG_END_STREAM));
1067
0
  }
1068
0
  case NGHTTP2_PRIORITY: {
1069
0
    return curl_msnprintf(buffer, blen,
1070
0
                          "FRAME[PRIORITY, len=%d, flags=%d]",
1071
0
                          (int)frame->hd.length, frame->hd.flags);
1072
0
  }
1073
0
  case NGHTTP2_RST_STREAM: {
1074
0
    return curl_msnprintf(buffer, blen,
1075
0
                          "FRAME[RST_STREAM, len=%d, flags=%d, error=%u]",
1076
0
                          (int)frame->hd.length, frame->hd.flags,
1077
0
                          frame->rst_stream.error_code);
1078
0
  }
1079
0
  case NGHTTP2_SETTINGS: {
1080
0
    if(frame->hd.flags & NGHTTP2_FLAG_ACK) {
1081
0
      return curl_msnprintf(buffer, blen, "FRAME[SETTINGS, ack=1]");
1082
0
    }
1083
0
    return curl_msnprintf(buffer, blen,
1084
0
                          "FRAME[SETTINGS, len=%d]", (int)frame->hd.length);
1085
0
  }
1086
0
  case NGHTTP2_PUSH_PROMISE:
1087
0
    return curl_msnprintf(buffer, blen,
1088
0
                          "FRAME[PUSH_PROMISE, len=%d, hend=%d]",
1089
0
                          (int)frame->hd.length,
1090
0
                          !!(frame->hd.flags & NGHTTP2_FLAG_END_HEADERS));
1091
0
  case NGHTTP2_PING:
1092
0
    return curl_msnprintf(buffer, blen,
1093
0
                          "FRAME[PING, len=%d, ack=%d]",
1094
0
                          (int)frame->hd.length,
1095
0
                          frame->hd.flags & NGHTTP2_FLAG_ACK);
1096
0
  case NGHTTP2_GOAWAY: {
1097
0
    char scratch[128];
1098
0
    size_t s_len = CURL_ARRAYSIZE(scratch);
1099
0
    size_t len = (frame->goaway.opaque_data_len < s_len) ?
1100
0
      frame->goaway.opaque_data_len : s_len - 1;
1101
0
    if(len)
1102
0
      memcpy(scratch, frame->goaway.opaque_data, len);
1103
0
    scratch[len] = '\0';
1104
0
    return curl_msnprintf(buffer, blen,
1105
0
                          "FRAME[GOAWAY, error=%u, reason='%s', "
1106
0
                          "last_stream=%d]", frame->goaway.error_code,
1107
0
                          scratch, frame->goaway.last_stream_id);
1108
0
  }
1109
0
  case NGHTTP2_WINDOW_UPDATE: {
1110
0
    return curl_msnprintf(buffer, blen,
1111
0
                          "FRAME[WINDOW_UPDATE, incr=%d]",
1112
0
                          frame->window_update.window_size_increment);
1113
0
  }
1114
0
  default:
1115
0
    return curl_msnprintf(buffer, blen, "FRAME[%d, len=%d, flags=%d]",
1116
0
                          frame->hd.type, (int)frame->hd.length,
1117
0
                          frame->hd.flags);
1118
0
  }
1119
0
}
1120
1121
static int on_frame_send(nghttp2_session *session, const nghttp2_frame *frame,
1122
                         void *userp)
1123
0
{
1124
0
  struct Curl_cfilter *cf = userp;
1125
0
  struct cf_h2_ctx *ctx = cf->ctx;
1126
0
  struct Curl_easy *data = CF_DATA_CURRENT(cf);
1127
1128
0
  (void)session;
1129
0
  DEBUGASSERT(data);
1130
0
  if(Curl_trc_cf_is_verbose(cf, data)) {
1131
0
    char buffer[256];
1132
0
    int len;
1133
0
    len = Curl_nghttp2_fr_print(frame, buffer, sizeof(buffer) - 1);
1134
0
    buffer[len] = 0;
1135
0
    CURL_TRC_CF(data, cf, "[%d] -> %s", frame->hd.stream_id, buffer);
1136
0
  }
1137
0
  if((frame->hd.type == NGHTTP2_GOAWAY) && !ctx->sent_goaway) {
1138
    /* A GOAWAY not initiated by us, but by nghttp2 itself on detecting
1139
     * a protocol error on the connection */
1140
0
    failf(data, "nghttp2 shuts down connection with error %u: %s",
1141
0
          frame->goaway.error_code,
1142
0
          nghttp2_http2_strerror(frame->goaway.error_code));
1143
0
  }
1144
0
  return 0;
1145
0
}
1146
#endif /* CURLVERBOSE */
1147
1148
static int on_frame_recv(nghttp2_session *session, const nghttp2_frame *frame,
1149
                         void *userp)
1150
0
{
1151
0
  struct Curl_cfilter *cf = userp;
1152
0
  struct cf_h2_ctx *ctx = cf->ctx;
1153
0
  struct Curl_easy *data = CF_DATA_CURRENT(cf), *data_s;
1154
0
  int32_t stream_id = frame->hd.stream_id;
1155
1156
0
  DEBUGASSERT(data);
1157
0
#ifdef CURLVERBOSE
1158
0
  if(Curl_trc_cf_is_verbose(cf, data)) {
1159
0
    char buffer[256];
1160
0
    int len;
1161
0
    len = Curl_nghttp2_fr_print(frame, buffer, sizeof(buffer) - 1);
1162
0
    buffer[len] = 0;
1163
0
    CURL_TRC_CF(data, cf, "[%d] <- %s", frame->hd.stream_id, buffer);
1164
0
  }
1165
0
#endif /* CURLVERBOSE */
1166
1167
0
  if(!stream_id) {
1168
    /* stream ID zero is for connection-oriented stuff */
1169
0
    DEBUGASSERT(data);
1170
0
    switch(frame->hd.type) {
1171
0
    case NGHTTP2_SETTINGS: {
1172
0
      if(!(frame->hd.flags & NGHTTP2_FLAG_ACK)) {
1173
0
        uint32_t max_conn = ctx->max_concurrent_streams;
1174
0
        ctx->max_concurrent_streams = nghttp2_session_get_remote_settings(
1175
0
          session, NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS);
1176
0
        ctx->enable_push = nghttp2_session_get_remote_settings(
1177
0
          session, NGHTTP2_SETTINGS_ENABLE_PUSH) != 0;
1178
0
        CURL_TRC_CF(data, cf, "[0] MAX_CONCURRENT_STREAMS: %u",
1179
0
                    ctx->max_concurrent_streams);
1180
0
        CURL_TRC_CF(data, cf, "[0] ENABLE_PUSH: %s",
1181
0
                    ctx->enable_push ? "TRUE" : "false");
1182
0
        if(data && max_conn != ctx->max_concurrent_streams) {
1183
          /* only signal change if the value actually changed */
1184
0
          CURL_TRC_CF(data, cf, "[0] notify MAX_CONCURRENT_STREAMS: %u",
1185
0
                      ctx->max_concurrent_streams);
1186
0
          Curl_multi_connchanged(data->multi);
1187
0
        }
1188
        /* Since the initial stream window is 64K, a request might be on HOLD,
1189
         * due to exhaustion. The (initial) SETTINGS may announce a much larger
1190
         * window and *assume* that we treat this like a WINDOW_UPDATE. Some
1191
         * servers send an explicit WINDOW_UPDATE, but not all seem to do that.
1192
         * To be safe, we UNHOLD a stream in order not to stall. */
1193
0
        if(CURL_REQ_WANT_SEND(data))
1194
0
          Curl_multi_mark_dirty(data);
1195
0
      }
1196
0
      break;
1197
0
    }
1198
0
    case NGHTTP2_GOAWAY:
1199
0
      ctx->rcvd_goaway = TRUE;
1200
0
      ctx->goaway_error = frame->goaway.error_code;
1201
0
      ctx->remote_max_sid = frame->goaway.last_stream_id;
1202
0
      if(data) {
1203
0
        infof(data, "received GOAWAY, error=%u, last_stream=%d",
1204
0
              ctx->goaway_error, ctx->remote_max_sid);
1205
0
        Curl_multi_connchanged(data->multi);
1206
0
      }
1207
0
      break;
1208
0
    default:
1209
0
      break;
1210
0
    }
1211
0
    return 0;
1212
0
  }
1213
1214
0
  data_s = nghttp2_session_get_stream_user_data(session, stream_id);
1215
0
  if(!data_s) {
1216
0
    CURL_TRC_CF(data, cf, "[%d] No Curl_easy associated", stream_id);
1217
0
    return 0;
1218
0
  }
1219
1220
0
  return on_stream_frame(cf, data_s, frame) ? NGHTTP2_ERR_CALLBACK_FAILURE : 0;
1221
0
}
1222
1223
static int cf_h2_on_invalid_frame_recv(nghttp2_session *session,
1224
                                       const nghttp2_frame *frame,
1225
                                       int ngerr, void *userp)
1226
0
{
1227
0
  struct Curl_cfilter *cf = userp;
1228
0
  struct cf_h2_ctx *ctx = cf->ctx;
1229
0
  struct Curl_easy *data;
1230
0
  int32_t stream_id = frame->hd.stream_id;
1231
1232
0
  data = nghttp2_session_get_stream_user_data(session, stream_id);
1233
0
  if(data) {
1234
0
    struct h2_stream_ctx *stream;
1235
0
#ifdef CURLVERBOSE
1236
0
    char buffer[256];
1237
0
    int len;
1238
0
    len = Curl_nghttp2_fr_print(frame, buffer, sizeof(buffer) - 1);
1239
0
    buffer[len] = 0;
1240
0
    failf(data, "[HTTP2] [%d] received invalid frame: %s, error %d: %s",
1241
0
          stream_id, buffer, ngerr, nghttp2_strerror(ngerr));
1242
0
#endif /* CURLVERBOSE */
1243
0
    stream = H2_STREAM_CTX(ctx, data);
1244
0
    if(stream) {
1245
0
      nghttp2_submit_rst_stream(ctx->h2, NGHTTP2_FLAG_NONE,
1246
0
                                stream->id, NGHTTP2_STREAM_CLOSED);
1247
0
      stream->error = ngerr;
1248
0
      stream->closed = TRUE;
1249
0
      stream->reset = TRUE;
1250
0
      return 0;  /* keep the connection alive */
1251
0
    }
1252
0
  }
1253
0
  return NGHTTP2_ERR_CALLBACK_FAILURE;
1254
0
}
1255
1256
static int on_data_chunk_recv(nghttp2_session *session, uint8_t flags,
1257
                              int32_t stream_id,
1258
                              const uint8_t *mem, size_t len, void *userp)
1259
0
{
1260
0
  struct Curl_cfilter *cf = userp;
1261
0
  struct cf_h2_ctx *ctx = cf->ctx;
1262
0
  struct h2_stream_ctx *stream;
1263
0
  struct Curl_easy *data_s;
1264
0
  (void)flags;
1265
1266
0
  DEBUGASSERT(stream_id); /* should never be a zero stream ID here */
1267
0
  DEBUGASSERT(CF_DATA_CURRENT(cf));
1268
1269
  /* get the stream from the hash based on Stream ID */
1270
0
  data_s = nghttp2_session_get_stream_user_data(session, stream_id);
1271
0
  if(!data_s) {
1272
    /* Receiving a Stream ID not in the hash should not happen - unless
1273
       we have aborted a transfer artificially and there were more data
1274
       in the pipeline. Silently ignore. */
1275
0
    CURL_TRC_CF(CF_DATA_CURRENT(cf), cf, "[%d] Data for unknown", stream_id);
1276
    /* consumed explicitly as no one will read it */
1277
0
    nghttp2_session_consume(session, stream_id, len);
1278
0
    return 0;
1279
0
  }
1280
1281
0
  stream = H2_STREAM_CTX(ctx, data_s);
1282
0
  if(!stream)
1283
0
    return NGHTTP2_ERR_CALLBACK_FAILURE;
1284
1285
0
  h2_xfer_write_resp(cf, data_s, stream, (const char *)mem, len, FALSE);
1286
1287
0
  nghttp2_session_consume(ctx->h2, stream_id, len);
1288
0
  stream->nrcvd_data += (curl_off_t)len;
1289
0
  return 0;
1290
0
}
1291
1292
static int on_stream_close(nghttp2_session *session, int32_t stream_id,
1293
                           uint32_t error_code, void *userp)
1294
0
{
1295
0
  struct Curl_cfilter *cf = userp;
1296
0
  struct cf_h2_ctx *ctx = cf->ctx;
1297
0
  struct Curl_easy *data_s, *call_data = CF_DATA_CURRENT(cf);
1298
0
  struct h2_stream_ctx *stream;
1299
0
  int rv;
1300
0
  (void)session;
1301
1302
0
  DEBUGASSERT(call_data);
1303
  /* stream id 0 is the connection, do not look there for streams. */
1304
0
  data_s = stream_id ?
1305
0
    nghttp2_session_get_stream_user_data(session, stream_id) : NULL;
1306
0
  if(!data_s) {
1307
0
    CURL_TRC_CF(call_data, cf,
1308
0
                "[%d] on_stream_close, no easy set on stream", stream_id);
1309
0
    return 0;
1310
0
  }
1311
0
  if(!GOOD_EASY_HANDLE(data_s)) {
1312
    /* nghttp2 still has an easy registered for the stream which has
1313
     * been freed be libcurl. This points to a code path that does not
1314
     * trigger DONE or DETACH events as it must. */
1315
0
    CURL_TRC_CF(call_data, cf,
1316
0
                "[%d] on_stream_close, not a GOOD easy on stream", stream_id);
1317
0
    (void)nghttp2_session_set_stream_user_data(session, stream_id, 0);
1318
0
    return NGHTTP2_ERR_CALLBACK_FAILURE;
1319
0
  }
1320
0
  stream = H2_STREAM_CTX(ctx, data_s);
1321
0
  if(!stream) {
1322
0
    CURL_TRC_CF(data_s, cf,
1323
0
                "[%d] on_stream_close, GOOD easy but no stream", stream_id);
1324
0
    return NGHTTP2_ERR_CALLBACK_FAILURE;
1325
0
  }
1326
1327
0
  stream->closed = TRUE;
1328
0
  stream->error = error_code;
1329
0
  if(stream->error)
1330
0
    stream->reset = TRUE;
1331
1332
0
  if(stream->error)
1333
0
    CURL_TRC_CF(data_s, cf, "[%d] RESET: %s (err %u)",
1334
0
              stream_id, nghttp2_http2_strerror(error_code), error_code);
1335
0
  else
1336
0
    CURL_TRC_CF(data_s, cf, "[%d] CLOSED", stream_id);
1337
0
  Curl_multi_mark_dirty(data_s);
1338
1339
  /* remove `data_s` from the nghttp2 stream */
1340
0
  rv = nghttp2_session_set_stream_user_data(session, stream_id, 0);
1341
0
  if(rv) {
1342
0
    infof(data_s, "http/2: failed to clear user_data for stream %d",
1343
0
          stream_id);
1344
0
    DEBUGASSERT(0);
1345
0
  }
1346
0
  return 0;
1347
0
}
1348
1349
static int on_begin_headers(nghttp2_session *session,
1350
                            const nghttp2_frame *frame, void *userp)
1351
0
{
1352
0
  struct Curl_cfilter *cf = userp;
1353
0
  struct cf_h2_ctx *ctx = cf->ctx;
1354
0
  struct h2_stream_ctx *stream;
1355
0
  struct Curl_easy *data_s = NULL;
1356
1357
0
  (void)cf;
1358
0
  data_s = nghttp2_session_get_stream_user_data(session, frame->hd.stream_id);
1359
0
  if(!data_s) {
1360
0
    return 0;
1361
0
  }
1362
1363
0
  if(frame->hd.type != NGHTTP2_HEADERS) {
1364
0
    return 0;
1365
0
  }
1366
1367
0
  stream = H2_STREAM_CTX(ctx, data_s);
1368
0
  if(!stream || !stream->bodystarted) {
1369
0
    return 0;
1370
0
  }
1371
1372
0
  return 0;
1373
0
}
1374
1375
static void cf_h2_header_error(struct Curl_cfilter *cf,
1376
                               struct Curl_easy *data,
1377
                               struct h2_stream_ctx *stream,
1378
                               CURLcode result)
1379
0
{
1380
0
  struct cf_h2_ctx *ctx = cf->ctx;
1381
1382
0
  failf(data, "Error receiving HTTP2 header: %d(%s)", (int)result,
1383
0
        curl_easy_strerror(result));
1384
0
  if(stream) {
1385
0
    nghttp2_submit_rst_stream(ctx->h2, NGHTTP2_FLAG_NONE,
1386
0
                              stream->id, NGHTTP2_STREAM_CLOSED);
1387
0
    stream->closed = TRUE;
1388
0
    stream->reset = TRUE;
1389
0
  }
1390
0
}
1391
1392
/* frame->hd.type is either NGHTTP2_HEADERS or NGHTTP2_PUSH_PROMISE */
1393
static int on_header(nghttp2_session *session, const nghttp2_frame *frame,
1394
                     const uint8_t *name, size_t namelen,
1395
                     const uint8_t *value, size_t valuelen,
1396
                     uint8_t flags,
1397
                     void *userp)
1398
0
{
1399
0
  struct Curl_cfilter *cf = userp;
1400
0
  struct cf_h2_ctx *ctx = cf->ctx;
1401
0
  struct h2_stream_ctx *stream;
1402
0
  struct Curl_easy *data;
1403
0
  int32_t stream_id = frame->hd.stream_id;
1404
0
  CURLcode result;
1405
0
  (void)flags;
1406
1407
0
  DEBUGASSERT(stream_id); /* should never be a zero stream ID here */
1408
1409
  /* get the stream from the hash based on Stream ID */
1410
0
  data = nghttp2_session_get_stream_user_data(session, stream_id);
1411
0
  if(!GOOD_EASY_HANDLE(data))
1412
    /* Receiving a Stream ID not in the hash should not happen, this is an
1413
       internal error more than anything else! */
1414
0
    return NGHTTP2_ERR_CALLBACK_FAILURE;
1415
1416
0
  stream = H2_STREAM_CTX(ctx, data);
1417
0
  if(!stream) {
1418
0
    failf(data, "Internal NULL stream");
1419
0
    return NGHTTP2_ERR_CALLBACK_FAILURE;
1420
0
  }
1421
1422
  /* Store received PUSH_PROMISE headers to be used when the subsequent
1423
     PUSH_PROMISE callback comes */
1424
0
  if(frame->hd.type == NGHTTP2_PUSH_PROMISE) {
1425
0
    char *h;
1426
1427
0
    if((namelen == (sizeof(HTTP_PSEUDO_AUTHORITY) - 1)) &&
1428
0
       !strncmp(HTTP_PSEUDO_AUTHORITY, (const char *)name, namelen)) {
1429
      /* pseudo headers are lower case */
1430
0
      int rc = 0;
1431
0
      char *check = curl_maprintf("%s:%d", data->state.origin->hostname,
1432
0
                                  data->state.origin->port);
1433
0
      if(!check)
1434
        /* no memory */
1435
0
        return NGHTTP2_ERR_CALLBACK_FAILURE;
1436
0
      if(!curl_strequal(check, (const char *)value) &&
1437
0
         ((data->state.origin->port != cf->conn->given->defport) ||
1438
0
          !curl_strequal(data->state.origin->hostname, (const char *)value))) {
1439
        /* This is push is not for the same authority that was asked for in
1440
         * the URL. RFC 7540 section 8.2 says: "A client MUST treat a
1441
         * PUSH_PROMISE for which the server is not authoritative as a stream
1442
         * error of type PROTOCOL_ERROR."
1443
         */
1444
0
        (void)nghttp2_submit_rst_stream(session, NGHTTP2_FLAG_NONE,
1445
0
                                        stream_id, NGHTTP2_PROTOCOL_ERROR);
1446
0
        rc = NGHTTP2_ERR_CALLBACK_FAILURE;
1447
0
      }
1448
0
      curlx_free(check);
1449
0
      if(rc)
1450
0
        return rc;
1451
0
    }
1452
1453
0
    if(!stream->push_headers) {
1454
0
      stream->push_headers_alloc = 10;
1455
0
      stream->push_headers = curlx_malloc(stream->push_headers_alloc *
1456
0
                                          sizeof(char *));
1457
0
      if(!stream->push_headers)
1458
0
        return NGHTTP2_ERR_CALLBACK_FAILURE;
1459
0
      stream->push_headers_used = 0;
1460
0
    }
1461
0
    else if(stream->push_headers_used ==
1462
0
            stream->push_headers_alloc) {
1463
0
      char **headp;
1464
0
      if(stream->push_headers_alloc > 1000) {
1465
        /* this is beyond crazy many headers, bail out */
1466
0
        failf(data, "Too many PUSH_PROMISE headers");
1467
0
        free_push_headers(stream);
1468
0
        return NGHTTP2_ERR_CALLBACK_FAILURE;
1469
0
      }
1470
0
      stream->push_headers_alloc *= 2;
1471
0
      headp = curlx_realloc(stream->push_headers,
1472
0
                            stream->push_headers_alloc * sizeof(char *));
1473
0
      if(!headp) {
1474
0
        free_push_headers(stream);
1475
0
        return NGHTTP2_ERR_CALLBACK_FAILURE;
1476
0
      }
1477
0
      stream->push_headers = headp;
1478
0
    }
1479
0
    h = curl_maprintf("%s:%s", name, value);
1480
0
    if(!h) {
1481
0
      free_push_headers(stream);
1482
0
      return NGHTTP2_ERR_CALLBACK_FAILURE;
1483
0
    }
1484
0
    stream->push_headers[stream->push_headers_used++] = h;
1485
0
    return 0;
1486
0
  }
1487
1488
0
  if(stream->bodystarted) {
1489
    /* This is a trailer */
1490
0
    CURL_TRC_CF(data, cf, "[%d] trailer: %.*s: %.*s",
1491
0
                stream->id, (int)namelen, name, (int)valuelen, value);
1492
0
    result = Curl_dynhds_add(&stream->resp_trailers,
1493
0
                             (const char *)name, namelen,
1494
0
                             (const char *)value, valuelen);
1495
0
    if(result) {
1496
0
      cf_h2_header_error(cf, data, stream, result);
1497
0
      return NGHTTP2_ERR_CALLBACK_FAILURE;
1498
0
    }
1499
1500
0
    return 0;
1501
0
  }
1502
1503
0
  if(namelen == sizeof(HTTP_PSEUDO_STATUS) - 1 &&
1504
0
     !memcmp(HTTP_PSEUDO_STATUS, name, namelen)) {
1505
    /* nghttp2 guarantees :status is received first and only once. */
1506
0
    char buffer[32];
1507
0
    size_t hlen;
1508
0
    result = Curl_http_decode_status(&stream->status_code,
1509
0
                                     (const char *)value, valuelen);
1510
0
    if(result) {
1511
0
      cf_h2_header_error(cf, data, stream, result);
1512
0
      return NGHTTP2_ERR_CALLBACK_FAILURE;
1513
0
    }
1514
0
    hlen = curl_msnprintf(buffer, sizeof(buffer), HTTP_PSEUDO_STATUS ":%d\r",
1515
0
                          stream->status_code);
1516
0
    result = Curl_headers_push(data, buffer, hlen, CURLH_PSEUDO);
1517
0
    if(result) {
1518
0
      cf_h2_header_error(cf, data, stream, result);
1519
0
      return NGHTTP2_ERR_CALLBACK_FAILURE;
1520
0
    }
1521
0
    curlx_dyn_reset(&ctx->scratch);
1522
0
    result = curlx_dyn_addn(&ctx->scratch, STRCONST("HTTP/2 "));
1523
0
    if(!result)
1524
0
      result = curlx_dyn_addn(&ctx->scratch, value, valuelen);
1525
0
    if(!result)
1526
0
      result = curlx_dyn_addn(&ctx->scratch, STRCONST(" \r\n"));
1527
0
    if(!result)
1528
0
      h2_xfer_write_resp_hd(cf, data, stream, curlx_dyn_ptr(&ctx->scratch),
1529
0
                            curlx_dyn_len(&ctx->scratch), FALSE);
1530
0
    if(result) {
1531
0
      cf_h2_header_error(cf, data, stream, result);
1532
0
      return NGHTTP2_ERR_CALLBACK_FAILURE;
1533
0
    }
1534
    /* if we receive data for another handle, wake that up */
1535
0
    if(CF_DATA_CURRENT(cf) != data)
1536
0
      Curl_multi_mark_dirty(data);
1537
1538
0
    CURL_TRC_CF(data, cf, "[%d] status: HTTP/2 %03d",
1539
0
                stream->id, stream->status_code);
1540
0
    return 0;
1541
0
  }
1542
1543
  /* nghttp2 guarantees that namelen > 0, and :status was already
1544
     received, and this is not pseudo-header field . */
1545
  /* convert to an HTTP1-style header */
1546
0
  curlx_dyn_reset(&ctx->scratch);
1547
0
  result = curlx_dyn_addn(&ctx->scratch, (const char *)name, namelen);
1548
0
  if(!result)
1549
0
    result = curlx_dyn_addn(&ctx->scratch, STRCONST(": "));
1550
0
  if(!result)
1551
0
    result = curlx_dyn_addn(&ctx->scratch, (const char *)value, valuelen);
1552
0
  if(!result)
1553
0
    result = curlx_dyn_addn(&ctx->scratch, STRCONST("\r\n"));
1554
0
  if(!result)
1555
0
    h2_xfer_write_resp_hd(cf, data, stream, curlx_dyn_ptr(&ctx->scratch),
1556
0
                          curlx_dyn_len(&ctx->scratch), FALSE);
1557
0
  if(result) {
1558
0
    cf_h2_header_error(cf, data, stream, result);
1559
0
    return NGHTTP2_ERR_CALLBACK_FAILURE;
1560
0
  }
1561
  /* if we receive data for another handle, wake that up */
1562
0
  if(CF_DATA_CURRENT(cf) != data)
1563
0
    Curl_multi_mark_dirty(data);
1564
1565
0
  CURL_TRC_CF(data, cf, "[%d] header: %.*s: %.*s",
1566
0
              stream->id, (int)namelen, name, (int)valuelen, value);
1567
1568
0
  return 0; /* 0 is successful */
1569
0
}
1570
1571
static ssize_t req_body_read_callback(nghttp2_session *session,
1572
                                      int32_t stream_id,
1573
                                      uint8_t *buf, size_t length,
1574
                                      uint32_t *data_flags,
1575
                                      nghttp2_data_source *source,
1576
                                      void *userp)
1577
0
{
1578
0
  struct Curl_cfilter *cf = userp;
1579
0
  struct cf_h2_ctx *ctx = cf->ctx;
1580
0
  struct Curl_easy *data_s;
1581
0
  struct h2_stream_ctx *stream = NULL;
1582
0
  CURLcode result;
1583
0
  ssize_t nread;
1584
0
  size_t n;
1585
0
  (void)source;
1586
1587
0
  (void)cf;
1588
0
  if(!stream_id)
1589
0
    return NGHTTP2_ERR_INVALID_ARGUMENT;
1590
1591
  /* get the stream from the hash based on Stream ID, stream ID zero is for
1592
     connection-oriented stuff */
1593
0
  data_s = nghttp2_session_get_stream_user_data(session, stream_id);
1594
0
  if(!data_s)
1595
    /* Receiving a Stream ID not in the hash should not happen, this is an
1596
       internal error more than anything else! */
1597
0
    return NGHTTP2_ERR_CALLBACK_FAILURE;
1598
1599
0
  stream = H2_STREAM_CTX(ctx, data_s);
1600
0
  if(!stream)
1601
0
    return NGHTTP2_ERR_CALLBACK_FAILURE;
1602
1603
0
  result = Curl_bufq_read(&stream->sendbuf, buf, length, &n);
1604
0
  if(result) {
1605
0
    if(result != CURLE_AGAIN)
1606
0
      return NGHTTP2_ERR_CALLBACK_FAILURE;
1607
0
    nread = 0;
1608
0
  }
1609
0
  else
1610
0
    nread = (ssize_t)n;
1611
1612
0
  CURL_TRC_CF(data_s, cf, "[%d] req_body_read(len=%zu) eos=%d -> %zd, %d",
1613
0
              stream_id, length, stream->body_eos, nread, (int)result);
1614
1615
0
  if(stream->body_eos && Curl_bufq_is_empty(&stream->sendbuf)) {
1616
0
    *data_flags = NGHTTP2_DATA_FLAG_EOF;
1617
0
    return nread;
1618
0
  }
1619
0
  return (nread == 0) ? NGHTTP2_ERR_DEFERRED : nread;
1620
0
}
1621
1622
#ifdef CURLVERBOSE
1623
static int error_callback(nghttp2_session *session,
1624
                          const char *msg,
1625
                          size_t len,
1626
                          void *userp)
1627
0
{
1628
0
  struct Curl_cfilter *cf = userp;
1629
0
  struct Curl_easy *data = CF_DATA_CURRENT(cf);
1630
0
  (void)session;
1631
0
  failf(data, "%.*s", (int)len, msg);
1632
0
  return 0;
1633
0
}
1634
#endif
1635
1636
/*
1637
 * Append headers to ask for an HTTP1.1 to HTTP2 upgrade.
1638
 */
1639
CURLcode Curl_http2_request_upgrade(struct dynbuf *req,
1640
                                    struct Curl_easy *data)
1641
0
{
1642
0
  CURLcode result;
1643
0
  char *base64;
1644
0
  size_t blen;
1645
0
  struct SingleRequest *k = &data->req;
1646
0
  uint8_t binsettings[H2_BINSETTINGS_LEN];
1647
0
  ssize_t rc;
1648
0
  size_t binlen; /* length of the binsettings data */
1649
1650
0
  rc = populate_binsettings(binsettings, data);
1651
0
  if(!curlx_sztouz(rc, &binlen) || !binlen) {
1652
0
    failf(data, "nghttp2 unexpectedly failed on pack_settings_payload");
1653
0
    curlx_dyn_free(req);
1654
0
    return CURLE_FAILED_INIT;
1655
0
  }
1656
1657
0
  result = curlx_base64url_encode(binsettings, binlen, &base64, &blen);
1658
0
  if(result) {
1659
0
    curlx_dyn_free(req);
1660
0
    return result;
1661
0
  }
1662
1663
0
  data->state.http_hd_upgrade = TRUE;
1664
0
  data->state.http_hd_h2_settings = TRUE;
1665
0
  result = curlx_dyn_addf(req,
1666
0
                          "Upgrade: %s\r\n"
1667
0
                          "HTTP2-Settings: %s\r\n",
1668
0
                          NGHTTP2_CLEARTEXT_PROTO_VERSION_ID, base64);
1669
0
  curlx_free(base64);
1670
1671
0
  k->upgr101 = UPGR101_H2;
1672
0
  data->conn->bits.upgrade_in_progress = TRUE;
1673
1674
0
  return result;
1675
0
}
1676
1677
static CURLcode http2_handle_stream_close(struct Curl_cfilter *cf,
1678
                                          struct Curl_easy *data,
1679
                                          struct h2_stream_ctx *stream,
1680
                                          size_t *pnlen)
1681
0
{
1682
0
  CURLcode result;
1683
1684
0
  *pnlen = 0;
1685
0
  if(stream->reset) {
1686
0
    if(stream->error == NGHTTP2_REFUSED_STREAM) {
1687
0
      infof(data, "HTTP/2 stream %d refused by server, try again on a new "
1688
0
                  "connection", stream->id);
1689
0
      connclose(cf->conn, "REFUSED_STREAM"); /* do not use this anymore */
1690
0
      data->state.refused_stream = TRUE;
1691
0
      return CURLE_RECV_ERROR; /* trigger Curl_retry_request() later */
1692
0
    }
1693
0
    else if(stream->resp_hds_complete && data->req.no_body) {
1694
0
      CURL_TRC_CF(data, cf, "[%d] error after response headers, but we did "
1695
0
                  "not want a body anyway, ignore: %s (err %u)",
1696
0
                  stream->id, nghttp2_http2_strerror(stream->error),
1697
0
                  stream->error);
1698
0
      stream->close_handled = TRUE;
1699
0
      return CURLE_OK;
1700
0
    }
1701
0
    failf(data, "HTTP/2 stream %d reset by %s (error 0x%x %s)",
1702
0
          stream->id, stream->reset_by_server ? "server" : "curl",
1703
0
          stream->error, nghttp2_http2_strerror(stream->error));
1704
0
    return stream->error ? CURLE_HTTP2_STREAM :
1705
0
           (data->req.bytecount ? CURLE_PARTIAL_FILE : CURLE_HTTP2);
1706
0
  }
1707
0
  else if(!stream->bodystarted) {
1708
0
    failf(data, "HTTP/2 stream %d was closed cleanly, but before getting "
1709
0
          "all response header fields, treated as error", stream->id);
1710
0
    return CURLE_HTTP2_STREAM;
1711
0
  }
1712
1713
0
  if(Curl_dynhds_count(&stream->resp_trailers)) {
1714
0
    struct dynhds_entry *e;
1715
0
    struct dynbuf dbuf;
1716
0
    size_t i;
1717
1718
0
    result = CURLE_OK;
1719
0
    curlx_dyn_init(&dbuf, DYN_TRAILERS);
1720
0
    for(i = 0; i < Curl_dynhds_count(&stream->resp_trailers); ++i) {
1721
0
      e = Curl_dynhds_getn(&stream->resp_trailers, i);
1722
0
      if(!e)
1723
0
        break;
1724
0
      curlx_dyn_reset(&dbuf);
1725
0
      result = curlx_dyn_addf(&dbuf, "%.*s: %.*s\x0d\x0a",
1726
0
                              (int)e->namelen, e->name,
1727
0
                              (int)e->valuelen, e->value);
1728
0
      if(result)
1729
0
        break;
1730
0
      Curl_debug(data, CURLINFO_HEADER_IN, curlx_dyn_ptr(&dbuf),
1731
0
                 curlx_dyn_len(&dbuf));
1732
0
      result = Curl_client_write(data,
1733
0
                                 CLIENTWRITE_HEADER | CLIENTWRITE_TRAILER,
1734
0
                                 curlx_dyn_ptr(&dbuf), curlx_dyn_len(&dbuf));
1735
0
      if(result)
1736
0
        break;
1737
0
    }
1738
0
    curlx_dyn_free(&dbuf);
1739
0
    if(result)
1740
0
      goto out;
1741
0
  }
1742
1743
0
  stream->close_handled = TRUE;
1744
0
  result = CURLE_OK;
1745
1746
0
out:
1747
0
  CURL_TRC_CF(data, cf, "handle_stream_close -> %d, %zu", (int)result, *pnlen);
1748
0
  return result;
1749
0
}
1750
1751
static int sweight_wanted(const struct Curl_easy *data)
1752
0
{
1753
  /* 0 weight is not set by user and we take the nghttp2 default one */
1754
0
  return data->set.priority.weight ?
1755
0
    data->set.priority.weight : NGHTTP2_DEFAULT_WEIGHT;
1756
0
}
1757
1758
static int sweight_in_effect(const struct Curl_easy *data)
1759
0
{
1760
  /* 0 weight is not set by user and we take the nghttp2 default one */
1761
0
  return data->state.priority.weight ?
1762
0
    data->state.priority.weight : NGHTTP2_DEFAULT_WEIGHT;
1763
0
}
1764
1765
/*
1766
 * h2_pri_spec() fills in the pri_spec struct, used by nghttp2 to send weight
1767
 * and dependency to the peer. It also stores the updated values in the state
1768
 * struct.
1769
 */
1770
1771
static void h2_pri_spec(struct Curl_easy *data,
1772
                        nghttp2_priority_spec *pri_spec)
1773
0
{
1774
0
  struct Curl_data_priority *prio = &data->set.priority;
1775
0
  nghttp2_priority_spec_init(pri_spec, 0,
1776
0
                             sweight_wanted(data), FALSE);
1777
0
  data->state.priority = *prio;
1778
0
}
1779
1780
/*
1781
 * Check if there is been an update in the priority /
1782
 * dependency settings and if so it submits a PRIORITY frame with the updated
1783
 * info.
1784
 * Flush any out data pending in the network buffer.
1785
 */
1786
static CURLcode h2_progress_egress(struct Curl_cfilter *cf,
1787
                                   struct Curl_easy *data)
1788
0
{
1789
0
  struct cf_h2_ctx *ctx = cf->ctx;
1790
0
  struct h2_stream_ctx *stream = H2_STREAM_CTX(ctx, data);
1791
0
  int rv = 0;
1792
1793
0
  if(stream && stream->id > 0 &&
1794
0
     (sweight_wanted(data) != sweight_in_effect(data))) {
1795
    /* send new weight and/or dependency */
1796
0
    nghttp2_priority_spec pri_spec;
1797
1798
0
    h2_pri_spec(data, &pri_spec);
1799
0
    CURL_TRC_CF(data, cf, "[%d] Queuing PRIORITY", stream->id);
1800
0
    DEBUGASSERT(stream->id != -1);
1801
0
    rv = nghttp2_submit_priority(ctx->h2, NGHTTP2_FLAG_NONE,
1802
0
                                 stream->id, &pri_spec);
1803
0
    if(rv)
1804
0
      goto out;
1805
0
  }
1806
1807
0
  ctx->nw_out_blocked = 0;
1808
0
  while(!rv && !ctx->nw_out_blocked && nghttp2_session_want_write(ctx->h2))
1809
0
    rv = nghttp2_session_send(ctx->h2);
1810
1811
0
out:
1812
0
  if(nghttp2_is_fatal(rv)) {
1813
0
    CURL_TRC_CF(data, cf, "nghttp2_session_send error (%s)%d",
1814
0
                nghttp2_strerror(rv), rv);
1815
0
    return CURLE_SEND_ERROR;
1816
0
  }
1817
  /* Defer flushing during the connect phase so that the SETTINGS and
1818
   * other initial frames are sent together with the first request.
1819
   * Unless we are 'connect_only' where the request will never come. */
1820
0
  if(!cf->connected && !cf->conn->bits.connect_only)
1821
0
    return CURLE_OK;
1822
0
  return nw_out_flush(cf, data);
1823
0
}
1824
1825
static CURLcode stream_recv(struct Curl_cfilter *cf, struct Curl_easy *data,
1826
                            struct h2_stream_ctx *stream,
1827
                            char *buf, size_t len, size_t *pnread)
1828
0
{
1829
0
  struct cf_h2_ctx *ctx = cf->ctx;
1830
0
  CURLcode result = CURLE_AGAIN;
1831
1832
0
  (void)buf;
1833
0
  (void)len;
1834
0
  *pnread = 0;
1835
1836
0
  if(!stream->xfer_result)
1837
0
    stream->xfer_result = cf_h2_update_local_win(cf, data, stream);
1838
1839
0
  if(stream->xfer_result) {
1840
0
    CURL_TRC_CF(data, cf, "[%d] xfer write failed", stream->id);
1841
0
    result = stream->xfer_result;
1842
0
  }
1843
0
  else if(stream->closed) {
1844
0
    CURL_TRC_CF(data, cf, "[%d] returning CLOSE", stream->id);
1845
0
    result = http2_handle_stream_close(cf, data, stream, pnread);
1846
0
  }
1847
0
  else if(stream->reset ||
1848
0
          (ctx->conn_closed && Curl_bufq_is_empty(&ctx->inbufq)) ||
1849
0
          (ctx->rcvd_goaway && ctx->remote_max_sid < stream->id)) {
1850
0
    CURL_TRC_CF(data, cf, "[%d] returning ERR", stream->id);
1851
0
    result = data->req.bytecount ? CURLE_PARTIAL_FILE : CURLE_HTTP2;
1852
0
  }
1853
1854
0
  if(result && (result != CURLE_AGAIN))
1855
0
    CURL_TRC_CF(data, cf, "[%d] stream_recv(len=%zu) -> %d, %zu",
1856
0
                stream->id, len, (int)result, *pnread);
1857
0
  return result;
1858
0
}
1859
1860
static CURLcode h2_progress_ingress(struct Curl_cfilter *cf,
1861
                                    struct Curl_easy *data,
1862
                                    size_t data_max_bytes)
1863
0
{
1864
0
  struct cf_h2_ctx *ctx = cf->ctx;
1865
0
  struct h2_stream_ctx *stream;
1866
0
  CURLcode result = CURLE_OK;
1867
0
  size_t nread;
1868
1869
0
  if(should_close_session(ctx)) {
1870
0
    CURL_TRC_CF(data, cf, "[0] ingress: session is closed");
1871
0
    return CURLE_HTTP2;
1872
0
  }
1873
1874
  /* Process network input buffer first */
1875
0
  if(!Curl_bufq_is_empty(&ctx->inbufq)) {
1876
0
    CURL_TRC_CF(data, cf, "Process %zu bytes in connection buffer",
1877
0
                Curl_bufq_len(&ctx->inbufq));
1878
0
    result = h2_process_pending_input(cf, data);
1879
0
    if(result)
1880
0
      return result;
1881
0
  }
1882
1883
0
  if(!data_max_bytes)
1884
0
    data_max_bytes = H2_CHUNK_SIZE;
1885
1886
  /* Receive data from the "lower" filters, e.g. network until
1887
   * it is time to stop due to connection close or us not processing
1888
   * all network input */
1889
0
  while(!ctx->conn_closed && Curl_bufq_is_empty(&ctx->inbufq)) {
1890
0
    stream = H2_STREAM_CTX(ctx, data);
1891
0
    if(stream && (stream->closed || !data_max_bytes)) {
1892
      /* We would like to abort here and stop processing, so that the transfer
1893
       * loop can handle the data/close here. This may leave data in
1894
       * underlying buffers that will not be consumed. */
1895
0
      if(!cf->next || !cf->next->cft->has_data_pending(cf->next, data))
1896
0
        Curl_multi_mark_dirty(data);
1897
0
      break;
1898
0
    }
1899
0
    else if(!stream) {
1900
0
      DEBUGASSERT(0);
1901
0
      break;
1902
0
    }
1903
1904
0
    result = Curl_cf_recv_bufq(cf->next, data, &ctx->inbufq, 0, &nread);
1905
0
    if(result) {
1906
0
      if(result != CURLE_AGAIN) {
1907
0
        failf(data, "Failed receiving HTTP2 data: %d(%s)", (int)result,
1908
0
              curl_easy_strerror(result));
1909
0
        return result;
1910
0
      }
1911
0
      break;
1912
0
    }
1913
0
    else if(nread == 0) {
1914
0
      CURL_TRC_CF(data, cf, "[0] ingress: connection closed");
1915
0
      ctx->conn_closed = TRUE;
1916
0
      break;
1917
0
    }
1918
0
    else {
1919
0
      CURL_TRC_CF(data, cf, "[0] ingress: read %zu bytes", nread);
1920
0
      data_max_bytes = (data_max_bytes > nread) ? (data_max_bytes - nread) : 0;
1921
0
    }
1922
1923
0
    result = h2_process_pending_input(cf, data);
1924
0
    if(result)
1925
0
      return result;
1926
0
    CURL_TRC_CF(data, cf, "[0] ingress: nw-in buffered %zu",
1927
0
                Curl_bufq_len(&ctx->inbufq));
1928
0
  }
1929
1930
0
  if(ctx->conn_closed && Curl_bufq_is_empty(&ctx->inbufq)) {
1931
0
    connclose(cf->conn, ctx->rcvd_goaway ? "server closed with GOAWAY" :
1932
0
              "server closed abruptly");
1933
0
  }
1934
1935
0
  CURL_TRC_CF(data, cf, "[0] ingress: done");
1936
0
  return CURLE_OK;
1937
0
}
1938
1939
static CURLcode cf_h2_recv(struct Curl_cfilter *cf, struct Curl_easy *data,
1940
                           char *buf, size_t len, size_t *pnread)
1941
0
{
1942
0
  struct cf_h2_ctx *ctx = cf->ctx;
1943
0
  struct h2_stream_ctx *stream;
1944
0
  CURLcode result, r2;
1945
0
  struct cf_call_data save;
1946
1947
0
  if(!data)
1948
0
    return CURLE_HTTP2;
1949
1950
0
  stream = H2_STREAM_CTX(ctx, data);
1951
1952
0
  *pnread = 0;
1953
0
  if(!stream) {
1954
    /* Abnormal call sequence: either this transfer has never opened a stream
1955
     * (unlikely) or the transfer has been done, cleaned up its resources, but
1956
     * a read() is called anyway. It is not clear what the calling sequence
1957
     * is for such a case. */
1958
0
    failf(data, "http/2 recv on a transfer never opened "
1959
0
          "or already cleared, mid=%u", data->mid);
1960
0
    return CURLE_HTTP2;
1961
0
  }
1962
1963
0
  CF_DATA_SAVE(save, cf, data);
1964
1965
0
  result = stream_recv(cf, data, stream, buf, len, pnread);
1966
0
  if(result && (result != CURLE_AGAIN))
1967
0
    goto out;
1968
1969
0
  if(result) {
1970
0
    result = h2_progress_ingress(cf, data, len);
1971
0
    if(result)
1972
0
      goto out;
1973
1974
0
    result = stream_recv(cf, data, stream, buf, len, pnread);
1975
0
  }
1976
1977
0
  if(*pnread > 0) {
1978
    /* Now that we transferred this to the upper layer, we report
1979
     * the actual amount of DATA consumed to the H2 session, so
1980
     * that it adjusts stream flow control */
1981
0
    nghttp2_session_consume(ctx->h2, stream->id, *pnread);
1982
0
    if(stream->closed) {
1983
0
      CURL_TRC_CF(data, cf, "[%d] DRAIN closed stream", stream->id);
1984
0
      Curl_multi_mark_dirty(data);
1985
0
    }
1986
0
  }
1987
1988
0
out:
1989
0
  r2 = h2_progress_egress(cf, data);
1990
0
  if(r2 == CURLE_AGAIN) {
1991
    /* pending data to send, need to be called again. Ideally, we
1992
     * monitor the socket for POLLOUT, but when not SENDING
1993
     * any more, we force processing of the transfer. */
1994
0
    if(!CURL_REQ_WANT_SEND(data))
1995
0
      Curl_multi_mark_dirty(data);
1996
0
  }
1997
0
  else if(r2) {
1998
0
    result = r2;
1999
0
  }
2000
0
  CURL_TRC_CF(data, cf, "[%d] cf_recv(len=%zu) -> %d, %zu, "
2001
0
              "window=%d/%d, connection %d/%d",
2002
0
              stream->id, len, (int)result, *pnread,
2003
0
              nghttp2_session_get_stream_effective_recv_data_length(
2004
0
                ctx->h2, stream->id),
2005
0
              nghttp2_session_get_stream_effective_local_window_size(
2006
0
                ctx->h2, stream->id),
2007
0
              nghttp2_session_get_local_window_size(ctx->h2),
2008
0
              HTTP2_HUGE_WINDOW_SIZE);
2009
2010
0
  CF_DATA_RESTORE(cf, save);
2011
0
  return result;
2012
0
}
2013
2014
static CURLcode cf_h2_body_send(struct Curl_cfilter *cf,
2015
                                struct Curl_easy *data,
2016
                                struct h2_stream_ctx *stream,
2017
                                const void *buf, size_t blen, bool eos,
2018
                                size_t *pnwritten)
2019
0
{
2020
0
  struct cf_h2_ctx *ctx = cf->ctx;
2021
0
  CURLcode result;
2022
2023
0
  *pnwritten = 0;
2024
0
  if(stream->closed) {
2025
0
    if(stream->resp_hds_complete) {
2026
      /* Server decided to close the stream after having sent us a final
2027
       * response. This is valid if it is not interested in the request
2028
       * body. This happens on 30x or 40x responses.
2029
       * We silently discard the data sent, since this is not a transport
2030
       * error situation. */
2031
0
      CURL_TRC_CF(data, cf, "[%d] discarding data"
2032
0
                  "on closed stream with response", stream->id);
2033
0
      if(eos)
2034
0
        stream->body_eos = TRUE;
2035
0
      *pnwritten = blen;
2036
0
      return CURLE_OK;
2037
0
    }
2038
    /* Server closed before we got a response, this is an error */
2039
0
    infof(data, "stream %d closed", stream->id);
2040
0
    return CURLE_SEND_ERROR;
2041
0
  }
2042
2043
0
  result = Curl_bufq_write(&stream->sendbuf, buf, blen, pnwritten);
2044
0
  if(result)
2045
0
    return result;
2046
2047
0
  if(eos && (blen == *pnwritten))
2048
0
    stream->body_eos = TRUE;
2049
2050
0
  if(eos || !Curl_bufq_is_empty(&stream->sendbuf)) {
2051
    /* resume the potentially suspended stream */
2052
0
    int rv = nghttp2_session_resume_data(ctx->h2, stream->id);
2053
0
    if(nghttp2_is_fatal(rv))
2054
0
      return CURLE_SEND_ERROR;
2055
0
  }
2056
2057
0
  return CURLE_OK;
2058
0
}
2059
2060
static CURLcode h2_submit(struct h2_stream_ctx **pstream,
2061
                          struct Curl_cfilter *cf, struct Curl_easy *data,
2062
                          const uint8_t *buf, size_t len,
2063
                          bool eos, size_t *pnwritten)
2064
0
{
2065
0
  struct cf_h2_ctx *ctx = cf->ctx;
2066
0
  struct h2_stream_ctx *stream = NULL;
2067
0
  struct dynhds h2_headers;
2068
0
  nghttp2_nv *nva = NULL;
2069
0
  const void *body = NULL;
2070
0
  size_t nheader, bodylen;
2071
0
  nghttp2_data_provider data_prd;
2072
0
  int32_t stream_id;
2073
0
  nghttp2_priority_spec pri_spec;
2074
0
  size_t nwritten;
2075
0
  CURLcode result = CURLE_OK;
2076
0
  uint32_t initial_win_size;
2077
2078
0
  *pnwritten = 0;
2079
0
  Curl_dynhds_init(&h2_headers, 0, DYN_HTTP_REQUEST);
2080
2081
0
  result = http2_data_setup(cf, data, &stream);
2082
0
  if(result)
2083
0
    goto out;
2084
2085
0
  result = Curl_h1_req_parse_read(&stream->h1, buf, len, NULL,
2086
0
                                  !data->state.http_ignorecustom ?
2087
0
                                  data->set.str[STRING_CUSTOMREQUEST] : NULL,
2088
0
                                  0, &nwritten);
2089
0
  if(result)
2090
0
    goto out;
2091
0
  *pnwritten = nwritten;
2092
0
  if(!stream->h1.done) {
2093
    /* need more data */
2094
0
    goto out;
2095
0
  }
2096
0
  DEBUGASSERT(stream->h1.req);
2097
2098
0
  result = Curl_http_req_to_h2(&h2_headers, stream->h1.req, data);
2099
0
  if(result)
2100
0
    goto out;
2101
  /* no longer needed */
2102
0
  Curl_h1_req_parse_free(&stream->h1);
2103
2104
0
  nva = Curl_dynhds_to_nva(&h2_headers, &nheader);
2105
0
  if(!nva) {
2106
0
    result = CURLE_OUT_OF_MEMORY;
2107
0
    goto out;
2108
0
  }
2109
2110
0
  h2_pri_spec(data, &pri_spec);
2111
0
  if(!nghttp2_session_check_request_allowed(ctx->h2))
2112
0
    CURL_TRC_CF(data, cf, "send request NOT allowed (via nghttp2)");
2113
2114
  /* Check the initial windows size of the transfer (rate-limits?) and
2115
   * send an updated settings on changes from previous value. */
2116
0
  initial_win_size = cf_h2_initial_win_size(data);
2117
0
  if(initial_win_size != ctx->initial_win_size) {
2118
0
    result = cf_h2_update_settings(ctx, initial_win_size);
2119
0
    if(result)
2120
0
      goto out;
2121
0
  }
2122
2123
0
  switch(data->state.httpreq) {
2124
0
  case HTTPREQ_POST:
2125
0
  case HTTPREQ_POST_FORM:
2126
0
  case HTTPREQ_POST_MIME:
2127
0
  case HTTPREQ_PUT:
2128
0
    data_prd.read_callback = req_body_read_callback;
2129
0
    data_prd.source.ptr = NULL;
2130
0
    stream_id = nghttp2_submit_request(ctx->h2, &pri_spec, nva, nheader,
2131
0
                                       &data_prd, data);
2132
0
    break;
2133
0
  default:
2134
0
    stream_id = nghttp2_submit_request(ctx->h2, &pri_spec, nva, nheader,
2135
0
                                       NULL, data);
2136
0
  }
2137
2138
0
  if(stream_id < 0) {
2139
0
    CURL_TRC_CF(data, cf, "send: nghttp2_submit_request error (%s)%d",
2140
0
                nghttp2_strerror(stream_id), stream_id);
2141
0
    result = CURLE_SEND_ERROR;
2142
0
    goto out;
2143
0
  }
2144
2145
0
#ifdef CURLVERBOSE
2146
0
#define MAX_ACC 60000  /* <64KB to account for some overhead */
2147
0
  if(Curl_trc_is_verbose(data)) {
2148
0
    size_t acc = 0, i;
2149
2150
0
    infof(data, "[HTTP/2] [%d] OPENED stream for %s",
2151
0
          stream_id, Curl_bufref_ptr(&data->state.url));
2152
0
    for(i = 0; i < nheader; ++i) {
2153
0
      acc += nva[i].namelen + nva[i].valuelen;
2154
2155
0
      infof(data, "[HTTP/2] [%d] [%.*s: %.*s]", stream_id,
2156
0
            (int)nva[i].namelen, nva[i].name,
2157
0
            (int)nva[i].valuelen, nva[i].value);
2158
0
    }
2159
2160
0
    if(acc > MAX_ACC) {
2161
0
      infof(data, "[HTTP/2] Warning: The cumulative length of all "
2162
0
            "headers exceeds %d bytes and that could cause the "
2163
0
            "stream to be rejected.", MAX_ACC);
2164
0
    }
2165
0
  }
2166
0
#endif
2167
2168
0
  stream->id = stream_id;
2169
2170
0
  body = (const char *)buf + *pnwritten;
2171
0
  bodylen = len - *pnwritten;
2172
2173
0
  if(bodylen || eos) {
2174
0
    size_t n;
2175
0
    result = cf_h2_body_send(cf, data, stream, body, bodylen, eos, &n);
2176
0
    if(!result)
2177
0
      *pnwritten += n;
2178
0
    else if(result == CURLE_AGAIN)
2179
0
      result = CURLE_OK;
2180
0
    else {
2181
0
      result = CURLE_SEND_ERROR;
2182
0
    }
2183
0
  }
2184
2185
0
out:
2186
0
  CURL_TRC_CF(data, cf, "[%d] submit -> %d, %zu",
2187
0
              stream ? stream->id : -1, (int)result, *pnwritten);
2188
0
  curlx_safefree(nva);
2189
0
  *pstream = stream;
2190
0
  Curl_dynhds_free(&h2_headers);
2191
0
  return result;
2192
0
}
2193
2194
static CURLcode cf_h2_send(struct Curl_cfilter *cf, struct Curl_easy *data,
2195
                           const uint8_t *buf, size_t len, bool eos,
2196
                           size_t *pnwritten)
2197
0
{
2198
0
  struct cf_h2_ctx *ctx = cf->ctx;
2199
0
  struct h2_stream_ctx *stream = H2_STREAM_CTX(ctx, data);
2200
0
  struct cf_call_data save;
2201
0
  CURLcode result = CURLE_OK, r2;
2202
2203
0
  CF_DATA_SAVE(save, cf, data);
2204
0
  *pnwritten = 0;
2205
2206
0
  if(!stream || stream->id == -1) {
2207
0
    result = h2_submit(&stream, cf, data, buf, len, eos, pnwritten);
2208
0
    if(result)
2209
0
      goto out;
2210
0
    DEBUGASSERT(stream);
2211
0
  }
2212
0
  else if(stream->body_eos) {
2213
    /* We already wrote this, but CURLE_AGAIN-ed the call due to not
2214
     * being able to flush stream->sendbuf. Make a 0-length write
2215
     * to trigger flushing again.
2216
     * If this works, we report to have written `len` bytes. */
2217
0
    size_t n;
2218
0
    DEBUGASSERT(eos);
2219
0
    result = cf_h2_body_send(cf, data, stream, buf, 0, eos, &n);
2220
0
    CURL_TRC_CF(data, cf, "[%d] cf_body_send last CHUNK -> %d, %zu, eos=%d",
2221
0
                stream->id, (int)result, n, eos);
2222
0
    if(result)
2223
0
      goto out;
2224
0
    *pnwritten = len;
2225
0
  }
2226
0
  else {
2227
0
    result = cf_h2_body_send(cf, data, stream, buf, len, eos, pnwritten);
2228
0
    CURL_TRC_CF(data, cf, "[%d] cf_body_send(len=%zu) -> %d, %zu, eos=%d",
2229
0
                stream->id, len, (int)result, *pnwritten, eos);
2230
0
  }
2231
2232
  /* Call the nghttp2 send loop and flush to write ALL buffered data,
2233
   * headers and/or request body completely out to the network */
2234
0
  r2 = h2_progress_egress(cf, data);
2235
2236
  /* if the stream has been closed in egress handling (nghttp2 does that
2237
   * when it does not like the headers, for example */
2238
0
  if(stream && stream->closed) {
2239
0
    infof(data, "stream %d closed", stream->id);
2240
0
    result = CURLE_SEND_ERROR;
2241
0
    goto out;
2242
0
  }
2243
0
  else if(r2 && (r2 != CURLE_AGAIN)) {
2244
0
    result = r2;
2245
0
    goto out;
2246
0
  }
2247
2248
0
  if(should_close_session(ctx)) {
2249
    /* nghttp2 thinks this session is done. If the stream has not been
2250
     * closed, this is an error state for out transfer */
2251
0
    if(stream && stream->closed) {
2252
0
      result = http2_handle_stream_close(cf, data, stream, pnwritten);
2253
0
    }
2254
0
    else {
2255
0
      CURL_TRC_CF(data, cf, "send: nothing to do in this session");
2256
0
      result = CURLE_HTTP2;
2257
0
    }
2258
0
  }
2259
2260
0
out:
2261
0
  if(stream) {
2262
0
    CURL_TRC_CF(data, cf, "[%d] cf_send(len=%zu) -> %d, %zu, "
2263
0
                "eos=%d, h2 windows %d-%d (stream-conn), "
2264
0
                "buffers %zu-%zu (stream-conn)",
2265
0
                stream->id, len, (int)result, *pnwritten,
2266
0
                stream->body_eos,
2267
0
                nghttp2_session_get_stream_remote_window_size(
2268
0
                  ctx->h2, stream->id),
2269
0
                nghttp2_session_get_remote_window_size(ctx->h2),
2270
0
                Curl_bufq_len(&stream->sendbuf),
2271
0
                Curl_bufq_len(&ctx->outbufq));
2272
0
  }
2273
0
  else {
2274
0
    CURL_TRC_CF(data, cf, "cf_send(len=%zu) -> %d, %zu, "
2275
0
                "connection-window=%d, nw_send_buffer(%zu)",
2276
0
                len, (int)result, *pnwritten,
2277
0
                nghttp2_session_get_remote_window_size(ctx->h2),
2278
0
                Curl_bufq_len(&ctx->outbufq));
2279
0
  }
2280
0
  CF_DATA_RESTORE(cf, save);
2281
0
  return result;
2282
0
}
2283
2284
static CURLcode cf_h2_flush(struct Curl_cfilter *cf,
2285
                            struct Curl_easy *data)
2286
0
{
2287
0
  struct cf_h2_ctx *ctx = cf->ctx;
2288
0
  struct h2_stream_ctx *stream = H2_STREAM_CTX(ctx, data);
2289
0
  struct cf_call_data save;
2290
0
  CURLcode result = CURLE_OK;
2291
2292
0
  CF_DATA_SAVE(save, cf, data);
2293
0
  if(stream && !Curl_bufq_is_empty(&stream->sendbuf)) {
2294
    /* resume the potentially suspended stream */
2295
0
    int rv = nghttp2_session_resume_data(ctx->h2, stream->id);
2296
0
    if(nghttp2_is_fatal(rv)) {
2297
0
      result = CURLE_SEND_ERROR;
2298
0
      goto out;
2299
0
    }
2300
0
  }
2301
2302
0
  result = h2_progress_egress(cf, data);
2303
2304
0
out:
2305
0
  if(stream) {
2306
0
    CURL_TRC_CF(data, cf, "[%d] flush -> %d, "
2307
0
                "h2 windows %d-%d (stream-conn), "
2308
0
                "buffers %zu-%zu (stream-conn)",
2309
0
                stream->id, (int)result,
2310
0
                nghttp2_session_get_stream_remote_window_size(
2311
0
                  ctx->h2, stream->id),
2312
0
                nghttp2_session_get_remote_window_size(ctx->h2),
2313
0
                Curl_bufq_len(&stream->sendbuf),
2314
0
                Curl_bufq_len(&ctx->outbufq));
2315
0
  }
2316
0
  else {
2317
0
    CURL_TRC_CF(data, cf, "flush -> %d, "
2318
0
                "connection-window=%d, nw_send_buffer(%zu)",
2319
0
                (int)result, nghttp2_session_get_remote_window_size(ctx->h2),
2320
0
                Curl_bufq_len(&ctx->outbufq));
2321
0
  }
2322
0
  CF_DATA_RESTORE(cf, save);
2323
0
  return result;
2324
0
}
2325
2326
static CURLcode cf_h2_adjust_pollset(struct Curl_cfilter *cf,
2327
                                     struct Curl_easy *data,
2328
                                     struct easy_pollset *ps)
2329
0
{
2330
0
  struct cf_h2_ctx *ctx = cf->ctx;
2331
0
  struct cf_call_data save;
2332
0
  curl_socket_t sock;
2333
0
  bool want_recv, want_send;
2334
0
  CURLcode result = CURLE_OK;
2335
2336
0
  if(!ctx->h2)
2337
0
    return CURLE_OK;
2338
2339
0
  sock = Curl_conn_cf_get_socket(cf, data);
2340
0
  Curl_pollset_check(data, ps, sock, &want_recv, &want_send);
2341
0
  if(want_recv || want_send) {
2342
0
    struct h2_stream_ctx *stream = H2_STREAM_CTX(ctx, data);
2343
0
    bool c_exhaust, s_exhaust;
2344
2345
0
    CF_DATA_SAVE(save, cf, data);
2346
0
    c_exhaust = want_send && !nghttp2_session_get_remote_window_size(ctx->h2);
2347
0
    s_exhaust = want_send && stream && stream->id >= 0 &&
2348
0
                !nghttp2_session_get_stream_remote_window_size(ctx->h2,
2349
0
                                                               stream->id);
2350
0
    want_recv = (want_recv || c_exhaust || s_exhaust);
2351
0
    want_send = (!s_exhaust && want_send) ||
2352
0
                (!c_exhaust && nghttp2_session_want_write(ctx->h2)) ||
2353
0
                !Curl_bufq_is_empty(&ctx->outbufq);
2354
2355
0
    result = Curl_pollset_set(data, ps, sock, want_recv, want_send);
2356
0
    CF_DATA_RESTORE(cf, save);
2357
0
  }
2358
0
  else if(ctx->sent_goaway && !cf->shutdown) {
2359
    /* shutdown in progress */
2360
0
    CF_DATA_SAVE(save, cf, data);
2361
0
    want_send = nghttp2_session_want_write(ctx->h2) ||
2362
0
                !Curl_bufq_is_empty(&ctx->outbufq);
2363
0
    want_recv = nghttp2_session_want_read(ctx->h2);
2364
0
    result = Curl_pollset_set(data, ps, sock, want_recv, want_send);
2365
0
    CF_DATA_RESTORE(cf, save);
2366
0
  }
2367
0
  return result;
2368
0
}
2369
2370
static CURLcode cf_h2_ctx_open(struct Curl_cfilter *cf,
2371
                               struct Curl_easy *data)
2372
0
{
2373
0
  struct cf_h2_ctx *ctx = cf->ctx;
2374
0
  struct h2_stream_ctx *stream;
2375
0
  CURLcode result = CURLE_OUT_OF_MEMORY;
2376
0
  int rc;
2377
0
  nghttp2_session_callbacks *cbs = NULL;
2378
2379
0
  DEBUGASSERT(!ctx->h2);
2380
0
  DEBUGASSERT(ctx->initialized);
2381
2382
0
  rc = nghttp2_session_callbacks_new(&cbs);
2383
0
  if(rc) {
2384
0
    failf(data, "Could not initialize nghttp2 callbacks");
2385
0
    goto out;
2386
0
  }
2387
2388
0
  nghttp2_session_callbacks_set_send_callback(cbs, send_callback);
2389
0
  nghttp2_session_callbacks_set_on_frame_recv_callback(cbs, on_frame_recv);
2390
0
  nghttp2_session_callbacks_set_on_invalid_frame_recv_callback(cbs,
2391
0
    cf_h2_on_invalid_frame_recv);
2392
0
#ifdef CURLVERBOSE
2393
0
  nghttp2_session_callbacks_set_on_frame_send_callback(cbs, on_frame_send);
2394
0
#endif
2395
0
  nghttp2_session_callbacks_set_on_data_chunk_recv_callback(
2396
0
    cbs, on_data_chunk_recv);
2397
0
  nghttp2_session_callbacks_set_on_stream_close_callback(cbs, on_stream_close);
2398
0
  nghttp2_session_callbacks_set_on_begin_headers_callback(
2399
0
    cbs, on_begin_headers);
2400
0
  nghttp2_session_callbacks_set_on_header_callback(cbs, on_header);
2401
0
#ifdef CURLVERBOSE
2402
0
  nghttp2_session_callbacks_set_error_callback(cbs, error_callback);
2403
0
#endif
2404
2405
  /* The nghttp2 session is not yet setup, do it */
2406
0
  rc = h2_client_new(cf, cbs);
2407
0
  if(rc) {
2408
0
    failf(data, "Could not initialize nghttp2");
2409
0
    goto out;
2410
0
  }
2411
0
  ctx->max_concurrent_streams = DEFAULT_MAX_CONCURRENT_STREAMS;
2412
2413
0
  if(ctx->via_h1_upgrade) {
2414
    /* HTTP/1.1 Upgrade issued. H2 Settings have already been submitted
2415
     * in the H1 request and we upgrade from there. This stream
2416
     * is opened implicitly as #1. */
2417
0
    uint8_t binsettings[H2_BINSETTINGS_LEN];
2418
0
    ssize_t rclen;
2419
0
    size_t binlen; /* length of the binsettings data */
2420
2421
0
    rclen = populate_binsettings(binsettings, data);
2422
2423
0
    if(!curlx_sztouz(rclen, &binlen) || !binlen) {
2424
0
      failf(data, "nghttp2 unexpectedly failed on pack_settings_payload");
2425
0
      result = CURLE_FAILED_INIT;
2426
0
      goto out;
2427
0
    }
2428
2429
0
    result = http2_data_setup(cf, data, &stream);
2430
0
    if(result)
2431
0
      goto out;
2432
0
    DEBUGASSERT(stream);
2433
0
    stream->id = 1;
2434
    /* queue SETTINGS frame (again) */
2435
0
    rc = nghttp2_session_upgrade2(ctx->h2, binsettings, binlen,
2436
0
                                  data->state.httpreq == HTTPREQ_HEAD,
2437
0
                                  NULL);
2438
0
    if(rc) {
2439
0
      failf(data, "nghttp2_session_upgrade2() failed: %s(%d)",
2440
0
            nghttp2_strerror(rc), rc);
2441
0
      result = CURLE_HTTP2;
2442
0
      goto out;
2443
0
    }
2444
2445
0
    rc = nghttp2_session_set_stream_user_data(ctx->h2, stream->id,
2446
0
                                              data);
2447
0
    if(rc) {
2448
0
      infof(data, "http/2: failed to set user_data for stream %d",
2449
0
            stream->id);
2450
0
      DEBUGASSERT(0);
2451
0
    }
2452
0
    CURL_TRC_CF(data, cf, "created session via Upgrade");
2453
0
  }
2454
0
  else {
2455
0
    nghttp2_settings_entry iv[H2_SETTINGS_IV_LEN];
2456
0
    size_t ivlen;
2457
2458
0
    ivlen = populate_settings(iv, data, ctx);
2459
0
    rc = nghttp2_submit_settings(ctx->h2, NGHTTP2_FLAG_NONE,
2460
0
                                 iv, ivlen);
2461
0
    if(rc) {
2462
0
      failf(data, "nghttp2_submit_settings() failed: %s(%d)",
2463
0
            nghttp2_strerror(rc), rc);
2464
0
      result = CURLE_HTTP2;
2465
0
      goto out;
2466
0
    }
2467
0
  }
2468
2469
0
  rc = nghttp2_session_set_local_window_size(ctx->h2, NGHTTP2_FLAG_NONE, 0,
2470
0
                                             HTTP2_HUGE_WINDOW_SIZE);
2471
0
  if(rc) {
2472
0
    failf(data, "nghttp2_session_set_local_window_size() failed: %s(%d)",
2473
0
          nghttp2_strerror(rc), rc);
2474
0
    result = CURLE_HTTP2;
2475
0
    goto out;
2476
0
  }
2477
2478
  /* all set, traffic will be send on connect */
2479
0
  result = CURLE_OK;
2480
0
  CURL_TRC_CF(data, cf, "[0] created h2 session%s",
2481
0
              ctx->via_h1_upgrade ? " (via h1 upgrade)" : "");
2482
2483
0
out:
2484
0
  if(cbs)
2485
0
    nghttp2_session_callbacks_del(cbs);
2486
0
  return result;
2487
0
}
2488
2489
static CURLcode cf_h2_connect(struct Curl_cfilter *cf,
2490
                              struct Curl_easy *data,
2491
                              bool *done)
2492
0
{
2493
0
  struct cf_h2_ctx *ctx = cf->ctx;
2494
0
  CURLcode result = CURLE_OK;
2495
0
  struct cf_call_data save;
2496
0
  bool first_time = FALSE;
2497
2498
0
  if(cf->connected) {
2499
0
    *done = TRUE;
2500
0
    return CURLE_OK;
2501
0
  }
2502
2503
  /* Connect the lower filters first */
2504
0
  if(!cf->next->connected) {
2505
0
    result = Curl_conn_cf_connect(cf->next, data, done);
2506
0
    if(result || !*done)
2507
0
      return result;
2508
0
  }
2509
2510
0
  *done = FALSE;
2511
2512
0
  CF_DATA_SAVE(save, cf, data);
2513
0
  DEBUGASSERT(ctx->initialized);
2514
0
  if(!ctx->h2) {
2515
0
    result = cf_h2_ctx_open(cf, data);
2516
0
    if(result)
2517
0
      goto out;
2518
0
    first_time = TRUE;
2519
0
  }
2520
2521
0
  if(!first_time) {
2522
0
    result = h2_progress_ingress(cf, data, 0);
2523
0
    if(result)
2524
0
      goto out;
2525
0
  }
2526
2527
  /* Send out our SETTINGS and ACKs and such. If that blocks, we
2528
   * have it buffered and can count this filter as being connected */
2529
0
  result = h2_progress_egress(cf, data);
2530
0
  if(result && (result != CURLE_AGAIN))
2531
0
    goto out;
2532
2533
0
  *done = TRUE;
2534
0
  cf->connected = TRUE;
2535
0
  result = CURLE_OK;
2536
2537
0
out:
2538
0
  CURL_TRC_CF(data, cf, "cf_connect() -> %d, %d, ", (int)result, *done);
2539
0
  CF_DATA_RESTORE(cf, save);
2540
0
  return result;
2541
0
}
2542
2543
static void cf_h2_destroy(struct Curl_cfilter *cf, struct Curl_easy *data)
2544
0
{
2545
0
  struct cf_h2_ctx *ctx = cf->ctx;
2546
2547
0
  (void)data;
2548
0
  if(ctx) {
2549
0
    cf_h2_ctx_free(ctx);
2550
0
    cf->ctx = NULL;
2551
0
  }
2552
0
}
2553
2554
static CURLcode cf_h2_shutdown(struct Curl_cfilter *cf,
2555
                               struct Curl_easy *data, bool *done)
2556
0
{
2557
0
  struct cf_h2_ctx *ctx = cf->ctx;
2558
0
  struct cf_call_data save;
2559
0
  CURLcode result;
2560
0
  int rv;
2561
2562
0
  if(!cf->connected || !ctx->h2 || cf->shutdown || ctx->conn_closed) {
2563
0
    *done = TRUE;
2564
0
    return CURLE_OK;
2565
0
  }
2566
2567
0
  CF_DATA_SAVE(save, cf, data);
2568
2569
0
  if(!ctx->sent_goaway) {
2570
0
    ctx->sent_goaway = TRUE;
2571
0
    rv = nghttp2_submit_goaway(ctx->h2, NGHTTP2_FLAG_NONE,
2572
0
                               ctx->local_max_sid, 0,
2573
0
                               (const uint8_t *)"shutdown",
2574
0
                               sizeof("shutdown"));
2575
0
    if(rv) {
2576
0
      failf(data, "nghttp2_submit_goaway() failed: %s(%d)",
2577
0
            nghttp2_strerror(rv), rv);
2578
0
      result = CURLE_SEND_ERROR;
2579
0
      goto out;
2580
0
    }
2581
0
  }
2582
  /* GOAWAY submitted, process egress and ingress until nghttp2 is done. */
2583
0
  result = CURLE_OK;
2584
0
  if(nghttp2_session_want_write(ctx->h2) ||
2585
0
     !Curl_bufq_is_empty(&ctx->outbufq))
2586
0
    result = h2_progress_egress(cf, data);
2587
0
  if(!result && nghttp2_session_want_read(ctx->h2))
2588
0
    result = h2_progress_ingress(cf, data, 0);
2589
2590
0
  if(result == CURLE_AGAIN)
2591
0
    result = CURLE_OK;
2592
2593
0
  *done = (ctx->conn_closed ||
2594
0
           (!result && !nghttp2_session_want_write(ctx->h2) &&
2595
0
            !nghttp2_session_want_read(ctx->h2) &&
2596
0
            Curl_bufq_is_empty(&ctx->outbufq)));
2597
2598
0
out:
2599
0
  CF_DATA_RESTORE(cf, save);
2600
0
  cf->shutdown = (result || *done);
2601
0
  return result;
2602
0
}
2603
2604
static CURLcode http2_data_pause(struct Curl_cfilter *cf,
2605
                                 struct Curl_easy *data,
2606
                                 bool pause)
2607
0
{
2608
0
  struct cf_h2_ctx *ctx = cf->ctx;
2609
0
  struct h2_stream_ctx *stream = H2_STREAM_CTX(ctx, data);
2610
2611
0
  DEBUGASSERT(data);
2612
0
  if(ctx && ctx->h2 && stream) {
2613
0
    CURLcode result;
2614
2615
0
    stream->write_paused = pause;
2616
0
    result = cf_h2_update_local_win(cf, data, stream);
2617
0
    if(result)
2618
0
      return result;
2619
2620
    /* attempt to send the window update */
2621
0
    (void)h2_progress_egress(cf, data);
2622
2623
0
    if(!pause) {
2624
      /* Unpausing a h2 transfer, requires it to be run again. The server
2625
       * may send new DATA on us increasing the flow window, and it may
2626
       * not. We may have already buffered and exhausted the new window
2627
       * by operating on things in flight during the handling of other
2628
       * transfers. */
2629
0
      Curl_multi_mark_dirty(data);
2630
0
    }
2631
0
    CURL_TRC_CF(data, cf, "[%d] stream now %spaused", stream->id,
2632
0
                pause ? "" : "un");
2633
0
  }
2634
0
  return CURLE_OK;
2635
0
}
2636
2637
static CURLcode cf_h2_cntrl(struct Curl_cfilter *cf,
2638
                            struct Curl_easy *data,
2639
                            int event, int arg1, void *arg2)
2640
0
{
2641
0
  CURLcode result = CURLE_OK;
2642
0
  struct cf_call_data save;
2643
2644
0
  (void)arg2;
2645
2646
0
  CF_DATA_SAVE(save, cf, data);
2647
0
  switch(event) {
2648
0
  case CF_CTRL_DATA_SETUP:
2649
0
    break;
2650
0
  case CF_CTRL_DATA_PAUSE:
2651
0
    result = http2_data_pause(cf, data, (arg1 != 0));
2652
0
    break;
2653
0
  case CF_CTRL_FLUSH:
2654
0
    result = cf_h2_flush(cf, data);
2655
0
    break;
2656
0
  case CF_CTRL_DATA_DONE:
2657
0
    http2_data_done(cf, data);
2658
0
    break;
2659
0
  case CF_CTRL_CONN_INFO_UPDATE:
2660
0
    if(!cf->sockindex && cf->connected) {
2661
0
      cf->conn->httpversion_seen = 20;
2662
0
      Curl_conn_set_multiplex(cf->conn);
2663
0
    }
2664
0
    break;
2665
0
  default:
2666
0
    break;
2667
0
  }
2668
0
  CF_DATA_RESTORE(cf, save);
2669
0
  return result;
2670
0
}
2671
2672
static bool cf_h2_data_pending(struct Curl_cfilter *cf,
2673
                               const struct Curl_easy *data)
2674
0
{
2675
0
  struct cf_h2_ctx *ctx = cf->ctx;
2676
2677
0
  if(ctx && !Curl_bufq_is_empty(&ctx->inbufq))
2678
0
    return TRUE;
2679
0
  return cf->next ? cf->next->cft->has_data_pending(cf->next, data) : FALSE;
2680
0
}
2681
2682
static bool cf_h2_is_alive(struct Curl_cfilter *cf,
2683
                           struct Curl_easy *data,
2684
                           bool *input_pending)
2685
0
{
2686
0
  struct cf_h2_ctx *ctx = cf->ctx;
2687
0
  bool alive;
2688
0
  struct cf_call_data save;
2689
2690
0
  *input_pending = FALSE;
2691
0
  CF_DATA_SAVE(save, cf, data);
2692
0
  alive = (ctx && ctx->h2 && http2_connisalive(cf, data, input_pending));
2693
0
  CURL_TRC_CF(data, cf, "conn alive -> %d, input_pending=%d",
2694
0
              alive, *input_pending);
2695
0
  CF_DATA_RESTORE(cf, save);
2696
0
  return alive;
2697
0
}
2698
2699
static CURLcode cf_h2_keep_alive(struct Curl_cfilter *cf,
2700
                                 struct Curl_easy *data)
2701
0
{
2702
0
  CURLcode result;
2703
0
  struct cf_call_data save;
2704
2705
0
  CF_DATA_SAVE(save, cf, data);
2706
0
  result = http2_send_ping(cf, data);
2707
0
  CF_DATA_RESTORE(cf, save);
2708
0
  return result;
2709
0
}
2710
2711
static CURLcode cf_h2_query(struct Curl_cfilter *cf,
2712
                            struct Curl_easy *data,
2713
                            int query, int *pres1, void *pres2)
2714
0
{
2715
0
  struct cf_h2_ctx *ctx = cf->ctx;
2716
0
  struct cf_call_data save;
2717
0
  size_t effective_max;
2718
2719
0
  switch(query) {
2720
0
  case CF_QUERY_MAX_CONCURRENT:
2721
0
    DEBUGASSERT(pres1);
2722
2723
0
    CF_DATA_SAVE(save, cf, data);
2724
0
    if(!ctx->h2 || !nghttp2_session_check_request_allowed(ctx->h2)) {
2725
      /* the limit is what we have in use right now */
2726
0
      effective_max = cf->conn->attached_xfers;
2727
0
    }
2728
0
    else {
2729
0
      effective_max = ctx->max_concurrent_streams;
2730
0
    }
2731
0
    *pres1 = (effective_max > INT_MAX) ? INT_MAX : (int)effective_max;
2732
0
    CF_DATA_RESTORE(cf, save);
2733
0
    return CURLE_OK;
2734
0
  case CF_QUERY_STREAM_ERROR: {
2735
0
    struct h2_stream_ctx *stream = H2_STREAM_CTX(ctx, data);
2736
0
    *pres1 = stream ? (int)stream->error : 0;
2737
0
    return CURLE_OK;
2738
0
  }
2739
0
  case CF_QUERY_NEED_FLUSH: {
2740
0
    struct h2_stream_ctx *stream = H2_STREAM_CTX(ctx, data);
2741
0
    if(!Curl_bufq_is_empty(&ctx->outbufq) ||
2742
0
       (stream && !Curl_bufq_is_empty(&stream->sendbuf))) {
2743
0
      *pres1 = TRUE;
2744
0
      return CURLE_OK;
2745
0
    }
2746
0
    break;
2747
0
  }
2748
0
  case CF_QUERY_HTTP_VERSION:
2749
0
    *pres1 = 20;
2750
0
    return CURLE_OK;
2751
0
  default:
2752
0
    break;
2753
0
  }
2754
0
  return cf->next ?
2755
0
    cf->next->cft->query(cf->next, data, query, pres1, pres2) :
2756
0
    CURLE_UNKNOWN_OPTION;
2757
0
}
2758
2759
struct Curl_cftype Curl_cft_nghttp2 = {
2760
  "HTTP/2",
2761
  CF_TYPE_MULTIPLEX | CF_TYPE_HTTP,
2762
  CURL_LOG_LVL_NONE,
2763
  cf_h2_destroy,
2764
  cf_h2_connect,
2765
  cf_h2_shutdown,
2766
  cf_h2_adjust_pollset,
2767
  cf_h2_data_pending,
2768
  cf_h2_send,
2769
  cf_h2_recv,
2770
  cf_h2_cntrl,
2771
  cf_h2_is_alive,
2772
  cf_h2_keep_alive,
2773
  cf_h2_query,
2774
};
2775
2776
static CURLcode http2_cfilter_add(struct Curl_cfilter **pcf,
2777
                                  struct Curl_easy *data,
2778
                                  struct connectdata *conn,
2779
                                  int sockindex,
2780
                                  bool via_h1_upgrade)
2781
0
{
2782
0
  struct Curl_cfilter *cf = NULL;
2783
0
  struct cf_h2_ctx *ctx;
2784
0
  CURLcode result = CURLE_OUT_OF_MEMORY;
2785
2786
0
  DEBUGASSERT(data->conn);
2787
0
  ctx = curlx_calloc(1, sizeof(*ctx));
2788
0
  if(!ctx)
2789
0
    goto out;
2790
0
  cf_h2_ctx_init(ctx, via_h1_upgrade);
2791
2792
0
  result = Curl_cf_create(&cf, &Curl_cft_nghttp2, ctx);
2793
0
  if(result)
2794
0
    goto out;
2795
2796
0
  ctx = NULL;
2797
0
  Curl_conn_cf_add(data, conn, sockindex, cf);
2798
2799
0
out:
2800
0
  if(result)
2801
0
    cf_h2_ctx_free(ctx);
2802
0
  *pcf = result ? NULL : cf;
2803
0
  return result;
2804
0
}
2805
2806
static CURLcode http2_cfilter_insert_after(struct Curl_cfilter *cf,
2807
                                           struct Curl_easy *data,
2808
                                           bool via_h1_upgrade)
2809
0
{
2810
0
  struct Curl_cfilter *cf_h2 = NULL;
2811
0
  struct cf_h2_ctx *ctx;
2812
0
  CURLcode result = CURLE_OUT_OF_MEMORY;
2813
2814
0
  (void)data;
2815
0
  ctx = curlx_calloc(1, sizeof(*ctx));
2816
0
  if(!ctx)
2817
0
    goto out;
2818
0
  cf_h2_ctx_init(ctx, via_h1_upgrade);
2819
2820
0
  result = Curl_cf_create(&cf_h2, &Curl_cft_nghttp2, ctx);
2821
0
  if(result)
2822
0
    goto out;
2823
2824
0
  ctx = NULL;
2825
0
  Curl_conn_cf_insert_after(cf, cf_h2);
2826
2827
0
out:
2828
0
  if(result)
2829
0
    cf_h2_ctx_free(ctx);
2830
0
  return result;
2831
0
}
2832
2833
bool Curl_http2_may_switch(struct Curl_easy *data)
2834
0
{
2835
0
  if(Curl_conn_http_version(data, data->conn) < 20 &&
2836
0
     (data->state.http_neg.wanted & CURL_HTTP_V2x) &&
2837
0
     data->state.http_neg.h2_prior_knowledge) {
2838
0
#ifndef CURL_DISABLE_PROXY
2839
0
    if(data->conn->bits.origin_is_proxy) {
2840
0
      infof(data, "Ignoring HTTP/2 prior knowledge due to proxy");
2841
0
      return FALSE;
2842
0
    }
2843
0
#endif
2844
0
    return TRUE;
2845
0
  }
2846
0
  return FALSE;
2847
0
}
2848
2849
CURLcode Curl_http2_switch(struct Curl_easy *data)
2850
0
{
2851
0
  struct Curl_cfilter *cf;
2852
0
  CURLcode result;
2853
2854
0
  DEBUGASSERT(Curl_conn_http_version(data, data->conn) < 20);
2855
2856
0
  result = http2_cfilter_add(&cf, data, data->conn, FIRSTSOCKET, FALSE);
2857
0
  if(result)
2858
0
    return result;
2859
0
  CURL_TRC_CF(data, cf, "switching connection to HTTP/2");
2860
2861
0
  if(cf->next) {
2862
0
    bool done;
2863
0
    return Curl_conn_cf_connect(cf, data, &done);
2864
0
  }
2865
0
  return CURLE_OK;
2866
0
}
2867
2868
CURLcode Curl_http2_switch_at(struct Curl_cfilter *cf, struct Curl_easy *data)
2869
0
{
2870
0
  struct Curl_cfilter *cf_h2;
2871
0
  CURLcode result;
2872
2873
0
  DEBUGASSERT(Curl_conn_http_version(data, data->conn) < 20);
2874
2875
0
  result = http2_cfilter_insert_after(cf, data, FALSE);
2876
0
  if(result)
2877
0
    return result;
2878
2879
0
  cf_h2 = cf->next;
2880
2881
0
  if(cf_h2->next) {
2882
0
    bool done;
2883
0
    return Curl_conn_cf_connect(cf_h2, data, &done);
2884
0
  }
2885
0
  return CURLE_OK;
2886
0
}
2887
2888
CURLcode Curl_http2_upgrade(struct Curl_easy *data,
2889
                            struct connectdata *conn, int sockindex,
2890
                            const char *mem, size_t nread)
2891
0
{
2892
0
  struct Curl_cfilter *cf;
2893
0
  struct cf_h2_ctx *ctx;
2894
0
  CURLcode result;
2895
2896
0
  DEBUGASSERT(Curl_conn_http_version(data, conn) < 20);
2897
2898
0
  result = http2_cfilter_add(&cf, data, conn, sockindex, TRUE);
2899
0
  if(result)
2900
0
    return result;
2901
0
  CURL_TRC_CF(data, cf, "upgrading connection to HTTP/2");
2902
2903
0
  DEBUGASSERT(cf->cft == &Curl_cft_nghttp2);
2904
0
  ctx = cf->ctx;
2905
2906
0
  data->req.httpversion_sent = 20; /* it is an h2 request now */
2907
0
  data->req.header = TRUE; /* we expect the real response to come in h2 */
2908
0
  data->req.headerline = 0; /* restart the header line counter */
2909
2910
0
  if(nread > 0) {
2911
    /* Remaining data from the protocol switch reply is already using
2912
     * the switched protocol, ie. HTTP/2. We add that to the network
2913
     * inbufq. */
2914
0
    size_t copied;
2915
2916
0
    result = Curl_bufq_write(&ctx->inbufq,
2917
0
                             (const unsigned char *)mem, nread, &copied);
2918
0
    if(result) {
2919
0
      failf(data, "error on copying HTTP Upgrade response: %d", (int)result);
2920
0
      return CURLE_RECV_ERROR;
2921
0
    }
2922
0
    if(copied < nread) {
2923
0
      failf(data, "connection buffer size could not take all data "
2924
0
            "from HTTP Upgrade response header: copied=%zu, datalen=%zu",
2925
0
            copied, nread);
2926
0
      return CURLE_HTTP2;
2927
0
    }
2928
0
    infof(data, "Copied HTTP/2 data in stream buffer to connection buffer"
2929
0
          " after upgrade: len=%zu", nread);
2930
0
  }
2931
2932
0
  if(cf->next) {
2933
0
    bool done;
2934
0
    result = Curl_conn_cf_connect(cf, data, &done);
2935
0
    if(!result)
2936
0
      cf->cft->cntrl(cf, data, CF_CTRL_CONN_INFO_UPDATE, 0, NULL);
2937
0
  }
2938
0
  return result;
2939
0
}
2940
2941
/* Only call this function for a transfer that already got an HTTP/2
2942
   CURLE_HTTP2_STREAM error! */
2943
bool Curl_h2_http_1_1_error(struct Curl_easy *data)
2944
0
{
2945
0
  if(Curl_conn_http_version(data, data->conn) == 20) {
2946
0
    int err = Curl_conn_get_stream_error(data, data->conn, FIRSTSOCKET);
2947
0
    return err == NGHTTP2_HTTP_1_1_REQUIRED;
2948
0
  }
2949
0
  return FALSE;
2950
0
}
2951
2952
void *Curl_nghttp2_malloc(size_t size, void *user_data)
2953
0
{
2954
0
  (void)user_data;
2955
0
  return Curl_cmalloc(size);
2956
0
}
2957
2958
void Curl_nghttp2_free(void *ptr, void *user_data)
2959
0
{
2960
0
  (void)user_data;
2961
0
  Curl_cfree(ptr);
2962
0
}
2963
2964
void *Curl_nghttp2_calloc(size_t nmemb, size_t size, void *user_data)
2965
0
{
2966
0
  (void)user_data;
2967
0
  return Curl_ccalloc(nmemb, size);
2968
0
}
2969
2970
void *Curl_nghttp2_realloc(void *ptr, size_t size, void *user_data)
2971
0
{
2972
0
  (void)user_data;
2973
0
  return Curl_crealloc(ptr, size);
2974
0
}
2975
2976
#else /* CURL_DISABLE_HTTP || !USE_NGHTTP2 */
2977
2978
/* Satisfy external references even if http2 is not compiled in. */
2979
2980
char *curl_pushheader_bynum(struct curl_pushheaders *h, size_t num)
2981
{
2982
  (void)h;
2983
  (void)num;
2984
  return NULL;
2985
}
2986
2987
char *curl_pushheader_byname(struct curl_pushheaders *h, const char *name)
2988
{
2989
  (void)h;
2990
  (void)name;
2991
  return NULL;
2992
}
2993
2994
#endif /* !CURL_DISABLE_HTTP && USE_NGHTTP2 */