Coverage Report

Created: 2026-07-16 06:10

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