Coverage Report

Created: 2026-10-15 06:17

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