Coverage Report

Created: 2026-12-01 06:28

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