Coverage Report

Created: 2026-04-29 07:01

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