Coverage Report

Created: 2026-05-30 06:06

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