Coverage Report

Created: 2025-07-18 07:19

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