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