http2.c 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at https://curl.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. * SPDX-License-Identifier: curl
  22. *
  23. ***************************************************************************/
  24. #include "curl_setup.h"
  25. #ifdef USE_NGHTTP2
  26. #include <stdint.h>
  27. #include <nghttp2/nghttp2.h>
  28. #include "urldata.h"
  29. #include "bufq.h"
  30. #include "http1.h"
  31. #include "http2.h"
  32. #include "http.h"
  33. #include "sendf.h"
  34. #include "select.h"
  35. #include "curl_base64.h"
  36. #include "strcase.h"
  37. #include "multiif.h"
  38. #include "url.h"
  39. #include "urlapi-int.h"
  40. #include "cfilters.h"
  41. #include "connect.h"
  42. #include "strtoofft.h"
  43. #include "strdup.h"
  44. #include "transfer.h"
  45. #include "dynbuf.h"
  46. #include "headers.h"
  47. /* The last 3 #include files should be in this order */
  48. #include "curl_printf.h"
  49. #include "curl_memory.h"
  50. #include "memdebug.h"
  51. #if (NGHTTP2_VERSION_NUM < 0x010c00)
  52. #error too old nghttp2 version, upgrade!
  53. #endif
  54. #ifdef CURL_DISABLE_VERBOSE_STRINGS
  55. #define nghttp2_session_callbacks_set_error_callback(x,y)
  56. #endif
  57. #if (NGHTTP2_VERSION_NUM >= 0x010c00)
  58. #define NGHTTP2_HAS_SET_LOCAL_WINDOW_SIZE 1
  59. #endif
  60. /* buffer dimensioning:
  61. * use 16K as chunk size, as that fits H2 DATA frames well */
  62. #define H2_CHUNK_SIZE (16 * 1024)
  63. /* this is how much we want "in flight" for a stream */
  64. #define H2_STREAM_WINDOW_SIZE (10 * 1024 * 1024)
  65. /* on receving from TLS, we prep for holding a full stream window */
  66. #define H2_NW_RECV_CHUNKS (H2_STREAM_WINDOW_SIZE / H2_CHUNK_SIZE)
  67. /* on send into TLS, we just want to accumulate small frames */
  68. #define H2_NW_SEND_CHUNKS 1
  69. /* stream recv/send chunks are a result of window / chunk sizes */
  70. #define H2_STREAM_RECV_CHUNKS (H2_STREAM_WINDOW_SIZE / H2_CHUNK_SIZE)
  71. /* keep smaller stream upload buffer (default h2 window size) to have
  72. * our progress bars and "upload done" reporting closer to reality */
  73. #define H2_STREAM_SEND_CHUNKS ((64 * 1024) / H2_CHUNK_SIZE)
  74. /* spare chunks we keep for a full window */
  75. #define H2_STREAM_POOL_SPARES (H2_STREAM_WINDOW_SIZE / H2_CHUNK_SIZE)
  76. /* We need to accommodate the max number of streams with their window
  77. * sizes on the overall connection. Streams might become PAUSED which
  78. * will block their received QUOTA in the connection window. And if we
  79. * run out of space, the server is blocked from sending us any data.
  80. * See #10988 for an issue with this. */
  81. #define HTTP2_HUGE_WINDOW_SIZE (100 * H2_STREAM_WINDOW_SIZE)
  82. #define H2_SETTINGS_IV_LEN 3
  83. #define H2_BINSETTINGS_LEN 80
  84. static int populate_settings(nghttp2_settings_entry *iv,
  85. struct Curl_easy *data)
  86. {
  87. iv[0].settings_id = NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS;
  88. iv[0].value = Curl_multi_max_concurrent_streams(data->multi);
  89. iv[1].settings_id = NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE;
  90. iv[1].value = H2_STREAM_WINDOW_SIZE;
  91. iv[2].settings_id = NGHTTP2_SETTINGS_ENABLE_PUSH;
  92. iv[2].value = data->multi->push_cb != NULL;
  93. return 3;
  94. }
  95. static size_t populate_binsettings(uint8_t *binsettings,
  96. struct Curl_easy *data)
  97. {
  98. nghttp2_settings_entry iv[H2_SETTINGS_IV_LEN];
  99. int ivlen;
  100. ivlen = populate_settings(iv, data);
  101. /* this returns number of bytes it wrote */
  102. return nghttp2_pack_settings_payload(binsettings, H2_BINSETTINGS_LEN,
  103. iv, ivlen);
  104. }
  105. struct cf_h2_ctx {
  106. nghttp2_session *h2;
  107. uint32_t max_concurrent_streams;
  108. /* The easy handle used in the current filter call, cleared at return */
  109. struct cf_call_data call_data;
  110. struct bufq inbufq; /* network input */
  111. struct bufq outbufq; /* network output */
  112. struct bufc_pool stream_bufcp; /* spares for stream buffers */
  113. size_t drain_total; /* sum of all stream's UrlState drain */
  114. int32_t goaway_error;
  115. int32_t last_stream_id;
  116. BIT(conn_closed);
  117. BIT(goaway);
  118. BIT(enable_push);
  119. BIT(nw_out_blocked);
  120. };
  121. /* How to access `call_data` from a cf_h2 filter */
  122. #undef CF_CTX_CALL_DATA
  123. #define CF_CTX_CALL_DATA(cf) \
  124. ((struct cf_h2_ctx *)(cf)->ctx)->call_data
  125. static void cf_h2_ctx_clear(struct cf_h2_ctx *ctx)
  126. {
  127. struct cf_call_data save = ctx->call_data;
  128. if(ctx->h2) {
  129. nghttp2_session_del(ctx->h2);
  130. }
  131. Curl_bufq_free(&ctx->inbufq);
  132. Curl_bufq_free(&ctx->outbufq);
  133. Curl_bufcp_free(&ctx->stream_bufcp);
  134. memset(ctx, 0, sizeof(*ctx));
  135. ctx->call_data = save;
  136. }
  137. static void cf_h2_ctx_free(struct cf_h2_ctx *ctx)
  138. {
  139. if(ctx) {
  140. cf_h2_ctx_clear(ctx);
  141. free(ctx);
  142. }
  143. }
  144. static CURLcode h2_progress_egress(struct Curl_cfilter *cf,
  145. struct Curl_easy *data);
  146. /**
  147. * All about the H3 internals of a stream
  148. */
  149. struct stream_ctx {
  150. /*********** for HTTP/2 we store stream-local data here *************/
  151. int32_t id; /* HTTP/2 protocol identifier for stream */
  152. struct bufq recvbuf; /* response buffer */
  153. struct bufq sendbuf; /* request buffer */
  154. struct dynhds resp_trailers; /* response trailer fields */
  155. size_t resp_hds_len; /* amount of response header bytes in recvbuf */
  156. size_t upload_blocked_len;
  157. curl_off_t upload_left; /* number of request bytes left to upload */
  158. char **push_headers; /* allocated array */
  159. size_t push_headers_used; /* number of entries filled in */
  160. size_t push_headers_alloc; /* number of entries allocated */
  161. int status_code; /* HTTP response status code */
  162. uint32_t error; /* stream error code */
  163. uint32_t local_window_size; /* the local recv window size */
  164. bool closed; /* TRUE on stream close */
  165. bool reset; /* TRUE on stream reset */
  166. bool close_handled; /* TRUE if stream closure is handled by libcurl */
  167. bool bodystarted;
  168. bool send_closed; /* transfer is done sending, we might have still
  169. buffered data in stream->sendbuf to upload. */
  170. };
  171. #define H2_STREAM_CTX(d) ((struct stream_ctx *)(((d) && (d)->req.p.http)? \
  172. ((struct HTTP *)(d)->req.p.http)->h2_ctx \
  173. : NULL))
  174. #define H2_STREAM_LCTX(d) ((struct HTTP *)(d)->req.p.http)->h2_ctx
  175. #define H2_STREAM_ID(d) (H2_STREAM_CTX(d)? \
  176. H2_STREAM_CTX(d)->id : -2)
  177. /*
  178. * Mark this transfer to get "drained".
  179. */
  180. static void drain_stream(struct Curl_cfilter *cf,
  181. struct Curl_easy *data,
  182. struct stream_ctx *stream)
  183. {
  184. unsigned char bits;
  185. (void)cf;
  186. bits = CURL_CSELECT_IN;
  187. if(!stream->send_closed &&
  188. (stream->upload_left || stream->upload_blocked_len))
  189. bits |= CURL_CSELECT_OUT;
  190. if(data->state.dselect_bits != bits) {
  191. DEBUGF(LOG_CF(data, cf, "[h2sid=%d] DRAIN dselect_bits=%x",
  192. stream->id, bits));
  193. data->state.dselect_bits = bits;
  194. Curl_expire(data, 0, EXPIRE_RUN_NOW);
  195. }
  196. }
  197. static CURLcode http2_data_setup(struct Curl_cfilter *cf,
  198. struct Curl_easy *data,
  199. struct stream_ctx **pstream)
  200. {
  201. struct cf_h2_ctx *ctx = cf->ctx;
  202. struct stream_ctx *stream;
  203. (void)cf;
  204. DEBUGASSERT(data);
  205. if(!data->req.p.http) {
  206. failf(data, "initialization failure, transfer not http initialized");
  207. return CURLE_FAILED_INIT;
  208. }
  209. stream = H2_STREAM_CTX(data);
  210. if(stream) {
  211. *pstream = stream;
  212. return CURLE_OK;
  213. }
  214. stream = calloc(1, sizeof(*stream));
  215. if(!stream)
  216. return CURLE_OUT_OF_MEMORY;
  217. stream->id = -1;
  218. Curl_bufq_initp(&stream->sendbuf, &ctx->stream_bufcp,
  219. H2_STREAM_SEND_CHUNKS, BUFQ_OPT_NONE);
  220. Curl_bufq_initp(&stream->recvbuf, &ctx->stream_bufcp,
  221. H2_STREAM_RECV_CHUNKS, BUFQ_OPT_SOFT_LIMIT);
  222. Curl_dynhds_init(&stream->resp_trailers, 0, DYN_HTTP_REQUEST);
  223. stream->resp_hds_len = 0;
  224. stream->bodystarted = FALSE;
  225. stream->status_code = -1;
  226. stream->closed = FALSE;
  227. stream->close_handled = FALSE;
  228. stream->error = NGHTTP2_NO_ERROR;
  229. stream->local_window_size = H2_STREAM_WINDOW_SIZE;
  230. stream->upload_left = 0;
  231. H2_STREAM_LCTX(data) = stream;
  232. *pstream = stream;
  233. return CURLE_OK;
  234. }
  235. static void http2_data_done(struct Curl_cfilter *cf,
  236. struct Curl_easy *data, bool premature)
  237. {
  238. struct cf_h2_ctx *ctx = cf->ctx;
  239. struct stream_ctx *stream = H2_STREAM_CTX(data);
  240. DEBUGASSERT(ctx);
  241. (void)premature;
  242. if(!stream)
  243. return;
  244. if(ctx->h2) {
  245. if(!stream->closed && stream->id > 0) {
  246. /* RST_STREAM */
  247. DEBUGF(LOG_CF(data, cf, "[h2sid=%d] premature DATA_DONE, RST stream",
  248. stream->id));
  249. if(!nghttp2_submit_rst_stream(ctx->h2, NGHTTP2_FLAG_NONE,
  250. stream->id, NGHTTP2_STREAM_CLOSED))
  251. (void)nghttp2_session_send(ctx->h2);
  252. }
  253. if(!Curl_bufq_is_empty(&stream->recvbuf)) {
  254. /* Anything in the recvbuf is still being counted
  255. * in stream and connection window flow control. Need
  256. * to free that space or the connection window might get
  257. * exhausted eventually. */
  258. nghttp2_session_consume(ctx->h2, stream->id,
  259. Curl_bufq_len(&stream->recvbuf));
  260. /* give WINDOW_UPATE a chance to be sent, but ignore any error */
  261. (void)h2_progress_egress(cf, data);
  262. }
  263. /* -1 means unassigned and 0 means cleared */
  264. if(nghttp2_session_get_stream_user_data(ctx->h2, stream->id)) {
  265. int rv = nghttp2_session_set_stream_user_data(ctx->h2,
  266. stream->id, 0);
  267. if(rv) {
  268. infof(data, "http/2: failed to clear user_data for stream %u",
  269. stream->id);
  270. DEBUGASSERT(0);
  271. }
  272. }
  273. }
  274. Curl_bufq_free(&stream->sendbuf);
  275. Curl_bufq_free(&stream->recvbuf);
  276. Curl_dynhds_free(&stream->resp_trailers);
  277. if(stream->push_headers) {
  278. /* if they weren't used and then freed before */
  279. for(; stream->push_headers_used > 0; --stream->push_headers_used) {
  280. free(stream->push_headers[stream->push_headers_used - 1]);
  281. }
  282. free(stream->push_headers);
  283. stream->push_headers = NULL;
  284. }
  285. free(stream);
  286. H2_STREAM_LCTX(data) = NULL;
  287. }
  288. static int h2_client_new(struct Curl_cfilter *cf,
  289. nghttp2_session_callbacks *cbs)
  290. {
  291. struct cf_h2_ctx *ctx = cf->ctx;
  292. nghttp2_option *o;
  293. int rc = nghttp2_option_new(&o);
  294. if(rc)
  295. return rc;
  296. /* We handle window updates ourself to enforce buffer limits */
  297. nghttp2_option_set_no_auto_window_update(o, 1);
  298. #if NGHTTP2_VERSION_NUM >= 0x013200
  299. /* with 1.50.0 */
  300. /* turn off RFC 9113 leading and trailing white spaces validation against
  301. HTTP field value. */
  302. nghttp2_option_set_no_rfc9113_leading_and_trailing_ws_validation(o, 1);
  303. #endif
  304. rc = nghttp2_session_client_new2(&ctx->h2, cbs, cf, o);
  305. nghttp2_option_del(o);
  306. return rc;
  307. }
  308. static ssize_t nw_in_reader(void *reader_ctx,
  309. unsigned char *buf, size_t buflen,
  310. CURLcode *err)
  311. {
  312. struct Curl_cfilter *cf = reader_ctx;
  313. struct Curl_easy *data = CF_DATA_CURRENT(cf);
  314. return Curl_conn_cf_recv(cf->next, data, (char *)buf, buflen, err);
  315. }
  316. static ssize_t nw_out_writer(void *writer_ctx,
  317. const unsigned char *buf, size_t buflen,
  318. CURLcode *err)
  319. {
  320. struct Curl_cfilter *cf = writer_ctx;
  321. struct Curl_easy *data = CF_DATA_CURRENT(cf);
  322. return Curl_conn_cf_send(cf->next, data, (const char *)buf, buflen, err);
  323. }
  324. static ssize_t send_callback(nghttp2_session *h2,
  325. const uint8_t *mem, size_t length, int flags,
  326. void *userp);
  327. static int on_frame_recv(nghttp2_session *session, const nghttp2_frame *frame,
  328. void *userp);
  329. static int on_data_chunk_recv(nghttp2_session *session, uint8_t flags,
  330. int32_t stream_id,
  331. const uint8_t *mem, size_t len, void *userp);
  332. static int on_stream_close(nghttp2_session *session, int32_t stream_id,
  333. uint32_t error_code, void *userp);
  334. static int on_begin_headers(nghttp2_session *session,
  335. const nghttp2_frame *frame, void *userp);
  336. static int on_header(nghttp2_session *session, const nghttp2_frame *frame,
  337. const uint8_t *name, size_t namelen,
  338. const uint8_t *value, size_t valuelen,
  339. uint8_t flags,
  340. void *userp);
  341. static int error_callback(nghttp2_session *session, const char *msg,
  342. size_t len, void *userp);
  343. /*
  344. * Initialize the cfilter context
  345. */
  346. static CURLcode cf_h2_ctx_init(struct Curl_cfilter *cf,
  347. struct Curl_easy *data,
  348. bool via_h1_upgrade)
  349. {
  350. struct cf_h2_ctx *ctx = cf->ctx;
  351. struct stream_ctx *stream;
  352. CURLcode result = CURLE_OUT_OF_MEMORY;
  353. int rc;
  354. nghttp2_session_callbacks *cbs = NULL;
  355. DEBUGASSERT(!ctx->h2);
  356. Curl_bufcp_init(&ctx->stream_bufcp, H2_CHUNK_SIZE, H2_STREAM_POOL_SPARES);
  357. Curl_bufq_initp(&ctx->inbufq, &ctx->stream_bufcp, H2_NW_RECV_CHUNKS, 0);
  358. Curl_bufq_initp(&ctx->outbufq, &ctx->stream_bufcp, H2_NW_SEND_CHUNKS, 0);
  359. ctx->last_stream_id = 2147483647;
  360. rc = nghttp2_session_callbacks_new(&cbs);
  361. if(rc) {
  362. failf(data, "Couldn't initialize nghttp2 callbacks");
  363. goto out;
  364. }
  365. nghttp2_session_callbacks_set_send_callback(cbs, send_callback);
  366. nghttp2_session_callbacks_set_on_frame_recv_callback(cbs, on_frame_recv);
  367. nghttp2_session_callbacks_set_on_data_chunk_recv_callback(
  368. cbs, on_data_chunk_recv);
  369. nghttp2_session_callbacks_set_on_stream_close_callback(cbs, on_stream_close);
  370. nghttp2_session_callbacks_set_on_begin_headers_callback(
  371. cbs, on_begin_headers);
  372. nghttp2_session_callbacks_set_on_header_callback(cbs, on_header);
  373. nghttp2_session_callbacks_set_error_callback(cbs, error_callback);
  374. /* The nghttp2 session is not yet setup, do it */
  375. rc = h2_client_new(cf, cbs);
  376. if(rc) {
  377. failf(data, "Couldn't initialize nghttp2");
  378. goto out;
  379. }
  380. ctx->max_concurrent_streams = DEFAULT_MAX_CONCURRENT_STREAMS;
  381. if(via_h1_upgrade) {
  382. /* HTTP/1.1 Upgrade issued. H2 Settings have already been submitted
  383. * in the H1 request and we upgrade from there. This stream
  384. * is opened implicitly as #1. */
  385. uint8_t binsettings[H2_BINSETTINGS_LEN];
  386. size_t binlen; /* length of the binsettings data */
  387. binlen = populate_binsettings(binsettings, data);
  388. result = http2_data_setup(cf, data, &stream);
  389. if(result)
  390. goto out;
  391. DEBUGASSERT(stream);
  392. stream->id = 1;
  393. /* queue SETTINGS frame (again) */
  394. rc = nghttp2_session_upgrade2(ctx->h2, binsettings, binlen,
  395. data->state.httpreq == HTTPREQ_HEAD,
  396. NULL);
  397. if(rc) {
  398. failf(data, "nghttp2_session_upgrade2() failed: %s(%d)",
  399. nghttp2_strerror(rc), rc);
  400. result = CURLE_HTTP2;
  401. goto out;
  402. }
  403. rc = nghttp2_session_set_stream_user_data(ctx->h2, stream->id,
  404. data);
  405. if(rc) {
  406. infof(data, "http/2: failed to set user_data for stream %u",
  407. stream->id);
  408. DEBUGASSERT(0);
  409. }
  410. }
  411. else {
  412. nghttp2_settings_entry iv[H2_SETTINGS_IV_LEN];
  413. int ivlen;
  414. ivlen = populate_settings(iv, data);
  415. rc = nghttp2_submit_settings(ctx->h2, NGHTTP2_FLAG_NONE,
  416. iv, ivlen);
  417. if(rc) {
  418. failf(data, "nghttp2_submit_settings() failed: %s(%d)",
  419. nghttp2_strerror(rc), rc);
  420. result = CURLE_HTTP2;
  421. goto out;
  422. }
  423. }
  424. rc = nghttp2_session_set_local_window_size(ctx->h2, NGHTTP2_FLAG_NONE, 0,
  425. HTTP2_HUGE_WINDOW_SIZE);
  426. if(rc) {
  427. failf(data, "nghttp2_session_set_local_window_size() failed: %s(%d)",
  428. nghttp2_strerror(rc), rc);
  429. result = CURLE_HTTP2;
  430. goto out;
  431. }
  432. /* all set, traffic will be send on connect */
  433. result = CURLE_OK;
  434. out:
  435. if(cbs)
  436. nghttp2_session_callbacks_del(cbs);
  437. return result;
  438. }
  439. /*
  440. * Returns nonzero if current HTTP/2 session should be closed.
  441. */
  442. static int should_close_session(struct cf_h2_ctx *ctx)
  443. {
  444. return ctx->drain_total == 0 && !nghttp2_session_want_read(ctx->h2) &&
  445. !nghttp2_session_want_write(ctx->h2);
  446. }
  447. /*
  448. * Processes pending input left in network input buffer.
  449. * This function returns 0 if it succeeds, or -1 and error code will
  450. * be assigned to *err.
  451. */
  452. static int h2_process_pending_input(struct Curl_cfilter *cf,
  453. struct Curl_easy *data,
  454. CURLcode *err)
  455. {
  456. struct cf_h2_ctx *ctx = cf->ctx;
  457. const unsigned char *buf;
  458. size_t blen;
  459. ssize_t rv;
  460. while(Curl_bufq_peek(&ctx->inbufq, &buf, &blen)) {
  461. rv = nghttp2_session_mem_recv(ctx->h2, (const uint8_t *)buf, blen);
  462. if(rv < 0) {
  463. failf(data,
  464. "process_pending_input: nghttp2_session_mem_recv() returned "
  465. "%zd:%s", rv, nghttp2_strerror((int)rv));
  466. *err = CURLE_RECV_ERROR;
  467. return -1;
  468. }
  469. Curl_bufq_skip(&ctx->inbufq, (size_t)rv);
  470. if(Curl_bufq_is_empty(&ctx->inbufq)) {
  471. break;
  472. }
  473. else {
  474. DEBUGF(LOG_CF(data, cf, "process_pending_input: %zu bytes left "
  475. "in connection buffer", Curl_bufq_len(&ctx->inbufq)));
  476. }
  477. }
  478. if(nghttp2_session_check_request_allowed(ctx->h2) == 0) {
  479. /* No more requests are allowed in the current session, so
  480. the connection may not be reused. This is set when a
  481. GOAWAY frame has been received or when the limit of stream
  482. identifiers has been reached. */
  483. connclose(cf->conn, "http/2: No new requests allowed");
  484. }
  485. return 0;
  486. }
  487. /*
  488. * The server may send us data at any point (e.g. PING frames). Therefore,
  489. * we cannot assume that an HTTP/2 socket is dead just because it is readable.
  490. *
  491. * Check the lower filters first and, if successful, peek at the socket
  492. * and distinguish between closed and data.
  493. */
  494. static bool http2_connisalive(struct Curl_cfilter *cf, struct Curl_easy *data,
  495. bool *input_pending)
  496. {
  497. struct cf_h2_ctx *ctx = cf->ctx;
  498. bool alive = TRUE;
  499. *input_pending = FALSE;
  500. if(!cf->next || !cf->next->cft->is_alive(cf->next, data, input_pending))
  501. return FALSE;
  502. if(*input_pending) {
  503. /* This happens before we've sent off a request and the connection is
  504. not in use by any other transfer, there shouldn't be any data here,
  505. only "protocol frames" */
  506. CURLcode result;
  507. ssize_t nread = -1;
  508. *input_pending = FALSE;
  509. nread = Curl_bufq_slurp(&ctx->inbufq, nw_in_reader, cf, &result);
  510. if(nread != -1) {
  511. DEBUGF(LOG_CF(data, cf, "%zd bytes stray data read before trying "
  512. "h2 connection", nread));
  513. if(h2_process_pending_input(cf, data, &result) < 0)
  514. /* immediate error, considered dead */
  515. alive = FALSE;
  516. else {
  517. alive = !should_close_session(ctx);
  518. }
  519. }
  520. else if(result != CURLE_AGAIN) {
  521. /* the read failed so let's say this is dead anyway */
  522. alive = FALSE;
  523. }
  524. }
  525. return alive;
  526. }
  527. static CURLcode http2_send_ping(struct Curl_cfilter *cf,
  528. struct Curl_easy *data)
  529. {
  530. struct cf_h2_ctx *ctx = cf->ctx;
  531. int rc;
  532. rc = nghttp2_submit_ping(ctx->h2, 0, ZERO_NULL);
  533. if(rc) {
  534. failf(data, "nghttp2_submit_ping() failed: %s(%d)",
  535. nghttp2_strerror(rc), rc);
  536. return CURLE_HTTP2;
  537. }
  538. rc = nghttp2_session_send(ctx->h2);
  539. if(rc) {
  540. failf(data, "nghttp2_session_send() failed: %s(%d)",
  541. nghttp2_strerror(rc), rc);
  542. return CURLE_SEND_ERROR;
  543. }
  544. return CURLE_OK;
  545. }
  546. /*
  547. * Store nghttp2 version info in this buffer.
  548. */
  549. void Curl_http2_ver(char *p, size_t len)
  550. {
  551. nghttp2_info *h2 = nghttp2_version(0);
  552. (void)msnprintf(p, len, "nghttp2/%s", h2->version_str);
  553. }
  554. static CURLcode nw_out_flush(struct Curl_cfilter *cf,
  555. struct Curl_easy *data)
  556. {
  557. struct cf_h2_ctx *ctx = cf->ctx;
  558. ssize_t nwritten;
  559. CURLcode result;
  560. (void)data;
  561. if(Curl_bufq_is_empty(&ctx->outbufq))
  562. return CURLE_OK;
  563. nwritten = Curl_bufq_pass(&ctx->outbufq, nw_out_writer, cf, &result);
  564. if(nwritten < 0) {
  565. if(result == CURLE_AGAIN) {
  566. DEBUGF(LOG_CF(data, cf, "flush nw send buffer(%zu) -> EAGAIN",
  567. Curl_bufq_len(&ctx->outbufq)));
  568. ctx->nw_out_blocked = 1;
  569. }
  570. return result;
  571. }
  572. DEBUGF(LOG_CF(data, cf, "nw send buffer flushed"));
  573. return Curl_bufq_is_empty(&ctx->outbufq)? CURLE_OK: CURLE_AGAIN;
  574. }
  575. /*
  576. * The implementation of nghttp2_send_callback type. Here we write |data| with
  577. * size |length| to the network and return the number of bytes actually
  578. * written. See the documentation of nghttp2_send_callback for the details.
  579. */
  580. static ssize_t send_callback(nghttp2_session *h2,
  581. const uint8_t *buf, size_t blen, int flags,
  582. void *userp)
  583. {
  584. struct Curl_cfilter *cf = userp;
  585. struct cf_h2_ctx *ctx = cf->ctx;
  586. struct Curl_easy *data = CF_DATA_CURRENT(cf);
  587. ssize_t nwritten;
  588. CURLcode result = CURLE_OK;
  589. (void)h2;
  590. (void)flags;
  591. DEBUGASSERT(data);
  592. nwritten = Curl_bufq_write_pass(&ctx->outbufq, buf, blen,
  593. nw_out_writer, cf, &result);
  594. if(nwritten < 0) {
  595. if(result == CURLE_AGAIN) {
  596. ctx->nw_out_blocked = 1;
  597. return NGHTTP2_ERR_WOULDBLOCK;
  598. }
  599. failf(data, "Failed sending HTTP2 data");
  600. return NGHTTP2_ERR_CALLBACK_FAILURE;
  601. }
  602. if(!nwritten) {
  603. ctx->nw_out_blocked = 1;
  604. return NGHTTP2_ERR_WOULDBLOCK;
  605. }
  606. return nwritten;
  607. }
  608. /* We pass a pointer to this struct in the push callback, but the contents of
  609. the struct are hidden from the user. */
  610. struct curl_pushheaders {
  611. struct Curl_easy *data;
  612. const nghttp2_push_promise *frame;
  613. };
  614. /*
  615. * push header access function. Only to be used from within the push callback
  616. */
  617. char *curl_pushheader_bynum(struct curl_pushheaders *h, size_t num)
  618. {
  619. /* Verify that we got a good easy handle in the push header struct, mostly to
  620. detect rubbish input fast(er). */
  621. if(!h || !GOOD_EASY_HANDLE(h->data))
  622. return NULL;
  623. else {
  624. struct stream_ctx *stream = H2_STREAM_CTX(h->data);
  625. if(stream && num < stream->push_headers_used)
  626. return stream->push_headers[num];
  627. }
  628. return NULL;
  629. }
  630. /*
  631. * push header access function. Only to be used from within the push callback
  632. */
  633. char *curl_pushheader_byname(struct curl_pushheaders *h, const char *header)
  634. {
  635. struct stream_ctx *stream;
  636. size_t len;
  637. size_t i;
  638. /* Verify that we got a good easy handle in the push header struct,
  639. mostly to detect rubbish input fast(er). Also empty header name
  640. is just a rubbish too. We have to allow ":" at the beginning of
  641. the header, but header == ":" must be rejected. If we have ':' in
  642. the middle of header, it could be matched in middle of the value,
  643. this is because we do prefix match.*/
  644. if(!h || !GOOD_EASY_HANDLE(h->data) || !header || !header[0] ||
  645. !strcmp(header, ":") || strchr(header + 1, ':'))
  646. return NULL;
  647. stream = H2_STREAM_CTX(h->data);
  648. if(!stream)
  649. return NULL;
  650. len = strlen(header);
  651. for(i = 0; i<stream->push_headers_used; i++) {
  652. if(!strncmp(header, stream->push_headers[i], len)) {
  653. /* sub-match, make sure that it is followed by a colon */
  654. if(stream->push_headers[i][len] != ':')
  655. continue;
  656. return &stream->push_headers[i][len + 1];
  657. }
  658. }
  659. return NULL;
  660. }
  661. static struct Curl_easy *h2_duphandle(struct Curl_cfilter *cf,
  662. struct Curl_easy *data)
  663. {
  664. struct Curl_easy *second = curl_easy_duphandle(data);
  665. if(second) {
  666. /* setup the request struct */
  667. struct HTTP *http = calloc(1, sizeof(struct HTTP));
  668. if(!http) {
  669. (void)Curl_close(&second);
  670. }
  671. else {
  672. struct stream_ctx *second_stream;
  673. second->req.p.http = http;
  674. http2_data_setup(cf, second, &second_stream);
  675. second->state.priority.weight = data->state.priority.weight;
  676. }
  677. }
  678. return second;
  679. }
  680. static int set_transfer_url(struct Curl_easy *data,
  681. struct curl_pushheaders *hp)
  682. {
  683. const char *v;
  684. CURLUcode uc;
  685. char *url = NULL;
  686. int rc = 0;
  687. CURLU *u = curl_url();
  688. if(!u)
  689. return 5;
  690. v = curl_pushheader_byname(hp, HTTP_PSEUDO_SCHEME);
  691. if(v) {
  692. uc = curl_url_set(u, CURLUPART_SCHEME, v, 0);
  693. if(uc) {
  694. rc = 1;
  695. goto fail;
  696. }
  697. }
  698. v = curl_pushheader_byname(hp, HTTP_PSEUDO_AUTHORITY);
  699. if(v) {
  700. uc = Curl_url_set_authority(u, v, CURLU_DISALLOW_USER);
  701. if(uc) {
  702. rc = 2;
  703. goto fail;
  704. }
  705. }
  706. v = curl_pushheader_byname(hp, HTTP_PSEUDO_PATH);
  707. if(v) {
  708. uc = curl_url_set(u, CURLUPART_PATH, v, 0);
  709. if(uc) {
  710. rc = 3;
  711. goto fail;
  712. }
  713. }
  714. uc = curl_url_get(u, CURLUPART_URL, &url, 0);
  715. if(uc)
  716. rc = 4;
  717. fail:
  718. curl_url_cleanup(u);
  719. if(rc)
  720. return rc;
  721. if(data->state.url_alloc)
  722. free(data->state.url);
  723. data->state.url_alloc = TRUE;
  724. data->state.url = url;
  725. return 0;
  726. }
  727. static void discard_newhandle(struct Curl_cfilter *cf,
  728. struct Curl_easy *newhandle)
  729. {
  730. if(!newhandle->req.p.http) {
  731. http2_data_done(cf, newhandle, TRUE);
  732. newhandle->req.p.http = NULL;
  733. }
  734. (void)Curl_close(&newhandle);
  735. }
  736. static int push_promise(struct Curl_cfilter *cf,
  737. struct Curl_easy *data,
  738. const nghttp2_push_promise *frame)
  739. {
  740. struct cf_h2_ctx *ctx = cf->ctx;
  741. int rv; /* one of the CURL_PUSH_* defines */
  742. DEBUGF(LOG_CF(data, cf, "[h2sid=%d] PUSH_PROMISE received",
  743. frame->promised_stream_id));
  744. if(data->multi->push_cb) {
  745. struct stream_ctx *stream;
  746. struct stream_ctx *newstream;
  747. struct curl_pushheaders heads;
  748. CURLMcode rc;
  749. CURLcode result;
  750. size_t i;
  751. /* clone the parent */
  752. struct Curl_easy *newhandle = h2_duphandle(cf, data);
  753. if(!newhandle) {
  754. infof(data, "failed to duplicate handle");
  755. rv = CURL_PUSH_DENY; /* FAIL HARD */
  756. goto fail;
  757. }
  758. heads.data = data;
  759. heads.frame = frame;
  760. /* ask the application */
  761. DEBUGF(LOG_CF(data, cf, "Got PUSH_PROMISE, ask application"));
  762. stream = H2_STREAM_CTX(data);
  763. if(!stream) {
  764. failf(data, "Internal NULL stream");
  765. discard_newhandle(cf, newhandle);
  766. rv = CURL_PUSH_DENY;
  767. goto fail;
  768. }
  769. rv = set_transfer_url(newhandle, &heads);
  770. if(rv) {
  771. discard_newhandle(cf, newhandle);
  772. rv = CURL_PUSH_DENY;
  773. goto fail;
  774. }
  775. result = http2_data_setup(cf, newhandle, &newstream);
  776. if(result) {
  777. failf(data, "error setting up stream: %d", result);
  778. discard_newhandle(cf, newhandle);
  779. rv = CURL_PUSH_DENY;
  780. goto fail;
  781. }
  782. DEBUGASSERT(stream);
  783. Curl_set_in_callback(data, true);
  784. rv = data->multi->push_cb(data, newhandle,
  785. stream->push_headers_used, &heads,
  786. data->multi->push_userp);
  787. Curl_set_in_callback(data, false);
  788. /* free the headers again */
  789. for(i = 0; i<stream->push_headers_used; i++)
  790. free(stream->push_headers[i]);
  791. free(stream->push_headers);
  792. stream->push_headers = NULL;
  793. stream->push_headers_used = 0;
  794. if(rv) {
  795. DEBUGASSERT((rv > CURL_PUSH_OK) && (rv <= CURL_PUSH_ERROROUT));
  796. /* denied, kill off the new handle again */
  797. discard_newhandle(cf, newhandle);
  798. goto fail;
  799. }
  800. newstream->id = frame->promised_stream_id;
  801. newhandle->req.maxdownload = -1;
  802. newhandle->req.size = -1;
  803. /* approved, add to the multi handle and immediately switch to PERFORM
  804. state with the given connection !*/
  805. rc = Curl_multi_add_perform(data->multi, newhandle, cf->conn);
  806. if(rc) {
  807. infof(data, "failed to add handle to multi");
  808. discard_newhandle(cf, newhandle);
  809. rv = CURL_PUSH_DENY;
  810. goto fail;
  811. }
  812. rv = nghttp2_session_set_stream_user_data(ctx->h2,
  813. newstream->id,
  814. newhandle);
  815. if(rv) {
  816. infof(data, "failed to set user_data for stream %u",
  817. newstream->id);
  818. DEBUGASSERT(0);
  819. rv = CURL_PUSH_DENY;
  820. goto fail;
  821. }
  822. }
  823. else {
  824. DEBUGF(LOG_CF(data, cf, "Got PUSH_PROMISE, ignore it"));
  825. rv = CURL_PUSH_DENY;
  826. }
  827. fail:
  828. return rv;
  829. }
  830. static CURLcode recvbuf_write_hds(struct Curl_cfilter *cf,
  831. struct Curl_easy *data,
  832. const char *buf, size_t blen)
  833. {
  834. struct stream_ctx *stream = H2_STREAM_CTX(data);
  835. ssize_t nwritten;
  836. CURLcode result;
  837. (void)cf;
  838. nwritten = Curl_bufq_write(&stream->recvbuf,
  839. (const unsigned char *)buf, blen, &result);
  840. if(nwritten < 0)
  841. return result;
  842. stream->resp_hds_len += (size_t)nwritten;
  843. DEBUGASSERT((size_t)nwritten == blen);
  844. return CURLE_OK;
  845. }
  846. static CURLcode on_stream_frame(struct Curl_cfilter *cf,
  847. struct Curl_easy *data,
  848. const nghttp2_frame *frame)
  849. {
  850. struct cf_h2_ctx *ctx = cf->ctx;
  851. struct stream_ctx *stream = H2_STREAM_CTX(data);
  852. int32_t stream_id = frame->hd.stream_id;
  853. CURLcode result;
  854. size_t rbuflen;
  855. int rv;
  856. if(!stream) {
  857. DEBUGF(LOG_CF(data, cf, "[h2sid=%d] No proto pointer", stream_id));
  858. return CURLE_FAILED_INIT;
  859. }
  860. switch(frame->hd.type) {
  861. case NGHTTP2_DATA:
  862. rbuflen = Curl_bufq_len(&stream->recvbuf);
  863. DEBUGF(LOG_CF(data, cf, "[h2sid=%d] FRAME[DATA len=%zu pad=%zu], "
  864. "buffered=%zu, window=%d/%d",
  865. stream_id, frame->hd.length, frame->data.padlen, rbuflen,
  866. nghttp2_session_get_stream_effective_recv_data_length(
  867. ctx->h2, stream->id),
  868. nghttp2_session_get_stream_effective_local_window_size(
  869. ctx->h2, stream->id)));
  870. /* If !body started on this stream, then receiving DATA is illegal. */
  871. if(!stream->bodystarted) {
  872. rv = nghttp2_submit_rst_stream(ctx->h2, NGHTTP2_FLAG_NONE,
  873. stream_id, NGHTTP2_PROTOCOL_ERROR);
  874. if(nghttp2_is_fatal(rv)) {
  875. return CURLE_RECV_ERROR;
  876. }
  877. }
  878. if(frame->hd.flags & NGHTTP2_FLAG_END_STREAM) {
  879. drain_stream(cf, data, stream);
  880. }
  881. else if(rbuflen > stream->local_window_size) {
  882. int32_t wsize = nghttp2_session_get_stream_local_window_size(
  883. ctx->h2, stream->id);
  884. if(wsize > 0 && (uint32_t)wsize != stream->local_window_size) {
  885. /* H2 flow control is not absolute, as the server might not have the
  886. * same view, yet. When we recieve more than we want, we enforce
  887. * the local window size again to make nghttp2 send WINDOW_UPATEs
  888. * accordingly. */
  889. nghttp2_session_set_local_window_size(ctx->h2,
  890. NGHTTP2_FLAG_NONE,
  891. stream->id,
  892. stream->local_window_size);
  893. }
  894. }
  895. break;
  896. case NGHTTP2_HEADERS:
  897. DEBUGF(LOG_CF(data, cf, "[h2sid=%d] FRAME[HEADERS]", stream_id));
  898. if(stream->bodystarted) {
  899. /* Only valid HEADERS after body started is trailer HEADERS. We
  900. buffer them in on_header callback. */
  901. break;
  902. }
  903. /* nghttp2 guarantees that :status is received, and we store it to
  904. stream->status_code. Fuzzing has proven this can still be reached
  905. without status code having been set. */
  906. if(stream->status_code == -1)
  907. return CURLE_RECV_ERROR;
  908. /* Only final status code signals the end of header */
  909. if(stream->status_code / 100 != 1) {
  910. stream->bodystarted = TRUE;
  911. stream->status_code = -1;
  912. }
  913. result = recvbuf_write_hds(cf, data, STRCONST("\r\n"));
  914. if(result)
  915. return result;
  916. DEBUGF(LOG_CF(data, cf, "[h2sid=%d] %zu header bytes",
  917. stream_id, Curl_bufq_len(&stream->recvbuf)));
  918. drain_stream(cf, data, stream);
  919. break;
  920. case NGHTTP2_PUSH_PROMISE:
  921. DEBUGF(LOG_CF(data, cf, "[h2sid=%d] FRAME[PUSH_PROMISE]", stream_id));
  922. rv = push_promise(cf, data, &frame->push_promise);
  923. if(rv) { /* deny! */
  924. DEBUGASSERT((rv > CURL_PUSH_OK) && (rv <= CURL_PUSH_ERROROUT));
  925. rv = nghttp2_submit_rst_stream(ctx->h2, NGHTTP2_FLAG_NONE,
  926. frame->push_promise.promised_stream_id,
  927. NGHTTP2_CANCEL);
  928. if(nghttp2_is_fatal(rv))
  929. return CURLE_SEND_ERROR;
  930. else if(rv == CURL_PUSH_ERROROUT) {
  931. DEBUGF(LOG_CF(data, cf, "[h2sid=%d] fail in PUSH_PROMISE received",
  932. stream_id));
  933. return CURLE_RECV_ERROR;
  934. }
  935. }
  936. break;
  937. case NGHTTP2_RST_STREAM:
  938. DEBUGF(LOG_CF(data, cf, "[h2sid=%d] FRAME[RST]", stream_id));
  939. stream->closed = TRUE;
  940. stream->reset = TRUE;
  941. stream->send_closed = TRUE;
  942. data->req.keepon &= ~KEEP_SEND_HOLD;
  943. drain_stream(cf, data, stream);
  944. break;
  945. case NGHTTP2_WINDOW_UPDATE:
  946. DEBUGF(LOG_CF(data, cf, "[h2sid=%d] FRAME[WINDOW_UPDATE]", stream_id));
  947. if((data->req.keepon & KEEP_SEND_HOLD) &&
  948. (data->req.keepon & KEEP_SEND)) {
  949. data->req.keepon &= ~KEEP_SEND_HOLD;
  950. drain_stream(cf, data, stream);
  951. DEBUGF(LOG_CF(data, cf, "[h2sid=%d] un-holding after win update",
  952. stream_id));
  953. }
  954. break;
  955. default:
  956. DEBUGF(LOG_CF(data, cf, "[h2sid=%d] FRAME[%x]",
  957. stream_id, frame->hd.type));
  958. break;
  959. }
  960. return CURLE_OK;
  961. }
  962. static int on_frame_recv(nghttp2_session *session, const nghttp2_frame *frame,
  963. void *userp)
  964. {
  965. struct Curl_cfilter *cf = userp;
  966. struct cf_h2_ctx *ctx = cf->ctx;
  967. struct Curl_easy *data = CF_DATA_CURRENT(cf), *data_s;
  968. int32_t stream_id = frame->hd.stream_id;
  969. DEBUGASSERT(data);
  970. if(!stream_id) {
  971. /* stream ID zero is for connection-oriented stuff */
  972. DEBUGASSERT(data);
  973. switch(frame->hd.type) {
  974. case NGHTTP2_SETTINGS: {
  975. uint32_t max_conn = ctx->max_concurrent_streams;
  976. DEBUGF(LOG_CF(data, cf, "FRAME[SETTINGS]"));
  977. ctx->max_concurrent_streams = nghttp2_session_get_remote_settings(
  978. session, NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS);
  979. ctx->enable_push = nghttp2_session_get_remote_settings(
  980. session, NGHTTP2_SETTINGS_ENABLE_PUSH) != 0;
  981. DEBUGF(LOG_CF(data, cf, "MAX_CONCURRENT_STREAMS == %d",
  982. ctx->max_concurrent_streams));
  983. DEBUGF(LOG_CF(data, cf, "ENABLE_PUSH == %s",
  984. ctx->enable_push ? "TRUE" : "false"));
  985. if(data && max_conn != ctx->max_concurrent_streams) {
  986. /* only signal change if the value actually changed */
  987. DEBUGF(LOG_CF(data, cf, "MAX_CONCURRENT_STREAMS now %u",
  988. ctx->max_concurrent_streams));
  989. Curl_multi_connchanged(data->multi);
  990. }
  991. /* Since the initial stream window is 64K, a request might be on HOLD,
  992. * due to exhaustion. The (initial) SETTINGS may announce a much larger
  993. * window and *assume* that we treat this like a WINDOW_UPDATE. Some
  994. * servers send an explicit WINDOW_UPDATE, but not all seem to do that.
  995. * To be safe, we UNHOLD a stream in order not to stall. */
  996. if((data->req.keepon & KEEP_SEND_HOLD) &&
  997. (data->req.keepon & KEEP_SEND)) {
  998. struct stream_ctx *stream = H2_STREAM_CTX(data);
  999. data->req.keepon &= ~KEEP_SEND_HOLD;
  1000. if(stream) {
  1001. drain_stream(cf, data, stream);
  1002. DEBUGF(LOG_CF(data, cf, "[h2sid=%d] un-holding after SETTINGS",
  1003. stream_id));
  1004. }
  1005. }
  1006. break;
  1007. }
  1008. case NGHTTP2_GOAWAY:
  1009. ctx->goaway = TRUE;
  1010. ctx->goaway_error = frame->goaway.error_code;
  1011. ctx->last_stream_id = frame->goaway.last_stream_id;
  1012. if(data) {
  1013. DEBUGF(LOG_CF(data, cf, "FRAME[GOAWAY, error=%d, last_stream=%u]",
  1014. ctx->goaway_error, ctx->last_stream_id));
  1015. infof(data, "received GOAWAY, error=%d, last_stream=%u",
  1016. ctx->goaway_error, ctx->last_stream_id);
  1017. Curl_multi_connchanged(data->multi);
  1018. }
  1019. break;
  1020. case NGHTTP2_WINDOW_UPDATE:
  1021. DEBUGF(LOG_CF(data, cf, "FRAME[WINDOW_UPDATE]"));
  1022. break;
  1023. default:
  1024. DEBUGF(LOG_CF(data, cf, "recv frame %x on 0", frame->hd.type));
  1025. }
  1026. return 0;
  1027. }
  1028. data_s = nghttp2_session_get_stream_user_data(session, stream_id);
  1029. if(!data_s) {
  1030. DEBUGF(LOG_CF(data, cf, "[h2sid=%d] No Curl_easy associated",
  1031. stream_id));
  1032. return 0;
  1033. }
  1034. return on_stream_frame(cf, data_s, frame)? NGHTTP2_ERR_CALLBACK_FAILURE : 0;
  1035. }
  1036. static int on_data_chunk_recv(nghttp2_session *session, uint8_t flags,
  1037. int32_t stream_id,
  1038. const uint8_t *mem, size_t len, void *userp)
  1039. {
  1040. struct Curl_cfilter *cf = userp;
  1041. struct stream_ctx *stream;
  1042. struct Curl_easy *data_s;
  1043. ssize_t nwritten;
  1044. CURLcode result;
  1045. (void)flags;
  1046. DEBUGASSERT(stream_id); /* should never be a zero stream ID here */
  1047. DEBUGASSERT(CF_DATA_CURRENT(cf));
  1048. /* get the stream from the hash based on Stream ID */
  1049. data_s = nghttp2_session_get_stream_user_data(session, stream_id);
  1050. if(!data_s) {
  1051. /* Receiving a Stream ID not in the hash should not happen - unless
  1052. we have aborted a transfer artificially and there were more data
  1053. in the pipeline. Silently ignore. */
  1054. DEBUGF(LOG_CF(CF_DATA_CURRENT(cf), cf, "[h2sid=%d] Data for unknown",
  1055. stream_id));
  1056. /* consumed explicitly as no one will read it */
  1057. nghttp2_session_consume(session, stream_id, len);
  1058. return 0;
  1059. }
  1060. stream = H2_STREAM_CTX(data_s);
  1061. if(!stream)
  1062. return NGHTTP2_ERR_CALLBACK_FAILURE;
  1063. nwritten = Curl_bufq_write(&stream->recvbuf, mem, len, &result);
  1064. if(nwritten < 0) {
  1065. if(result != CURLE_AGAIN)
  1066. return NGHTTP2_ERR_CALLBACK_FAILURE;
  1067. nwritten = 0;
  1068. }
  1069. /* if we receive data for another handle, wake that up */
  1070. drain_stream(cf, data_s, stream);
  1071. DEBUGASSERT((size_t)nwritten == len);
  1072. return 0;
  1073. }
  1074. static int on_stream_close(nghttp2_session *session, int32_t stream_id,
  1075. uint32_t error_code, void *userp)
  1076. {
  1077. struct Curl_cfilter *cf = userp;
  1078. struct Curl_easy *data_s;
  1079. struct stream_ctx *stream;
  1080. int rv;
  1081. (void)session;
  1082. /* get the stream from the hash based on Stream ID, stream ID zero is for
  1083. connection-oriented stuff */
  1084. data_s = stream_id?
  1085. nghttp2_session_get_stream_user_data(session, stream_id) : NULL;
  1086. if(!data_s) {
  1087. return 0;
  1088. }
  1089. stream = H2_STREAM_CTX(data_s);
  1090. DEBUGF(LOG_CF(data_s, cf, "[h2sid=%d] on_stream_close(), %s (err %d)",
  1091. stream_id, nghttp2_http2_strerror(error_code), error_code));
  1092. if(!stream)
  1093. return NGHTTP2_ERR_CALLBACK_FAILURE;
  1094. stream->closed = TRUE;
  1095. stream->error = error_code;
  1096. if(stream->error)
  1097. stream->reset = TRUE;
  1098. data_s->req.keepon &= ~KEEP_SEND_HOLD;
  1099. drain_stream(cf, data_s, stream);
  1100. /* remove `data_s` from the nghttp2 stream */
  1101. rv = nghttp2_session_set_stream_user_data(session, stream_id, 0);
  1102. if(rv) {
  1103. infof(data_s, "http/2: failed to clear user_data for stream %u",
  1104. stream_id);
  1105. DEBUGASSERT(0);
  1106. }
  1107. DEBUGF(LOG_CF(data_s, cf, "[h2sid=%d] closed now", stream_id));
  1108. return 0;
  1109. }
  1110. static int on_begin_headers(nghttp2_session *session,
  1111. const nghttp2_frame *frame, void *userp)
  1112. {
  1113. struct Curl_cfilter *cf = userp;
  1114. struct stream_ctx *stream;
  1115. struct Curl_easy *data_s = NULL;
  1116. (void)cf;
  1117. data_s = nghttp2_session_get_stream_user_data(session, frame->hd.stream_id);
  1118. if(!data_s) {
  1119. return 0;
  1120. }
  1121. DEBUGF(LOG_CF(data_s, cf, "on_begin_headers() was called"));
  1122. if(frame->hd.type != NGHTTP2_HEADERS) {
  1123. return 0;
  1124. }
  1125. stream = H2_STREAM_CTX(data_s);
  1126. if(!stream || !stream->bodystarted) {
  1127. return 0;
  1128. }
  1129. return 0;
  1130. }
  1131. /* frame->hd.type is either NGHTTP2_HEADERS or NGHTTP2_PUSH_PROMISE */
  1132. static int on_header(nghttp2_session *session, const nghttp2_frame *frame,
  1133. const uint8_t *name, size_t namelen,
  1134. const uint8_t *value, size_t valuelen,
  1135. uint8_t flags,
  1136. void *userp)
  1137. {
  1138. struct Curl_cfilter *cf = userp;
  1139. struct stream_ctx *stream;
  1140. struct Curl_easy *data_s;
  1141. int32_t stream_id = frame->hd.stream_id;
  1142. CURLcode result;
  1143. (void)flags;
  1144. DEBUGASSERT(stream_id); /* should never be a zero stream ID here */
  1145. /* get the stream from the hash based on Stream ID */
  1146. data_s = nghttp2_session_get_stream_user_data(session, stream_id);
  1147. if(!data_s)
  1148. /* Receiving a Stream ID not in the hash should not happen, this is an
  1149. internal error more than anything else! */
  1150. return NGHTTP2_ERR_CALLBACK_FAILURE;
  1151. stream = H2_STREAM_CTX(data_s);
  1152. if(!stream) {
  1153. failf(data_s, "Internal NULL stream");
  1154. return NGHTTP2_ERR_CALLBACK_FAILURE;
  1155. }
  1156. /* Store received PUSH_PROMISE headers to be used when the subsequent
  1157. PUSH_PROMISE callback comes */
  1158. if(frame->hd.type == NGHTTP2_PUSH_PROMISE) {
  1159. char *h;
  1160. if(!strcmp(HTTP_PSEUDO_AUTHORITY, (const char *)name)) {
  1161. /* pseudo headers are lower case */
  1162. int rc = 0;
  1163. char *check = aprintf("%s:%d", cf->conn->host.name,
  1164. cf->conn->remote_port);
  1165. if(!check)
  1166. /* no memory */
  1167. return NGHTTP2_ERR_CALLBACK_FAILURE;
  1168. if(!strcasecompare(check, (const char *)value) &&
  1169. ((cf->conn->remote_port != cf->conn->given->defport) ||
  1170. !strcasecompare(cf->conn->host.name, (const char *)value))) {
  1171. /* This is push is not for the same authority that was asked for in
  1172. * the URL. RFC 7540 section 8.2 says: "A client MUST treat a
  1173. * PUSH_PROMISE for which the server is not authoritative as a stream
  1174. * error of type PROTOCOL_ERROR."
  1175. */
  1176. (void)nghttp2_submit_rst_stream(session, NGHTTP2_FLAG_NONE,
  1177. stream_id, NGHTTP2_PROTOCOL_ERROR);
  1178. rc = NGHTTP2_ERR_CALLBACK_FAILURE;
  1179. }
  1180. free(check);
  1181. if(rc)
  1182. return rc;
  1183. }
  1184. if(!stream->push_headers) {
  1185. stream->push_headers_alloc = 10;
  1186. stream->push_headers = malloc(stream->push_headers_alloc *
  1187. sizeof(char *));
  1188. if(!stream->push_headers)
  1189. return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
  1190. stream->push_headers_used = 0;
  1191. }
  1192. else if(stream->push_headers_used ==
  1193. stream->push_headers_alloc) {
  1194. char **headp;
  1195. if(stream->push_headers_alloc > 1000) {
  1196. /* this is beyond crazy many headers, bail out */
  1197. failf(data_s, "Too many PUSH_PROMISE headers");
  1198. Curl_safefree(stream->push_headers);
  1199. return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
  1200. }
  1201. stream->push_headers_alloc *= 2;
  1202. headp = Curl_saferealloc(stream->push_headers,
  1203. stream->push_headers_alloc * sizeof(char *));
  1204. if(!headp) {
  1205. stream->push_headers = NULL;
  1206. return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
  1207. }
  1208. stream->push_headers = headp;
  1209. }
  1210. h = aprintf("%s:%s", name, value);
  1211. if(h)
  1212. stream->push_headers[stream->push_headers_used++] = h;
  1213. return 0;
  1214. }
  1215. if(stream->bodystarted) {
  1216. /* This is a trailer */
  1217. DEBUGF(LOG_CF(data_s, cf, "[h2sid=%d] trailer: %.*s: %.*s",
  1218. stream->id,
  1219. (int)namelen, name,
  1220. (int)valuelen, value));
  1221. result = Curl_dynhds_add(&stream->resp_trailers,
  1222. (const char *)name, namelen,
  1223. (const char *)value, valuelen);
  1224. if(result)
  1225. return NGHTTP2_ERR_CALLBACK_FAILURE;
  1226. return 0;
  1227. }
  1228. if(namelen == sizeof(HTTP_PSEUDO_STATUS) - 1 &&
  1229. memcmp(HTTP_PSEUDO_STATUS, name, namelen) == 0) {
  1230. /* nghttp2 guarantees :status is received first and only once. */
  1231. char buffer[32];
  1232. result = Curl_http_decode_status(&stream->status_code,
  1233. (const char *)value, valuelen);
  1234. if(result)
  1235. return NGHTTP2_ERR_CALLBACK_FAILURE;
  1236. msnprintf(buffer, sizeof(buffer), HTTP_PSEUDO_STATUS ":%u\r",
  1237. stream->status_code);
  1238. result = Curl_headers_push(data_s, buffer, CURLH_PSEUDO);
  1239. if(result)
  1240. return NGHTTP2_ERR_CALLBACK_FAILURE;
  1241. result = recvbuf_write_hds(cf, data_s, STRCONST("HTTP/2 "));
  1242. if(result)
  1243. return NGHTTP2_ERR_CALLBACK_FAILURE;
  1244. result = recvbuf_write_hds(cf, data_s, (const char *)value, valuelen);
  1245. if(result)
  1246. return NGHTTP2_ERR_CALLBACK_FAILURE;
  1247. /* the space character after the status code is mandatory */
  1248. result = recvbuf_write_hds(cf, data_s, STRCONST(" \r\n"));
  1249. if(result)
  1250. return NGHTTP2_ERR_CALLBACK_FAILURE;
  1251. /* if we receive data for another handle, wake that up */
  1252. if(CF_DATA_CURRENT(cf) != data_s)
  1253. Curl_expire(data_s, 0, EXPIRE_RUN_NOW);
  1254. DEBUGF(LOG_CF(data_s, cf, "[h2sid=%d] status: HTTP/2 %03d",
  1255. stream->id, stream->status_code));
  1256. return 0;
  1257. }
  1258. /* nghttp2 guarantees that namelen > 0, and :status was already
  1259. received, and this is not pseudo-header field . */
  1260. /* convert to an HTTP1-style header */
  1261. result = recvbuf_write_hds(cf, data_s, (const char *)name, namelen);
  1262. if(result)
  1263. return NGHTTP2_ERR_CALLBACK_FAILURE;
  1264. result = recvbuf_write_hds(cf, data_s, STRCONST(": "));
  1265. if(result)
  1266. return NGHTTP2_ERR_CALLBACK_FAILURE;
  1267. result = recvbuf_write_hds(cf, data_s, (const char *)value, valuelen);
  1268. if(result)
  1269. return NGHTTP2_ERR_CALLBACK_FAILURE;
  1270. result = recvbuf_write_hds(cf, data_s, STRCONST("\r\n"));
  1271. if(result)
  1272. return NGHTTP2_ERR_CALLBACK_FAILURE;
  1273. /* if we receive data for another handle, wake that up */
  1274. if(CF_DATA_CURRENT(cf) != data_s)
  1275. Curl_expire(data_s, 0, EXPIRE_RUN_NOW);
  1276. DEBUGF(LOG_CF(data_s, cf, "[h2sid=%d] header: %.*s: %.*s",
  1277. stream->id,
  1278. (int)namelen, name,
  1279. (int)valuelen, value));
  1280. return 0; /* 0 is successful */
  1281. }
  1282. static ssize_t req_body_read_callback(nghttp2_session *session,
  1283. int32_t stream_id,
  1284. uint8_t *buf, size_t length,
  1285. uint32_t *data_flags,
  1286. nghttp2_data_source *source,
  1287. void *userp)
  1288. {
  1289. struct Curl_cfilter *cf = userp;
  1290. struct Curl_easy *data_s;
  1291. struct stream_ctx *stream = NULL;
  1292. CURLcode result;
  1293. ssize_t nread;
  1294. (void)source;
  1295. (void)cf;
  1296. if(stream_id) {
  1297. /* get the stream from the hash based on Stream ID, stream ID zero is for
  1298. connection-oriented stuff */
  1299. data_s = nghttp2_session_get_stream_user_data(session, stream_id);
  1300. if(!data_s)
  1301. /* Receiving a Stream ID not in the hash should not happen, this is an
  1302. internal error more than anything else! */
  1303. return NGHTTP2_ERR_CALLBACK_FAILURE;
  1304. stream = H2_STREAM_CTX(data_s);
  1305. if(!stream)
  1306. return NGHTTP2_ERR_CALLBACK_FAILURE;
  1307. }
  1308. else
  1309. return NGHTTP2_ERR_INVALID_ARGUMENT;
  1310. nread = Curl_bufq_read(&stream->sendbuf, buf, length, &result);
  1311. if(nread < 0) {
  1312. if(result != CURLE_AGAIN)
  1313. return NGHTTP2_ERR_CALLBACK_FAILURE;
  1314. nread = 0;
  1315. }
  1316. if(nread > 0 && stream->upload_left != -1)
  1317. stream->upload_left -= nread;
  1318. DEBUGF(LOG_CF(data_s, cf, "[h2sid=%d] req_body_read(len=%zu) left=%"
  1319. CURL_FORMAT_CURL_OFF_T " -> %zd, %d",
  1320. stream_id, length, stream->upload_left, nread, result));
  1321. if(stream->upload_left == 0)
  1322. *data_flags = NGHTTP2_DATA_FLAG_EOF;
  1323. else if(nread == 0)
  1324. return NGHTTP2_ERR_DEFERRED;
  1325. return nread;
  1326. }
  1327. #if !defined(CURL_DISABLE_VERBOSE_STRINGS)
  1328. static int error_callback(nghttp2_session *session,
  1329. const char *msg,
  1330. size_t len,
  1331. void *userp)
  1332. {
  1333. (void)session;
  1334. (void)msg;
  1335. (void)len;
  1336. (void)userp;
  1337. return 0;
  1338. }
  1339. #endif
  1340. /*
  1341. * Append headers to ask for an HTTP1.1 to HTTP2 upgrade.
  1342. */
  1343. CURLcode Curl_http2_request_upgrade(struct dynbuf *req,
  1344. struct Curl_easy *data)
  1345. {
  1346. CURLcode result;
  1347. char *base64;
  1348. size_t blen;
  1349. struct SingleRequest *k = &data->req;
  1350. uint8_t binsettings[H2_BINSETTINGS_LEN];
  1351. size_t binlen; /* length of the binsettings data */
  1352. binlen = populate_binsettings(binsettings, data);
  1353. if(binlen <= 0) {
  1354. failf(data, "nghttp2 unexpectedly failed on pack_settings_payload");
  1355. Curl_dyn_free(req);
  1356. return CURLE_FAILED_INIT;
  1357. }
  1358. result = Curl_base64url_encode((const char *)binsettings, binlen,
  1359. &base64, &blen);
  1360. if(result) {
  1361. Curl_dyn_free(req);
  1362. return result;
  1363. }
  1364. result = Curl_dyn_addf(req,
  1365. "Connection: Upgrade, HTTP2-Settings\r\n"
  1366. "Upgrade: %s\r\n"
  1367. "HTTP2-Settings: %s\r\n",
  1368. NGHTTP2_CLEARTEXT_PROTO_VERSION_ID, base64);
  1369. free(base64);
  1370. k->upgr101 = UPGR101_H2;
  1371. return result;
  1372. }
  1373. static CURLcode http2_data_done_send(struct Curl_cfilter *cf,
  1374. struct Curl_easy *data)
  1375. {
  1376. struct cf_h2_ctx *ctx = cf->ctx;
  1377. CURLcode result = CURLE_OK;
  1378. struct stream_ctx *stream = H2_STREAM_CTX(data);
  1379. if(!ctx || !ctx->h2 || !stream)
  1380. goto out;
  1381. DEBUGF(LOG_CF(data, cf, "[h2sid=%d] data done send", stream->id));
  1382. if(!stream->send_closed) {
  1383. stream->send_closed = TRUE;
  1384. if(stream->upload_left) {
  1385. /* we now know that everything that is buffered is all there is. */
  1386. stream->upload_left = Curl_bufq_len(&stream->sendbuf);
  1387. /* resume sending here to trigger the callback to get called again so
  1388. that it can signal EOF to nghttp2 */
  1389. (void)nghttp2_session_resume_data(ctx->h2, stream->id);
  1390. drain_stream(cf, data, stream);
  1391. }
  1392. }
  1393. out:
  1394. return result;
  1395. }
  1396. static ssize_t http2_handle_stream_close(struct Curl_cfilter *cf,
  1397. struct Curl_easy *data,
  1398. struct stream_ctx *stream,
  1399. CURLcode *err)
  1400. {
  1401. ssize_t rv = 0;
  1402. if(stream->error == NGHTTP2_REFUSED_STREAM) {
  1403. DEBUGF(LOG_CF(data, cf, "[h2sid=%d] REFUSED_STREAM, try again on a new "
  1404. "connection", stream->id));
  1405. connclose(cf->conn, "REFUSED_STREAM"); /* don't use this anymore */
  1406. data->state.refused_stream = TRUE;
  1407. *err = CURLE_SEND_ERROR; /* trigger Curl_retry_request() later */
  1408. return -1;
  1409. }
  1410. else if(stream->error != NGHTTP2_NO_ERROR) {
  1411. failf(data, "HTTP/2 stream %u was not closed cleanly: %s (err %u)",
  1412. stream->id, nghttp2_http2_strerror(stream->error),
  1413. stream->error);
  1414. *err = CURLE_HTTP2_STREAM;
  1415. return -1;
  1416. }
  1417. else if(stream->reset) {
  1418. failf(data, "HTTP/2 stream %u was reset", stream->id);
  1419. *err = stream->bodystarted? CURLE_PARTIAL_FILE : CURLE_RECV_ERROR;
  1420. return -1;
  1421. }
  1422. if(!stream->bodystarted) {
  1423. failf(data, "HTTP/2 stream %u was closed cleanly, but before getting "
  1424. " all response header fields, treated as error",
  1425. stream->id);
  1426. *err = CURLE_HTTP2_STREAM;
  1427. return -1;
  1428. }
  1429. if(Curl_dynhds_count(&stream->resp_trailers)) {
  1430. struct dynhds_entry *e;
  1431. struct dynbuf dbuf;
  1432. size_t i;
  1433. *err = CURLE_OK;
  1434. Curl_dyn_init(&dbuf, DYN_TRAILERS);
  1435. for(i = 0; i < Curl_dynhds_count(&stream->resp_trailers); ++i) {
  1436. e = Curl_dynhds_getn(&stream->resp_trailers, i);
  1437. if(!e)
  1438. break;
  1439. Curl_dyn_reset(&dbuf);
  1440. *err = Curl_dyn_addf(&dbuf, "%.*s: %.*s\x0d\x0a",
  1441. (int)e->namelen, e->name,
  1442. (int)e->valuelen, e->value);
  1443. if(*err)
  1444. break;
  1445. Curl_debug(data, CURLINFO_HEADER_IN, Curl_dyn_ptr(&dbuf),
  1446. Curl_dyn_len(&dbuf));
  1447. *err = Curl_client_write(data, CLIENTWRITE_HEADER|CLIENTWRITE_TRAILER,
  1448. Curl_dyn_ptr(&dbuf), Curl_dyn_len(&dbuf));
  1449. if(*err)
  1450. break;
  1451. }
  1452. Curl_dyn_free(&dbuf);
  1453. if(*err)
  1454. goto out;
  1455. }
  1456. stream->close_handled = TRUE;
  1457. *err = CURLE_OK;
  1458. rv = 0;
  1459. out:
  1460. DEBUGF(LOG_CF(data, cf, "handle_stream_close -> %zd, %d", rv, *err));
  1461. return rv;
  1462. }
  1463. static int sweight_wanted(const struct Curl_easy *data)
  1464. {
  1465. /* 0 weight is not set by user and we take the nghttp2 default one */
  1466. return data->set.priority.weight?
  1467. data->set.priority.weight : NGHTTP2_DEFAULT_WEIGHT;
  1468. }
  1469. static int sweight_in_effect(const struct Curl_easy *data)
  1470. {
  1471. /* 0 weight is not set by user and we take the nghttp2 default one */
  1472. return data->state.priority.weight?
  1473. data->state.priority.weight : NGHTTP2_DEFAULT_WEIGHT;
  1474. }
  1475. /*
  1476. * h2_pri_spec() fills in the pri_spec struct, used by nghttp2 to send weight
  1477. * and dependency to the peer. It also stores the updated values in the state
  1478. * struct.
  1479. */
  1480. static void h2_pri_spec(struct Curl_easy *data,
  1481. nghttp2_priority_spec *pri_spec)
  1482. {
  1483. struct Curl_data_priority *prio = &data->set.priority;
  1484. struct stream_ctx *depstream = H2_STREAM_CTX(prio->parent);
  1485. int32_t depstream_id = depstream? depstream->id:0;
  1486. nghttp2_priority_spec_init(pri_spec, depstream_id,
  1487. sweight_wanted(data),
  1488. data->set.priority.exclusive);
  1489. data->state.priority = *prio;
  1490. }
  1491. /*
  1492. * Check if there's been an update in the priority /
  1493. * dependency settings and if so it submits a PRIORITY frame with the updated
  1494. * info.
  1495. * Flush any out data pending in the network buffer.
  1496. */
  1497. static CURLcode h2_progress_egress(struct Curl_cfilter *cf,
  1498. struct Curl_easy *data)
  1499. {
  1500. struct cf_h2_ctx *ctx = cf->ctx;
  1501. struct stream_ctx *stream = H2_STREAM_CTX(data);
  1502. int rv = 0;
  1503. if(stream && stream->id > 0 &&
  1504. ((sweight_wanted(data) != sweight_in_effect(data)) ||
  1505. (data->set.priority.exclusive != data->state.priority.exclusive) ||
  1506. (data->set.priority.parent != data->state.priority.parent)) ) {
  1507. /* send new weight and/or dependency */
  1508. nghttp2_priority_spec pri_spec;
  1509. h2_pri_spec(data, &pri_spec);
  1510. DEBUGF(LOG_CF(data, cf, "[h2sid=%d] Queuing PRIORITY",
  1511. stream->id));
  1512. DEBUGASSERT(stream->id != -1);
  1513. rv = nghttp2_submit_priority(ctx->h2, NGHTTP2_FLAG_NONE,
  1514. stream->id, &pri_spec);
  1515. if(rv)
  1516. goto out;
  1517. }
  1518. ctx->nw_out_blocked = 0;
  1519. while(!rv && !ctx->nw_out_blocked && nghttp2_session_want_write(ctx->h2))
  1520. rv = nghttp2_session_send(ctx->h2);
  1521. out:
  1522. if(nghttp2_is_fatal(rv)) {
  1523. DEBUGF(LOG_CF(data, cf, "nghttp2_session_send error (%s)%d",
  1524. nghttp2_strerror(rv), rv));
  1525. return CURLE_SEND_ERROR;
  1526. }
  1527. return nw_out_flush(cf, data);
  1528. }
  1529. static ssize_t stream_recv(struct Curl_cfilter *cf, struct Curl_easy *data,
  1530. char *buf, size_t len, CURLcode *err)
  1531. {
  1532. struct cf_h2_ctx *ctx = cf->ctx;
  1533. struct stream_ctx *stream = H2_STREAM_CTX(data);
  1534. ssize_t nread = -1;
  1535. *err = CURLE_AGAIN;
  1536. if(!Curl_bufq_is_empty(&stream->recvbuf)) {
  1537. nread = Curl_bufq_read(&stream->recvbuf,
  1538. (unsigned char *)buf, len, err);
  1539. DEBUGF(LOG_CF(data, cf, "recvbuf read(len=%zu) -> %zd, %d",
  1540. len, nread, *err));
  1541. if(nread < 0)
  1542. goto out;
  1543. DEBUGASSERT(nread > 0);
  1544. }
  1545. if(nread < 0) {
  1546. if(stream->closed) {
  1547. DEBUGF(LOG_CF(data, cf, "[h2sid=%d] returning CLOSE", stream->id));
  1548. nread = http2_handle_stream_close(cf, data, stream, err);
  1549. }
  1550. else if(stream->reset ||
  1551. (ctx->conn_closed && Curl_bufq_is_empty(&ctx->inbufq)) ||
  1552. (ctx->goaway && ctx->last_stream_id < stream->id)) {
  1553. DEBUGF(LOG_CF(data, cf, "[h2sid=%d] returning ERR", stream->id));
  1554. *err = stream->bodystarted? CURLE_PARTIAL_FILE : CURLE_RECV_ERROR;
  1555. nread = -1;
  1556. }
  1557. }
  1558. else if(nread == 0) {
  1559. *err = CURLE_AGAIN;
  1560. nread = -1;
  1561. }
  1562. out:
  1563. DEBUGF(LOG_CF(data, cf, "stream_recv(len=%zu) -> %zd, %d",
  1564. len, nread, *err));
  1565. return nread;
  1566. }
  1567. static CURLcode h2_progress_ingress(struct Curl_cfilter *cf,
  1568. struct Curl_easy *data)
  1569. {
  1570. struct cf_h2_ctx *ctx = cf->ctx;
  1571. struct stream_ctx *stream;
  1572. CURLcode result = CURLE_OK;
  1573. ssize_t nread;
  1574. /* Process network input buffer fist */
  1575. if(!Curl_bufq_is_empty(&ctx->inbufq)) {
  1576. DEBUGF(LOG_CF(data, cf, "Process %zu bytes in connection buffer",
  1577. Curl_bufq_len(&ctx->inbufq)));
  1578. if(h2_process_pending_input(cf, data, &result) < 0)
  1579. return result;
  1580. }
  1581. /* Receive data from the "lower" filters, e.g. network until
  1582. * it is time to stop due to connection close or us not processing
  1583. * all network input */
  1584. while(!ctx->conn_closed && Curl_bufq_is_empty(&ctx->inbufq)) {
  1585. stream = H2_STREAM_CTX(data);
  1586. if(stream && (stream->closed || Curl_bufq_is_full(&stream->recvbuf))) {
  1587. /* We would like to abort here and stop processing, so that
  1588. * the transfer loop can handle the data/close here. However,
  1589. * this may leave data in underlying buffers that will not
  1590. * be consumed. */
  1591. if(!cf->next || !cf->next->cft->has_data_pending(cf->next, data))
  1592. break;
  1593. }
  1594. nread = Curl_bufq_slurp(&ctx->inbufq, nw_in_reader, cf, &result);
  1595. /* DEBUGF(LOG_CF(data, cf, "read %zu bytes nw data -> %zd, %d",
  1596. Curl_bufq_len(&ctx->inbufq), nread, result)); */
  1597. if(nread < 0) {
  1598. if(result != CURLE_AGAIN) {
  1599. failf(data, "Failed receiving HTTP2 data: %d(%s)", result,
  1600. curl_easy_strerror(result));
  1601. return result;
  1602. }
  1603. break;
  1604. }
  1605. else if(nread == 0) {
  1606. ctx->conn_closed = TRUE;
  1607. break;
  1608. }
  1609. if(h2_process_pending_input(cf, data, &result))
  1610. return result;
  1611. }
  1612. if(ctx->conn_closed && Curl_bufq_is_empty(&ctx->inbufq)) {
  1613. connclose(cf->conn, "GOAWAY received");
  1614. }
  1615. return CURLE_OK;
  1616. }
  1617. static ssize_t cf_h2_recv(struct Curl_cfilter *cf, struct Curl_easy *data,
  1618. char *buf, size_t len, CURLcode *err)
  1619. {
  1620. struct cf_h2_ctx *ctx = cf->ctx;
  1621. struct stream_ctx *stream = H2_STREAM_CTX(data);
  1622. ssize_t nread = -1;
  1623. CURLcode result;
  1624. struct cf_call_data save;
  1625. DEBUGASSERT(stream);
  1626. CF_DATA_SAVE(save, cf, data);
  1627. nread = stream_recv(cf, data, buf, len, err);
  1628. if(nread < 0 && *err != CURLE_AGAIN)
  1629. goto out;
  1630. if(nread < 0) {
  1631. *err = h2_progress_ingress(cf, data);
  1632. if(*err)
  1633. goto out;
  1634. nread = stream_recv(cf, data, buf, len, err);
  1635. }
  1636. if(nread > 0) {
  1637. size_t data_consumed = (size_t)nread;
  1638. /* Now that we transferred this to the upper layer, we report
  1639. * the actual amount of DATA consumed to the H2 session, so
  1640. * that it adjusts stream flow control */
  1641. if(stream->resp_hds_len >= data_consumed) {
  1642. stream->resp_hds_len -= data_consumed; /* no DATA */
  1643. }
  1644. else {
  1645. if(stream->resp_hds_len) {
  1646. data_consumed -= stream->resp_hds_len;
  1647. stream->resp_hds_len = 0;
  1648. }
  1649. if(data_consumed) {
  1650. nghttp2_session_consume(ctx->h2, stream->id, data_consumed);
  1651. }
  1652. }
  1653. if(stream->closed) {
  1654. DEBUGF(LOG_CF(data, cf, "[h2sid=%d] closed stream, set drain",
  1655. stream->id));
  1656. drain_stream(cf, data, stream);
  1657. }
  1658. }
  1659. out:
  1660. result = h2_progress_egress(cf, data);
  1661. if(result && result != CURLE_AGAIN) {
  1662. *err = result;
  1663. nread = -1;
  1664. }
  1665. DEBUGF(LOG_CF(data, cf, "[h2sid=%d] cf_recv(len=%zu) -> %zd %d, "
  1666. "buffered=%zu, window=%d/%d, connection %d/%d",
  1667. stream->id, len, nread, *err,
  1668. Curl_bufq_len(&stream->recvbuf),
  1669. nghttp2_session_get_stream_effective_recv_data_length(
  1670. ctx->h2, stream->id),
  1671. nghttp2_session_get_stream_effective_local_window_size(
  1672. ctx->h2, stream->id),
  1673. nghttp2_session_get_local_window_size(ctx->h2),
  1674. HTTP2_HUGE_WINDOW_SIZE));
  1675. CF_DATA_RESTORE(cf, save);
  1676. return nread;
  1677. }
  1678. static ssize_t h2_submit(struct stream_ctx **pstream,
  1679. struct Curl_cfilter *cf, struct Curl_easy *data,
  1680. const void *buf, size_t len, CURLcode *err)
  1681. {
  1682. struct cf_h2_ctx *ctx = cf->ctx;
  1683. struct stream_ctx *stream = NULL;
  1684. struct h1_req_parser h1;
  1685. struct dynhds h2_headers;
  1686. nghttp2_nv *nva = NULL;
  1687. const void *body = NULL;
  1688. size_t nheader, bodylen, i;
  1689. nghttp2_data_provider data_prd;
  1690. int32_t stream_id;
  1691. nghttp2_priority_spec pri_spec;
  1692. ssize_t nwritten;
  1693. Curl_h1_req_parse_init(&h1, H1_PARSE_DEFAULT_MAX_LINE_LEN);
  1694. Curl_dynhds_init(&h2_headers, 0, DYN_HTTP_REQUEST);
  1695. *err = http2_data_setup(cf, data, &stream);
  1696. if(*err) {
  1697. nwritten = -1;
  1698. goto out;
  1699. }
  1700. nwritten = Curl_h1_req_parse_read(&h1, buf, len, NULL, 0, err);
  1701. if(nwritten < 0)
  1702. goto out;
  1703. DEBUGASSERT(h1.done);
  1704. DEBUGASSERT(h1.req);
  1705. *err = Curl_http_req_to_h2(&h2_headers, h1.req, data);
  1706. if(*err) {
  1707. nwritten = -1;
  1708. goto out;
  1709. }
  1710. nheader = Curl_dynhds_count(&h2_headers);
  1711. nva = malloc(sizeof(nghttp2_nv) * nheader);
  1712. if(!nva) {
  1713. *err = CURLE_OUT_OF_MEMORY;
  1714. nwritten = -1;
  1715. goto out;
  1716. }
  1717. for(i = 0; i < nheader; ++i) {
  1718. struct dynhds_entry *e = Curl_dynhds_getn(&h2_headers, i);
  1719. nva[i].name = (unsigned char *)e->name;
  1720. nva[i].namelen = e->namelen;
  1721. nva[i].value = (unsigned char *)e->value;
  1722. nva[i].valuelen = e->valuelen;
  1723. nva[i].flags = NGHTTP2_NV_FLAG_NONE;
  1724. }
  1725. #define MAX_ACC 60000 /* <64KB to account for some overhead */
  1726. {
  1727. size_t acc = 0;
  1728. for(i = 0; i < nheader; ++i) {
  1729. acc += nva[i].namelen + nva[i].valuelen;
  1730. infof(data, "h2 [%.*s: %.*s]",
  1731. (int)nva[i].namelen, nva[i].name,
  1732. (int)nva[i].valuelen, nva[i].value);
  1733. }
  1734. if(acc > MAX_ACC) {
  1735. infof(data, "http_request: Warning: The cumulative length of all "
  1736. "headers exceeds %d bytes and that could cause the "
  1737. "stream to be rejected.", MAX_ACC);
  1738. }
  1739. }
  1740. h2_pri_spec(data, &pri_spec);
  1741. DEBUGF(LOG_CF(data, cf, "send request allowed %d",
  1742. nghttp2_session_check_request_allowed(ctx->h2)));
  1743. switch(data->state.httpreq) {
  1744. case HTTPREQ_POST:
  1745. case HTTPREQ_POST_FORM:
  1746. case HTTPREQ_POST_MIME:
  1747. case HTTPREQ_PUT:
  1748. if(data->state.infilesize != -1)
  1749. stream->upload_left = data->state.infilesize;
  1750. else
  1751. /* data sending without specifying the data amount up front */
  1752. stream->upload_left = -1; /* unknown */
  1753. data_prd.read_callback = req_body_read_callback;
  1754. data_prd.source.ptr = NULL;
  1755. stream_id = nghttp2_submit_request(ctx->h2, &pri_spec, nva, nheader,
  1756. &data_prd, data);
  1757. break;
  1758. default:
  1759. stream->upload_left = 0; /* no request body */
  1760. stream_id = nghttp2_submit_request(ctx->h2, &pri_spec, nva, nheader,
  1761. NULL, data);
  1762. }
  1763. Curl_safefree(nva);
  1764. if(stream_id < 0) {
  1765. DEBUGF(LOG_CF(data, cf, "send: nghttp2_submit_request error (%s)%u",
  1766. nghttp2_strerror(stream_id), stream_id));
  1767. *err = CURLE_SEND_ERROR;
  1768. nwritten = -1;
  1769. goto out;
  1770. }
  1771. DEBUGF(LOG_CF(data, cf, "[h2sid=%d] cf_send(len=%zu) submit %s",
  1772. stream_id, len, data->state.url));
  1773. infof(data, "Using Stream ID: %u", stream_id);
  1774. stream->id = stream_id;
  1775. stream->local_window_size = H2_STREAM_WINDOW_SIZE;
  1776. if(data->set.max_recv_speed) {
  1777. /* We are asked to only receive `max_recv_speed` bytes per second.
  1778. * Let's limit our stream window size around that, otherwise the server
  1779. * will send in large bursts only. We make the window 50% larger to
  1780. * allow for data in flight and avoid stalling. */
  1781. curl_off_t n = (((data->set.max_recv_speed - 1) / H2_CHUNK_SIZE) + 1);
  1782. n += CURLMAX((n/2), 1);
  1783. if(n < (H2_STREAM_WINDOW_SIZE / H2_CHUNK_SIZE) &&
  1784. n < (UINT_MAX / H2_CHUNK_SIZE)) {
  1785. stream->local_window_size = (uint32_t)n * H2_CHUNK_SIZE;
  1786. }
  1787. }
  1788. body = (const char *)buf + nwritten;
  1789. bodylen = len - nwritten;
  1790. if(bodylen) {
  1791. /* We have request body to send in DATA frame */
  1792. ssize_t n = Curl_bufq_write(&stream->sendbuf, body, bodylen, err);
  1793. if(n < 0) {
  1794. *err = CURLE_SEND_ERROR;
  1795. nwritten = -1;
  1796. goto out;
  1797. }
  1798. nwritten += n;
  1799. }
  1800. out:
  1801. DEBUGF(LOG_CF(data, cf, "[h2sid=%d] submit -> %zd, %d",
  1802. stream? stream->id : -1, nwritten, *err));
  1803. *pstream = stream;
  1804. Curl_h1_req_parse_free(&h1);
  1805. Curl_dynhds_free(&h2_headers);
  1806. return nwritten;
  1807. }
  1808. static ssize_t cf_h2_send(struct Curl_cfilter *cf, struct Curl_easy *data,
  1809. const void *buf, size_t len, CURLcode *err)
  1810. {
  1811. struct cf_h2_ctx *ctx = cf->ctx;
  1812. struct stream_ctx *stream = H2_STREAM_CTX(data);
  1813. struct cf_call_data save;
  1814. int rv;
  1815. ssize_t nwritten;
  1816. CURLcode result;
  1817. int blocked = 0;
  1818. CF_DATA_SAVE(save, cf, data);
  1819. if(stream && stream->id != -1) {
  1820. if(stream->close_handled) {
  1821. infof(data, "stream %u closed", stream->id);
  1822. *err = CURLE_HTTP2_STREAM;
  1823. nwritten = -1;
  1824. goto out;
  1825. }
  1826. else if(stream->closed) {
  1827. nwritten = http2_handle_stream_close(cf, data, stream, err);
  1828. goto out;
  1829. }
  1830. else if(stream->upload_blocked_len) {
  1831. /* the data in `buf` has alread been submitted or added to the
  1832. * buffers, but have been EAGAINed on the last invocation. */
  1833. /* TODO: this assertion triggers in OSSFuzz runs and it is not
  1834. * clear why. Disable for now to let OSSFuzz continue its tests.
  1835. DEBUGASSERT(len >= stream->upload_blocked_len); */
  1836. if(len < stream->upload_blocked_len) {
  1837. /* Did we get called again with a smaller `len`? This should not
  1838. * happend. We are not prepared to handle that. */
  1839. failf(data, "HTTP/2 send again with decreased length");
  1840. *err = CURLE_HTTP2;
  1841. nwritten = -1;
  1842. goto out;
  1843. }
  1844. nwritten = (ssize_t)stream->upload_blocked_len;
  1845. stream->upload_blocked_len = 0;
  1846. }
  1847. else {
  1848. /* If stream_id != -1, we have dispatched request HEADERS and
  1849. * optionally request body, and now are going to send or sending
  1850. * more request body in DATA frame */
  1851. nwritten = Curl_bufq_write(&stream->sendbuf, buf, len, err);
  1852. if(nwritten < 0) {
  1853. if(*err != CURLE_AGAIN)
  1854. goto out;
  1855. nwritten = 0;
  1856. }
  1857. }
  1858. if(!Curl_bufq_is_empty(&stream->sendbuf)) {
  1859. /* req body data is buffered, resume the potentially suspended stream */
  1860. rv = nghttp2_session_resume_data(ctx->h2, stream->id);
  1861. if(nghttp2_is_fatal(rv)) {
  1862. *err = CURLE_SEND_ERROR;
  1863. nwritten = -1;
  1864. goto out;
  1865. }
  1866. }
  1867. }
  1868. else {
  1869. nwritten = h2_submit(&stream, cf, data, buf, len, err);
  1870. if(nwritten < 0) {
  1871. goto out;
  1872. }
  1873. DEBUGASSERT(stream);
  1874. }
  1875. /* Call the nghttp2 send loop and flush to write ALL buffered data,
  1876. * headers and/or request body completely out to the network */
  1877. result = h2_progress_egress(cf, data);
  1878. /* if the stream has been closed in egress handling (nghttp2 does that
  1879. * when it does not like the headers, for example */
  1880. if(stream && stream->closed) {
  1881. nwritten = http2_handle_stream_close(cf, data, stream, err);
  1882. goto out;
  1883. }
  1884. else if(result == CURLE_AGAIN) {
  1885. blocked = 1;
  1886. }
  1887. else if(result) {
  1888. *err = result;
  1889. nwritten = -1;
  1890. goto out;
  1891. }
  1892. else if(stream && !Curl_bufq_is_empty(&stream->sendbuf)) {
  1893. /* although we wrote everything that nghttp2 wants to send now,
  1894. * there is data left in our stream send buffer unwritten. This may
  1895. * be due to the stream's HTTP/2 flow window being exhausted. */
  1896. blocked = 1;
  1897. }
  1898. if(stream && blocked) {
  1899. /* Unable to send all data, due to connection blocked or H2 window
  1900. * exhaustion. Data is left in our stream buffer, or nghttp2's internal
  1901. * frame buffer or our network out buffer. */
  1902. size_t rwin = nghttp2_session_get_stream_remote_window_size(ctx->h2,
  1903. stream->id);
  1904. if(rwin == 0) {
  1905. /* H2 flow window exhaustion. We need to HOLD upload until we get
  1906. * a WINDOW_UPDATE from the server. */
  1907. data->req.keepon |= KEEP_SEND_HOLD;
  1908. DEBUGF(LOG_CF(data, cf, "[h2sid=%d] holding send as remote flow "
  1909. "window is exhausted", stream->id));
  1910. }
  1911. /* Whatever the cause, we need to return CURL_EAGAIN for this call.
  1912. * We have unwritten state that needs us being invoked again and EAGAIN
  1913. * is the only way to ensure that. */
  1914. stream->upload_blocked_len = nwritten;
  1915. DEBUGF(LOG_CF(data, cf, "[h2sid=%d] cf_send(len=%zu) BLOCK: win %u/%zu "
  1916. "blocked_len=%zu",
  1917. stream->id, len,
  1918. nghttp2_session_get_remote_window_size(ctx->h2), rwin,
  1919. nwritten));
  1920. *err = CURLE_AGAIN;
  1921. nwritten = -1;
  1922. goto out;
  1923. }
  1924. else if(should_close_session(ctx)) {
  1925. /* nghttp2 thinks this session is done. If the stream has not been
  1926. * closed, this is an error state for out transfer */
  1927. if(stream->closed) {
  1928. nwritten = http2_handle_stream_close(cf, data, stream, err);
  1929. }
  1930. else {
  1931. DEBUGF(LOG_CF(data, cf, "send: nothing to do in this session"));
  1932. *err = CURLE_HTTP2;
  1933. nwritten = -1;
  1934. }
  1935. }
  1936. out:
  1937. if(stream) {
  1938. DEBUGF(LOG_CF(data, cf, "[h2sid=%d] cf_send(len=%zu) -> %zd, %d, "
  1939. "upload_left=%" CURL_FORMAT_CURL_OFF_T ", "
  1940. "h2 windows %d-%d (stream-conn), "
  1941. "buffers %zu-%zu (stream-conn)",
  1942. stream->id, len, nwritten, *err,
  1943. (ssize_t)stream->upload_left,
  1944. nghttp2_session_get_stream_remote_window_size(
  1945. ctx->h2, stream->id),
  1946. nghttp2_session_get_remote_window_size(ctx->h2),
  1947. Curl_bufq_len(&stream->sendbuf),
  1948. Curl_bufq_len(&ctx->outbufq)));
  1949. }
  1950. else {
  1951. DEBUGF(LOG_CF(data, cf, "cf_send(len=%zu) -> %zd, %d, "
  1952. "connection-window=%d, nw_send_buffer(%zu)",
  1953. len, nwritten, *err,
  1954. nghttp2_session_get_remote_window_size(ctx->h2),
  1955. Curl_bufq_len(&ctx->outbufq)));
  1956. }
  1957. CF_DATA_RESTORE(cf, save);
  1958. return nwritten;
  1959. }
  1960. static int cf_h2_get_select_socks(struct Curl_cfilter *cf,
  1961. struct Curl_easy *data,
  1962. curl_socket_t *sock)
  1963. {
  1964. struct cf_h2_ctx *ctx = cf->ctx;
  1965. struct SingleRequest *k = &data->req;
  1966. struct stream_ctx *stream = H2_STREAM_CTX(data);
  1967. int bitmap = GETSOCK_BLANK;
  1968. struct cf_call_data save;
  1969. CF_DATA_SAVE(save, cf, data);
  1970. sock[0] = Curl_conn_cf_get_socket(cf, data);
  1971. if(!(k->keepon & (KEEP_RECV_PAUSE|KEEP_RECV_HOLD)))
  1972. /* Unless paused - in an HTTP/2 connection we can basically always get a
  1973. frame so we should always be ready for one */
  1974. bitmap |= GETSOCK_READSOCK(0);
  1975. /* we're (still uploading OR the HTTP/2 layer wants to send data) AND
  1976. there's a window to send data in */
  1977. if((((k->keepon & KEEP_SENDBITS) == KEEP_SEND) ||
  1978. nghttp2_session_want_write(ctx->h2)) &&
  1979. (nghttp2_session_get_remote_window_size(ctx->h2) &&
  1980. nghttp2_session_get_stream_remote_window_size(ctx->h2,
  1981. stream->id)))
  1982. bitmap |= GETSOCK_WRITESOCK(0);
  1983. CF_DATA_RESTORE(cf, save);
  1984. return bitmap;
  1985. }
  1986. static CURLcode cf_h2_connect(struct Curl_cfilter *cf,
  1987. struct Curl_easy *data,
  1988. bool blocking, bool *done)
  1989. {
  1990. struct cf_h2_ctx *ctx = cf->ctx;
  1991. CURLcode result = CURLE_OK;
  1992. struct cf_call_data save;
  1993. if(cf->connected) {
  1994. *done = TRUE;
  1995. return CURLE_OK;
  1996. }
  1997. /* Connect the lower filters first */
  1998. if(!cf->next->connected) {
  1999. result = Curl_conn_cf_connect(cf->next, data, blocking, done);
  2000. if(result || !*done)
  2001. return result;
  2002. }
  2003. *done = FALSE;
  2004. CF_DATA_SAVE(save, cf, data);
  2005. if(!ctx->h2) {
  2006. result = cf_h2_ctx_init(cf, data, FALSE);
  2007. if(result)
  2008. goto out;
  2009. }
  2010. result = h2_progress_ingress(cf, data);
  2011. if(result)
  2012. goto out;
  2013. result = h2_progress_egress(cf, data);
  2014. if(result)
  2015. goto out;
  2016. *done = TRUE;
  2017. cf->connected = TRUE;
  2018. result = CURLE_OK;
  2019. out:
  2020. CF_DATA_RESTORE(cf, save);
  2021. return result;
  2022. }
  2023. static void cf_h2_close(struct Curl_cfilter *cf, struct Curl_easy *data)
  2024. {
  2025. struct cf_h2_ctx *ctx = cf->ctx;
  2026. if(ctx) {
  2027. struct cf_call_data save;
  2028. CF_DATA_SAVE(save, cf, data);
  2029. cf_h2_ctx_clear(ctx);
  2030. CF_DATA_RESTORE(cf, save);
  2031. }
  2032. }
  2033. static void cf_h2_destroy(struct Curl_cfilter *cf, struct Curl_easy *data)
  2034. {
  2035. struct cf_h2_ctx *ctx = cf->ctx;
  2036. (void)data;
  2037. if(ctx) {
  2038. cf_h2_ctx_free(ctx);
  2039. cf->ctx = NULL;
  2040. }
  2041. }
  2042. static CURLcode http2_data_pause(struct Curl_cfilter *cf,
  2043. struct Curl_easy *data,
  2044. bool pause)
  2045. {
  2046. #ifdef NGHTTP2_HAS_SET_LOCAL_WINDOW_SIZE
  2047. struct cf_h2_ctx *ctx = cf->ctx;
  2048. struct stream_ctx *stream = H2_STREAM_CTX(data);
  2049. DEBUGASSERT(data);
  2050. if(ctx && ctx->h2 && stream) {
  2051. uint32_t window = pause? 0 : stream->local_window_size;
  2052. int rv = nghttp2_session_set_local_window_size(ctx->h2,
  2053. NGHTTP2_FLAG_NONE,
  2054. stream->id,
  2055. window);
  2056. if(rv) {
  2057. failf(data, "nghttp2_session_set_local_window_size() failed: %s(%d)",
  2058. nghttp2_strerror(rv), rv);
  2059. return CURLE_HTTP2;
  2060. }
  2061. if(!pause)
  2062. drain_stream(cf, data, stream);
  2063. /* attempt to send the window update */
  2064. (void)h2_progress_egress(cf, data);
  2065. if(!pause) {
  2066. /* Unpausing a h2 transfer, requires it to be run again. The server
  2067. * may send new DATA on us increasing the flow window, and it may
  2068. * not. We may have already buffered and exhausted the new window
  2069. * by operating on things in flight during the handling of other
  2070. * transfers. */
  2071. drain_stream(cf, data, stream);
  2072. Curl_expire(data, 0, EXPIRE_RUN_NOW);
  2073. }
  2074. DEBUGF(infof(data, "Set HTTP/2 window size to %u for stream %u",
  2075. window, stream->id));
  2076. #ifdef DEBUGBUILD
  2077. {
  2078. /* read out the stream local window again */
  2079. uint32_t window2 =
  2080. nghttp2_session_get_stream_local_window_size(ctx->h2,
  2081. stream->id);
  2082. DEBUGF(infof(data, "HTTP/2 window size is now %u for stream %u",
  2083. window2, stream->id));
  2084. }
  2085. #endif
  2086. }
  2087. #endif
  2088. return CURLE_OK;
  2089. }
  2090. static CURLcode cf_h2_cntrl(struct Curl_cfilter *cf,
  2091. struct Curl_easy *data,
  2092. int event, int arg1, void *arg2)
  2093. {
  2094. CURLcode result = CURLE_OK;
  2095. struct cf_call_data save;
  2096. (void)arg2;
  2097. CF_DATA_SAVE(save, cf, data);
  2098. switch(event) {
  2099. case CF_CTRL_DATA_SETUP:
  2100. break;
  2101. case CF_CTRL_DATA_PAUSE:
  2102. result = http2_data_pause(cf, data, (arg1 != 0));
  2103. break;
  2104. case CF_CTRL_DATA_DONE_SEND: {
  2105. result = http2_data_done_send(cf, data);
  2106. break;
  2107. }
  2108. case CF_CTRL_DATA_DONE: {
  2109. http2_data_done(cf, data, arg1 != 0);
  2110. break;
  2111. }
  2112. default:
  2113. break;
  2114. }
  2115. CF_DATA_RESTORE(cf, save);
  2116. return result;
  2117. }
  2118. static bool cf_h2_data_pending(struct Curl_cfilter *cf,
  2119. const struct Curl_easy *data)
  2120. {
  2121. struct cf_h2_ctx *ctx = cf->ctx;
  2122. struct stream_ctx *stream = H2_STREAM_CTX(data);
  2123. if(ctx && (!Curl_bufq_is_empty(&ctx->inbufq)
  2124. || (stream && !Curl_bufq_is_empty(&stream->sendbuf))
  2125. || (stream && !Curl_bufq_is_empty(&stream->recvbuf))))
  2126. return TRUE;
  2127. return cf->next? cf->next->cft->has_data_pending(cf->next, data) : FALSE;
  2128. }
  2129. static bool cf_h2_is_alive(struct Curl_cfilter *cf,
  2130. struct Curl_easy *data,
  2131. bool *input_pending)
  2132. {
  2133. struct cf_h2_ctx *ctx = cf->ctx;
  2134. CURLcode result;
  2135. struct cf_call_data save;
  2136. CF_DATA_SAVE(save, cf, data);
  2137. result = (ctx && ctx->h2 && http2_connisalive(cf, data, input_pending));
  2138. DEBUGF(LOG_CF(data, cf, "conn alive -> %d, input_pending=%d",
  2139. result, *input_pending));
  2140. CF_DATA_RESTORE(cf, save);
  2141. return result;
  2142. }
  2143. static CURLcode cf_h2_keep_alive(struct Curl_cfilter *cf,
  2144. struct Curl_easy *data)
  2145. {
  2146. CURLcode result;
  2147. struct cf_call_data save;
  2148. CF_DATA_SAVE(save, cf, data);
  2149. result = http2_send_ping(cf, data);
  2150. CF_DATA_RESTORE(cf, save);
  2151. return result;
  2152. }
  2153. static CURLcode cf_h2_query(struct Curl_cfilter *cf,
  2154. struct Curl_easy *data,
  2155. int query, int *pres1, void *pres2)
  2156. {
  2157. struct cf_h2_ctx *ctx = cf->ctx;
  2158. struct cf_call_data save;
  2159. size_t effective_max;
  2160. switch(query) {
  2161. case CF_QUERY_MAX_CONCURRENT:
  2162. DEBUGASSERT(pres1);
  2163. CF_DATA_SAVE(save, cf, data);
  2164. if(nghttp2_session_check_request_allowed(ctx->h2) == 0) {
  2165. /* the limit is what we have in use right now */
  2166. effective_max = CONN_INUSE(cf->conn);
  2167. }
  2168. else {
  2169. effective_max = ctx->max_concurrent_streams;
  2170. }
  2171. *pres1 = (effective_max > INT_MAX)? INT_MAX : (int)effective_max;
  2172. CF_DATA_RESTORE(cf, save);
  2173. return CURLE_OK;
  2174. default:
  2175. break;
  2176. }
  2177. return cf->next?
  2178. cf->next->cft->query(cf->next, data, query, pres1, pres2) :
  2179. CURLE_UNKNOWN_OPTION;
  2180. }
  2181. struct Curl_cftype Curl_cft_nghttp2 = {
  2182. "HTTP/2",
  2183. CF_TYPE_MULTIPLEX,
  2184. CURL_LOG_DEFAULT,
  2185. cf_h2_destroy,
  2186. cf_h2_connect,
  2187. cf_h2_close,
  2188. Curl_cf_def_get_host,
  2189. cf_h2_get_select_socks,
  2190. cf_h2_data_pending,
  2191. cf_h2_send,
  2192. cf_h2_recv,
  2193. cf_h2_cntrl,
  2194. cf_h2_is_alive,
  2195. cf_h2_keep_alive,
  2196. cf_h2_query,
  2197. };
  2198. static CURLcode http2_cfilter_add(struct Curl_cfilter **pcf,
  2199. struct Curl_easy *data,
  2200. struct connectdata *conn,
  2201. int sockindex)
  2202. {
  2203. struct Curl_cfilter *cf = NULL;
  2204. struct cf_h2_ctx *ctx;
  2205. CURLcode result = CURLE_OUT_OF_MEMORY;
  2206. DEBUGASSERT(data->conn);
  2207. ctx = calloc(sizeof(*ctx), 1);
  2208. if(!ctx)
  2209. goto out;
  2210. result = Curl_cf_create(&cf, &Curl_cft_nghttp2, ctx);
  2211. if(result)
  2212. goto out;
  2213. Curl_conn_cf_add(data, conn, sockindex, cf);
  2214. result = CURLE_OK;
  2215. out:
  2216. if(result)
  2217. cf_h2_ctx_free(ctx);
  2218. *pcf = result? NULL : cf;
  2219. return result;
  2220. }
  2221. static CURLcode http2_cfilter_insert_after(struct Curl_cfilter *cf,
  2222. struct Curl_easy *data)
  2223. {
  2224. struct Curl_cfilter *cf_h2 = NULL;
  2225. struct cf_h2_ctx *ctx;
  2226. CURLcode result = CURLE_OUT_OF_MEMORY;
  2227. (void)data;
  2228. ctx = calloc(sizeof(*ctx), 1);
  2229. if(!ctx)
  2230. goto out;
  2231. result = Curl_cf_create(&cf_h2, &Curl_cft_nghttp2, ctx);
  2232. if(result)
  2233. goto out;
  2234. Curl_conn_cf_insert_after(cf, cf_h2);
  2235. result = CURLE_OK;
  2236. out:
  2237. if(result)
  2238. cf_h2_ctx_free(ctx);
  2239. return result;
  2240. }
  2241. static bool Curl_cf_is_http2(struct Curl_cfilter *cf,
  2242. const struct Curl_easy *data)
  2243. {
  2244. (void)data;
  2245. for(; cf; cf = cf->next) {
  2246. if(cf->cft == &Curl_cft_nghttp2)
  2247. return TRUE;
  2248. if(cf->cft->flags & CF_TYPE_IP_CONNECT)
  2249. return FALSE;
  2250. }
  2251. return FALSE;
  2252. }
  2253. bool Curl_conn_is_http2(const struct Curl_easy *data,
  2254. const struct connectdata *conn,
  2255. int sockindex)
  2256. {
  2257. return conn? Curl_cf_is_http2(conn->cfilter[sockindex], data) : FALSE;
  2258. }
  2259. bool Curl_http2_may_switch(struct Curl_easy *data,
  2260. struct connectdata *conn,
  2261. int sockindex)
  2262. {
  2263. (void)sockindex;
  2264. if(!Curl_conn_is_http2(data, conn, sockindex) &&
  2265. data->state.httpwant == CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE) {
  2266. #ifndef CURL_DISABLE_PROXY
  2267. if(conn->bits.httpproxy && !conn->bits.tunnel_proxy) {
  2268. /* We don't support HTTP/2 proxies yet. Also it's debatable
  2269. whether or not this setting should apply to HTTP/2 proxies. */
  2270. infof(data, "Ignoring HTTP/2 prior knowledge due to proxy");
  2271. return FALSE;
  2272. }
  2273. #endif
  2274. return TRUE;
  2275. }
  2276. return FALSE;
  2277. }
  2278. CURLcode Curl_http2_switch(struct Curl_easy *data,
  2279. struct connectdata *conn, int sockindex)
  2280. {
  2281. struct Curl_cfilter *cf;
  2282. CURLcode result;
  2283. DEBUGASSERT(!Curl_conn_is_http2(data, conn, sockindex));
  2284. DEBUGF(infof(data, "switching to HTTP/2"));
  2285. result = http2_cfilter_add(&cf, data, conn, sockindex);
  2286. if(result)
  2287. return result;
  2288. result = cf_h2_ctx_init(cf, data, FALSE);
  2289. if(result)
  2290. return result;
  2291. conn->httpversion = 20; /* we know we're on HTTP/2 now */
  2292. conn->bits.multiplex = TRUE; /* at least potentially multiplexed */
  2293. conn->bundle->multiuse = BUNDLE_MULTIPLEX;
  2294. Curl_multi_connchanged(data->multi);
  2295. if(cf->next) {
  2296. bool done;
  2297. return Curl_conn_cf_connect(cf, data, FALSE, &done);
  2298. }
  2299. return CURLE_OK;
  2300. }
  2301. CURLcode Curl_http2_switch_at(struct Curl_cfilter *cf, struct Curl_easy *data)
  2302. {
  2303. struct Curl_cfilter *cf_h2;
  2304. CURLcode result;
  2305. DEBUGASSERT(!Curl_cf_is_http2(cf, data));
  2306. result = http2_cfilter_insert_after(cf, data);
  2307. if(result)
  2308. return result;
  2309. cf_h2 = cf->next;
  2310. result = cf_h2_ctx_init(cf_h2, data, FALSE);
  2311. if(result)
  2312. return result;
  2313. cf->conn->httpversion = 20; /* we know we're on HTTP/2 now */
  2314. cf->conn->bits.multiplex = TRUE; /* at least potentially multiplexed */
  2315. cf->conn->bundle->multiuse = BUNDLE_MULTIPLEX;
  2316. Curl_multi_connchanged(data->multi);
  2317. if(cf_h2->next) {
  2318. bool done;
  2319. return Curl_conn_cf_connect(cf_h2, data, FALSE, &done);
  2320. }
  2321. return CURLE_OK;
  2322. }
  2323. CURLcode Curl_http2_upgrade(struct Curl_easy *data,
  2324. struct connectdata *conn, int sockindex,
  2325. const char *mem, size_t nread)
  2326. {
  2327. struct Curl_cfilter *cf;
  2328. struct cf_h2_ctx *ctx;
  2329. CURLcode result;
  2330. DEBUGASSERT(!Curl_conn_is_http2(data, conn, sockindex));
  2331. DEBUGF(infof(data, "upgrading to HTTP/2"));
  2332. DEBUGASSERT(data->req.upgr101 == UPGR101_RECEIVED);
  2333. result = http2_cfilter_add(&cf, data, conn, sockindex);
  2334. if(result)
  2335. return result;
  2336. DEBUGASSERT(cf->cft == &Curl_cft_nghttp2);
  2337. ctx = cf->ctx;
  2338. result = cf_h2_ctx_init(cf, data, TRUE);
  2339. if(result)
  2340. return result;
  2341. if(nread > 0) {
  2342. /* Remaining data from the protocol switch reply is already using
  2343. * the switched protocol, ie. HTTP/2. We add that to the network
  2344. * inbufq. */
  2345. ssize_t copied;
  2346. copied = Curl_bufq_write(&ctx->inbufq,
  2347. (const unsigned char *)mem, nread, &result);
  2348. if(copied < 0) {
  2349. failf(data, "error on copying HTTP Upgrade response: %d", result);
  2350. return CURLE_RECV_ERROR;
  2351. }
  2352. if((size_t)copied < nread) {
  2353. failf(data, "connection buffer size could not take all data "
  2354. "from HTTP Upgrade response header: copied=%zd, datalen=%zu",
  2355. copied, nread);
  2356. return CURLE_HTTP2;
  2357. }
  2358. infof(data, "Copied HTTP/2 data in stream buffer to connection buffer"
  2359. " after upgrade: len=%zu", nread);
  2360. }
  2361. conn->httpversion = 20; /* we know we're on HTTP/2 now */
  2362. conn->bits.multiplex = TRUE; /* at least potentially multiplexed */
  2363. conn->bundle->multiuse = BUNDLE_MULTIPLEX;
  2364. Curl_multi_connchanged(data->multi);
  2365. if(cf->next) {
  2366. bool done;
  2367. return Curl_conn_cf_connect(cf, data, FALSE, &done);
  2368. }
  2369. return CURLE_OK;
  2370. }
  2371. /* Only call this function for a transfer that already got an HTTP/2
  2372. CURLE_HTTP2_STREAM error! */
  2373. bool Curl_h2_http_1_1_error(struct Curl_easy *data)
  2374. {
  2375. struct stream_ctx *stream = H2_STREAM_CTX(data);
  2376. return (stream && stream->error == NGHTTP2_HTTP_1_1_REQUIRED);
  2377. }
  2378. #else /* !USE_NGHTTP2 */
  2379. /* Satisfy external references even if http2 is not compiled in. */
  2380. #include <curl/curl.h>
  2381. char *curl_pushheader_bynum(struct curl_pushheaders *h, size_t num)
  2382. {
  2383. (void) h;
  2384. (void) num;
  2385. return NULL;
  2386. }
  2387. char *curl_pushheader_byname(struct curl_pushheaders *h, const char *header)
  2388. {
  2389. (void) h;
  2390. (void) header;
  2391. return NULL;
  2392. }
  2393. #endif /* USE_NGHTTP2 */