Coverage Report

Created: 2026-10-22 06:48

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