curl_ngtcp2.c 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752
  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. #if defined(USE_NGTCP2) && defined(USE_NGHTTP3)
  26. #include <ngtcp2/ngtcp2.h>
  27. #include <nghttp3/nghttp3.h>
  28. #ifdef USE_OPENSSL
  29. #include <openssl/err.h>
  30. #ifdef OPENSSL_IS_BORINGSSL
  31. #include <ngtcp2/ngtcp2_crypto_boringssl.h>
  32. #else
  33. #include <ngtcp2/ngtcp2_crypto_quictls.h>
  34. #endif
  35. #include "vtls/openssl.h"
  36. #elif defined(USE_GNUTLS)
  37. #include <ngtcp2/ngtcp2_crypto_gnutls.h>
  38. #include "vtls/gtls.h"
  39. #elif defined(USE_WOLFSSL)
  40. #include <ngtcp2/ngtcp2_crypto_wolfssl.h>
  41. #include "vtls/wolfssl.h"
  42. #endif
  43. #include "urldata.h"
  44. #include "sendf.h"
  45. #include "strdup.h"
  46. #include "rand.h"
  47. #include "multiif.h"
  48. #include "strcase.h"
  49. #include "cfilters.h"
  50. #include "cf-socket.h"
  51. #include "connect.h"
  52. #include "progress.h"
  53. #include "strerror.h"
  54. #include "dynbuf.h"
  55. #include "http1.h"
  56. #include "select.h"
  57. #include "inet_pton.h"
  58. #include "vquic.h"
  59. #include "vquic_int.h"
  60. #include "vtls/keylog.h"
  61. #include "vtls/vtls.h"
  62. #include "curl_ngtcp2.h"
  63. #include "warnless.h"
  64. /* The last 3 #include files should be in this order */
  65. #include "curl_printf.h"
  66. #include "curl_memory.h"
  67. #include "memdebug.h"
  68. #define H3_ALPN_H3_29 "\x5h3-29"
  69. #define H3_ALPN_H3 "\x2h3"
  70. #define QUIC_MAX_STREAMS (256*1024)
  71. #define QUIC_MAX_DATA (1*1024*1024)
  72. #define QUIC_IDLE_TIMEOUT (60*NGTCP2_SECONDS)
  73. #define QUIC_HANDSHAKE_TIMEOUT (10*NGTCP2_SECONDS)
  74. /* A stream window is the maximum amount we need to buffer for
  75. * each active transfer. We use HTTP/3 flow control and only ACK
  76. * when we take things out of the buffer.
  77. * Chunk size is large enough to take a full DATA frame */
  78. #define H3_STREAM_WINDOW_SIZE (128 * 1024)
  79. #define H3_STREAM_CHUNK_SIZE (16 * 1024)
  80. /* The pool keeps spares around and half of a full stream windows
  81. * seems good. More does not seem to improve performance.
  82. * The benefit of the pool is that stream buffer to not keep
  83. * spares. So memory consumption goes down when streams run empty,
  84. * have a large upload done, etc. */
  85. #define H3_STREAM_POOL_SPARES \
  86. (H3_STREAM_WINDOW_SIZE / H3_STREAM_CHUNK_SIZE ) / 2
  87. /* Receive and Send max number of chunks just follows from the
  88. * chunk size and window size */
  89. #define H3_STREAM_RECV_CHUNKS \
  90. (H3_STREAM_WINDOW_SIZE / H3_STREAM_CHUNK_SIZE)
  91. #define H3_STREAM_SEND_CHUNKS \
  92. (H3_STREAM_WINDOW_SIZE / H3_STREAM_CHUNK_SIZE)
  93. #ifdef USE_OPENSSL
  94. #define QUIC_CIPHERS \
  95. "TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_" \
  96. "POLY1305_SHA256:TLS_AES_128_CCM_SHA256"
  97. #define QUIC_GROUPS "P-256:X25519:P-384:P-521"
  98. #elif defined(USE_GNUTLS)
  99. #define QUIC_PRIORITY \
  100. "NORMAL:-VERS-ALL:+VERS-TLS1.3:-CIPHER-ALL:+AES-128-GCM:+AES-256-GCM:" \
  101. "+CHACHA20-POLY1305:+AES-128-CCM:-GROUP-ALL:+GROUP-SECP256R1:" \
  102. "+GROUP-X25519:+GROUP-SECP384R1:+GROUP-SECP521R1:" \
  103. "%DISABLE_TLS13_COMPAT_MODE"
  104. #elif defined(USE_WOLFSSL)
  105. #define QUIC_CIPHERS \
  106. "TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_" \
  107. "POLY1305_SHA256:TLS_AES_128_CCM_SHA256"
  108. #define QUIC_GROUPS "P-256:P-384:P-521"
  109. #endif
  110. /*
  111. * Store ngtcp2 version info in this buffer.
  112. */
  113. void Curl_ngtcp2_ver(char *p, size_t len)
  114. {
  115. const ngtcp2_info *ng2 = ngtcp2_version(0);
  116. const nghttp3_info *ht3 = nghttp3_version(0);
  117. (void)msnprintf(p, len, "ngtcp2/%s nghttp3/%s",
  118. ng2->version_str, ht3->version_str);
  119. }
  120. struct cf_ngtcp2_ctx {
  121. struct cf_quic_ctx q;
  122. ngtcp2_path connected_path;
  123. ngtcp2_conn *qconn;
  124. ngtcp2_cid dcid;
  125. ngtcp2_cid scid;
  126. uint32_t version;
  127. ngtcp2_settings settings;
  128. ngtcp2_transport_params transport_params;
  129. ngtcp2_ccerr last_error;
  130. ngtcp2_crypto_conn_ref conn_ref;
  131. #ifdef USE_OPENSSL
  132. SSL_CTX *sslctx;
  133. SSL *ssl;
  134. #elif defined(USE_GNUTLS)
  135. struct gtls_instance *gtls;
  136. #elif defined(USE_WOLFSSL)
  137. WOLFSSL_CTX *sslctx;
  138. WOLFSSL *ssl;
  139. #endif
  140. struct cf_call_data call_data;
  141. nghttp3_conn *h3conn;
  142. nghttp3_settings h3settings;
  143. struct curltime started_at; /* time the current attempt started */
  144. struct curltime handshake_at; /* time connect handshake finished */
  145. struct curltime first_byte_at; /* when first byte was recvd */
  146. struct curltime reconnect_at; /* time the next attempt should start */
  147. struct bufc_pool stream_bufcp; /* chunk pool for streams */
  148. size_t max_stream_window; /* max flow window for one stream */
  149. int qlogfd;
  150. BIT(got_first_byte); /* if first byte was received */
  151. #ifdef USE_OPENSSL
  152. BIT(x509_store_setup); /* if x509 store has been set up */
  153. #endif
  154. };
  155. /* How to access `call_data` from a cf_ngtcp2 filter */
  156. #undef CF_CTX_CALL_DATA
  157. #define CF_CTX_CALL_DATA(cf) \
  158. ((struct cf_ngtcp2_ctx *)(cf)->ctx)->call_data
  159. /**
  160. * All about the H3 internals of a stream
  161. */
  162. struct h3_stream_ctx {
  163. int64_t id; /* HTTP/3 protocol identifier */
  164. struct bufq sendbuf; /* h3 request body */
  165. struct bufq recvbuf; /* h3 response body */
  166. struct h1_req_parser h1; /* h1 request parsing */
  167. size_t sendbuf_len_in_flight; /* sendbuf amount "in flight" */
  168. size_t upload_blocked_len; /* the amount written last and EGAINed */
  169. size_t recv_buf_nonflow; /* buffered bytes, not counting for flow control */
  170. uint64_t error3; /* HTTP/3 stream error code */
  171. curl_off_t upload_left; /* number of request bytes left to upload */
  172. int status_code; /* HTTP status code */
  173. bool resp_hds_complete; /* we have a complete, final response */
  174. bool closed; /* TRUE on stream close */
  175. bool reset; /* TRUE on stream reset */
  176. bool send_closed; /* stream is local closed */
  177. };
  178. #define H3_STREAM_CTX(d) ((struct h3_stream_ctx *)(((d) && (d)->req.p.http)? \
  179. ((struct HTTP *)(d)->req.p.http)->h3_ctx \
  180. : NULL))
  181. #define H3_STREAM_LCTX(d) ((struct HTTP *)(d)->req.p.http)->h3_ctx
  182. #define H3_STREAM_ID(d) (H3_STREAM_CTX(d)? \
  183. H3_STREAM_CTX(d)->id : -2)
  184. static CURLcode h3_data_setup(struct Curl_cfilter *cf,
  185. struct Curl_easy *data)
  186. {
  187. struct cf_ngtcp2_ctx *ctx = cf->ctx;
  188. struct h3_stream_ctx *stream = H3_STREAM_CTX(data);
  189. if(!data || !data->req.p.http) {
  190. failf(data, "initialization failure, transfer not http initialized");
  191. return CURLE_FAILED_INIT;
  192. }
  193. if(stream)
  194. return CURLE_OK;
  195. stream = calloc(1, sizeof(*stream));
  196. if(!stream)
  197. return CURLE_OUT_OF_MEMORY;
  198. stream->id = -1;
  199. /* on send, we control how much we put into the buffer */
  200. Curl_bufq_initp(&stream->sendbuf, &ctx->stream_bufcp,
  201. H3_STREAM_SEND_CHUNKS, BUFQ_OPT_NONE);
  202. stream->sendbuf_len_in_flight = 0;
  203. /* on recv, we need a flexible buffer limit since we also write
  204. * headers to it that are not counted against the nghttp3 flow limits. */
  205. Curl_bufq_initp(&stream->recvbuf, &ctx->stream_bufcp,
  206. H3_STREAM_RECV_CHUNKS, BUFQ_OPT_SOFT_LIMIT);
  207. stream->recv_buf_nonflow = 0;
  208. Curl_h1_req_parse_init(&stream->h1, H1_PARSE_DEFAULT_MAX_LINE_LEN);
  209. H3_STREAM_LCTX(data) = stream;
  210. return CURLE_OK;
  211. }
  212. static void h3_data_done(struct Curl_cfilter *cf, struct Curl_easy *data)
  213. {
  214. struct h3_stream_ctx *stream = H3_STREAM_CTX(data);
  215. (void)cf;
  216. if(stream) {
  217. CURL_TRC_CF(data, cf, "[%"PRId64"] easy handle is done", stream->id);
  218. Curl_bufq_free(&stream->sendbuf);
  219. Curl_bufq_free(&stream->recvbuf);
  220. Curl_h1_req_parse_free(&stream->h1);
  221. free(stream);
  222. H3_STREAM_LCTX(data) = NULL;
  223. }
  224. }
  225. /* ngtcp2 default congestion controller does not perform pacing. Limit
  226. the maximum packet burst to MAX_PKT_BURST packets. */
  227. #define MAX_PKT_BURST 10
  228. struct pkt_io_ctx {
  229. struct Curl_cfilter *cf;
  230. struct Curl_easy *data;
  231. ngtcp2_tstamp ts;
  232. size_t pkt_count;
  233. ngtcp2_path_storage ps;
  234. };
  235. static ngtcp2_tstamp timestamp(void)
  236. {
  237. struct curltime ct = Curl_now();
  238. return ct.tv_sec * NGTCP2_SECONDS + ct.tv_usec * NGTCP2_MICROSECONDS;
  239. }
  240. static void pktx_init(struct pkt_io_ctx *pktx,
  241. struct Curl_cfilter *cf,
  242. struct Curl_easy *data)
  243. {
  244. pktx->cf = cf;
  245. pktx->data = data;
  246. pktx->ts = timestamp();
  247. pktx->pkt_count = 0;
  248. ngtcp2_path_storage_zero(&pktx->ps);
  249. }
  250. static CURLcode cf_progress_ingress(struct Curl_cfilter *cf,
  251. struct Curl_easy *data,
  252. struct pkt_io_ctx *pktx);
  253. static CURLcode cf_progress_egress(struct Curl_cfilter *cf,
  254. struct Curl_easy *data,
  255. struct pkt_io_ctx *pktx);
  256. static int cb_h3_acked_req_body(nghttp3_conn *conn, int64_t stream_id,
  257. uint64_t datalen, void *user_data,
  258. void *stream_user_data);
  259. static ngtcp2_conn *get_conn(ngtcp2_crypto_conn_ref *conn_ref)
  260. {
  261. struct Curl_cfilter *cf = conn_ref->user_data;
  262. struct cf_ngtcp2_ctx *ctx = cf->ctx;
  263. return ctx->qconn;
  264. }
  265. #ifdef DEBUG_NGTCP2
  266. static void quic_printf(void *user_data, const char *fmt, ...)
  267. {
  268. struct Curl_cfilter *cf = user_data;
  269. struct cf_ngtcp2_ctx *ctx = cf->ctx;
  270. (void)ctx; /* TODO: need an easy handle to infof() message */
  271. va_list ap;
  272. va_start(ap, fmt);
  273. vfprintf(stderr, fmt, ap);
  274. va_end(ap);
  275. fprintf(stderr, "\n");
  276. }
  277. #endif
  278. static void qlog_callback(void *user_data, uint32_t flags,
  279. const void *data, size_t datalen)
  280. {
  281. struct Curl_cfilter *cf = user_data;
  282. struct cf_ngtcp2_ctx *ctx = cf->ctx;
  283. (void)flags;
  284. if(ctx->qlogfd != -1) {
  285. ssize_t rc = write(ctx->qlogfd, data, datalen);
  286. if(rc == -1) {
  287. /* on write error, stop further write attempts */
  288. close(ctx->qlogfd);
  289. ctx->qlogfd = -1;
  290. }
  291. }
  292. }
  293. static void quic_settings(struct cf_ngtcp2_ctx *ctx,
  294. struct Curl_easy *data,
  295. struct pkt_io_ctx *pktx)
  296. {
  297. ngtcp2_settings *s = &ctx->settings;
  298. ngtcp2_transport_params *t = &ctx->transport_params;
  299. ngtcp2_settings_default(s);
  300. ngtcp2_transport_params_default(t);
  301. #ifdef DEBUG_NGTCP2
  302. s->log_printf = quic_printf;
  303. #else
  304. s->log_printf = NULL;
  305. #endif
  306. (void)data;
  307. s->initial_ts = pktx->ts;
  308. s->handshake_timeout = QUIC_HANDSHAKE_TIMEOUT;
  309. s->max_window = 100 * ctx->max_stream_window;
  310. s->max_stream_window = ctx->max_stream_window;
  311. t->initial_max_data = 10 * ctx->max_stream_window;
  312. t->initial_max_stream_data_bidi_local = ctx->max_stream_window;
  313. t->initial_max_stream_data_bidi_remote = ctx->max_stream_window;
  314. t->initial_max_stream_data_uni = ctx->max_stream_window;
  315. t->initial_max_streams_bidi = QUIC_MAX_STREAMS;
  316. t->initial_max_streams_uni = QUIC_MAX_STREAMS;
  317. t->max_idle_timeout = QUIC_IDLE_TIMEOUT;
  318. if(ctx->qlogfd != -1) {
  319. s->qlog_write = qlog_callback;
  320. }
  321. }
  322. #ifdef USE_OPENSSL
  323. static void keylog_callback(const SSL *ssl, const char *line)
  324. {
  325. (void)ssl;
  326. Curl_tls_keylog_write_line(line);
  327. }
  328. #elif defined(USE_GNUTLS)
  329. static int keylog_callback(gnutls_session_t session, const char *label,
  330. const gnutls_datum_t *secret)
  331. {
  332. gnutls_datum_t crandom;
  333. gnutls_datum_t srandom;
  334. gnutls_session_get_random(session, &crandom, &srandom);
  335. if(crandom.size != 32) {
  336. return -1;
  337. }
  338. Curl_tls_keylog_write(label, crandom.data, secret->data, secret->size);
  339. return 0;
  340. }
  341. #elif defined(USE_WOLFSSL)
  342. #if defined(HAVE_SECRET_CALLBACK)
  343. static void keylog_callback(const WOLFSSL *ssl, const char *line)
  344. {
  345. (void)ssl;
  346. Curl_tls_keylog_write_line(line);
  347. }
  348. #endif
  349. #endif
  350. static int init_ngh3_conn(struct Curl_cfilter *cf);
  351. #ifdef USE_OPENSSL
  352. static CURLcode quic_ssl_ctx(SSL_CTX **pssl_ctx,
  353. struct Curl_cfilter *cf, struct Curl_easy *data)
  354. {
  355. struct cf_ngtcp2_ctx *ctx = cf->ctx;
  356. struct connectdata *conn = cf->conn;
  357. CURLcode result = CURLE_FAILED_INIT;
  358. SSL_CTX *ssl_ctx = SSL_CTX_new(TLS_method());
  359. if(!ssl_ctx) {
  360. result = CURLE_OUT_OF_MEMORY;
  361. goto out;
  362. }
  363. #ifdef OPENSSL_IS_BORINGSSL
  364. if(ngtcp2_crypto_boringssl_configure_client_context(ssl_ctx) != 0) {
  365. failf(data, "ngtcp2_crypto_boringssl_configure_client_context failed");
  366. goto out;
  367. }
  368. #else
  369. if(ngtcp2_crypto_quictls_configure_client_context(ssl_ctx) != 0) {
  370. failf(data, "ngtcp2_crypto_quictls_configure_client_context failed");
  371. goto out;
  372. }
  373. #endif
  374. SSL_CTX_set_default_verify_paths(ssl_ctx);
  375. {
  376. const char *curves = conn->ssl_config.curves ?
  377. conn->ssl_config.curves : QUIC_GROUPS;
  378. if(!SSL_CTX_set1_curves_list(ssl_ctx, curves)) {
  379. failf(data, "failed setting curves list for QUIC: '%s'", curves);
  380. return CURLE_SSL_CIPHER;
  381. }
  382. }
  383. {
  384. const char *ciphers13 = conn->ssl_config.cipher_list13 ?
  385. conn->ssl_config.cipher_list13 : QUIC_CIPHERS;
  386. if(SSL_CTX_set_ciphersuites(ssl_ctx, ciphers13) != 1) {
  387. failf(data, "failed setting QUIC cipher suite: %s", ciphers13);
  388. return CURLE_SSL_CIPHER;
  389. }
  390. infof(data, "QUIC cipher selection: %s", ciphers13);
  391. }
  392. /* Open the file if a TLS or QUIC backend has not done this before. */
  393. Curl_tls_keylog_open();
  394. if(Curl_tls_keylog_enabled()) {
  395. SSL_CTX_set_keylog_callback(ssl_ctx, keylog_callback);
  396. }
  397. /* OpenSSL always tries to verify the peer, this only says whether it should
  398. * fail to connect if the verification fails, or if it should continue
  399. * anyway. In the latter case the result of the verification is checked with
  400. * SSL_get_verify_result() below. */
  401. SSL_CTX_set_verify(ssl_ctx, conn->ssl_config.verifypeer ?
  402. SSL_VERIFY_PEER : SSL_VERIFY_NONE, NULL);
  403. /* give application a chance to interfere with SSL set up. */
  404. if(data->set.ssl.fsslctx) {
  405. /* When a user callback is installed to modify the SSL_CTX,
  406. * we need to do the full initialization before calling it.
  407. * See: #11800 */
  408. if(!ctx->x509_store_setup) {
  409. result = Curl_ssl_setup_x509_store(cf, data, ssl_ctx);
  410. if(result)
  411. goto out;
  412. ctx->x509_store_setup = TRUE;
  413. }
  414. Curl_set_in_callback(data, true);
  415. result = (*data->set.ssl.fsslctx)(data, ssl_ctx,
  416. data->set.ssl.fsslctxp);
  417. Curl_set_in_callback(data, false);
  418. if(result) {
  419. failf(data, "error signaled by ssl ctx callback");
  420. goto out;
  421. }
  422. }
  423. result = CURLE_OK;
  424. out:
  425. *pssl_ctx = result? NULL : ssl_ctx;
  426. if(result && ssl_ctx)
  427. SSL_CTX_free(ssl_ctx);
  428. return result;
  429. }
  430. static CURLcode quic_set_client_cert(struct Curl_cfilter *cf,
  431. struct Curl_easy *data)
  432. {
  433. struct cf_ngtcp2_ctx *ctx = cf->ctx;
  434. SSL_CTX *ssl_ctx = ctx->sslctx;
  435. const struct ssl_config_data *ssl_config;
  436. ssl_config = Curl_ssl_get_config(data, FIRSTSOCKET);
  437. DEBUGASSERT(ssl_config);
  438. if(ssl_config->primary.clientcert || ssl_config->primary.cert_blob
  439. || ssl_config->cert_type) {
  440. return Curl_ossl_set_client_cert(
  441. data, ssl_ctx, ssl_config->primary.clientcert,
  442. ssl_config->primary.cert_blob, ssl_config->cert_type,
  443. ssl_config->key, ssl_config->key_blob,
  444. ssl_config->key_type, ssl_config->key_passwd);
  445. }
  446. return CURLE_OK;
  447. }
  448. /** SSL callbacks ***/
  449. static CURLcode quic_init_ssl(struct Curl_cfilter *cf,
  450. struct Curl_easy *data)
  451. {
  452. struct cf_ngtcp2_ctx *ctx = cf->ctx;
  453. const uint8_t *alpn = NULL;
  454. size_t alpnlen = 0;
  455. unsigned char checkip[16];
  456. DEBUGASSERT(!ctx->ssl);
  457. ctx->ssl = SSL_new(ctx->sslctx);
  458. SSL_set_app_data(ctx->ssl, &ctx->conn_ref);
  459. SSL_set_connect_state(ctx->ssl);
  460. SSL_set_quic_use_legacy_codepoint(ctx->ssl, 0);
  461. alpn = (const uint8_t *)H3_ALPN_H3_29 H3_ALPN_H3;
  462. alpnlen = sizeof(H3_ALPN_H3_29) - 1 + sizeof(H3_ALPN_H3) - 1;
  463. if(alpn)
  464. SSL_set_alpn_protos(ctx->ssl, alpn, (int)alpnlen);
  465. /* set SNI */
  466. if((0 == Curl_inet_pton(AF_INET, cf->conn->host.name, checkip))
  467. #ifdef ENABLE_IPV6
  468. && (0 == Curl_inet_pton(AF_INET6, cf->conn->host.name, checkip))
  469. #endif
  470. ) {
  471. char *snihost = Curl_ssl_snihost(data, cf->conn->host.name, NULL);
  472. if(!snihost || !SSL_set_tlsext_host_name(ctx->ssl, snihost)) {
  473. failf(data, "Failed set SNI");
  474. SSL_free(ctx->ssl);
  475. ctx->ssl = NULL;
  476. return CURLE_QUIC_CONNECT_ERROR;
  477. }
  478. }
  479. return CURLE_OK;
  480. }
  481. #elif defined(USE_GNUTLS)
  482. static CURLcode quic_init_ssl(struct Curl_cfilter *cf,
  483. struct Curl_easy *data)
  484. {
  485. struct cf_ngtcp2_ctx *ctx = cf->ctx;
  486. CURLcode result;
  487. gnutls_datum_t alpn[2];
  488. /* this will need some attention when HTTPS proxy over QUIC get fixed */
  489. const char * const hostname = cf->conn->host.name;
  490. long * const pverifyresult = &data->set.ssl.certverifyresult;
  491. int rc;
  492. DEBUGASSERT(ctx->gtls == NULL);
  493. ctx->gtls = calloc(1, sizeof(*(ctx->gtls)));
  494. if(!ctx->gtls)
  495. return CURLE_OUT_OF_MEMORY;
  496. result = gtls_client_init(data, &cf->conn->ssl_config, &data->set.ssl,
  497. hostname, ctx->gtls, pverifyresult);
  498. if(result)
  499. return result;
  500. gnutls_session_set_ptr(ctx->gtls->session, &ctx->conn_ref);
  501. if(ngtcp2_crypto_gnutls_configure_client_session(ctx->gtls->session) != 0) {
  502. CURL_TRC_CF(data, cf,
  503. "ngtcp2_crypto_gnutls_configure_client_session failed\n");
  504. return CURLE_QUIC_CONNECT_ERROR;
  505. }
  506. rc = gnutls_priority_set_direct(ctx->gtls->session, QUIC_PRIORITY, NULL);
  507. if(rc < 0) {
  508. CURL_TRC_CF(data, cf, "gnutls_priority_set_direct failed: %s\n",
  509. gnutls_strerror(rc));
  510. return CURLE_QUIC_CONNECT_ERROR;
  511. }
  512. /* Open the file if a TLS or QUIC backend has not done this before. */
  513. Curl_tls_keylog_open();
  514. if(Curl_tls_keylog_enabled()) {
  515. gnutls_session_set_keylog_function(ctx->gtls->session, keylog_callback);
  516. }
  517. /* strip the first byte (the length) from NGHTTP3_ALPN_H3 */
  518. alpn[0].data = (unsigned char *)H3_ALPN_H3_29 + 1;
  519. alpn[0].size = sizeof(H3_ALPN_H3_29) - 2;
  520. alpn[1].data = (unsigned char *)H3_ALPN_H3 + 1;
  521. alpn[1].size = sizeof(H3_ALPN_H3) - 2;
  522. gnutls_alpn_set_protocols(ctx->gtls->session,
  523. alpn, 2, GNUTLS_ALPN_MANDATORY);
  524. return CURLE_OK;
  525. }
  526. #elif defined(USE_WOLFSSL)
  527. static CURLcode quic_ssl_ctx(WOLFSSL_CTX **pssl_ctx,
  528. struct Curl_cfilter *cf, struct Curl_easy *data)
  529. {
  530. struct connectdata *conn = cf->conn;
  531. CURLcode result = CURLE_FAILED_INIT;
  532. WOLFSSL_CTX *ssl_ctx = wolfSSL_CTX_new(wolfTLSv1_3_client_method());
  533. if(!ssl_ctx) {
  534. result = CURLE_OUT_OF_MEMORY;
  535. goto out;
  536. }
  537. if(ngtcp2_crypto_wolfssl_configure_client_context(ssl_ctx) != 0) {
  538. failf(data, "ngtcp2_crypto_wolfssl_configure_client_context failed");
  539. goto out;
  540. }
  541. wolfSSL_CTX_set_default_verify_paths(ssl_ctx);
  542. if(wolfSSL_CTX_set_cipher_list(ssl_ctx, conn->ssl_config.cipher_list13 ?
  543. conn->ssl_config.cipher_list13 :
  544. QUIC_CIPHERS) != 1) {
  545. char error_buffer[256];
  546. ERR_error_string_n(ERR_get_error(), error_buffer, sizeof(error_buffer));
  547. failf(data, "wolfSSL failed to set ciphers: %s", error_buffer);
  548. goto out;
  549. }
  550. if(wolfSSL_CTX_set1_groups_list(ssl_ctx, conn->ssl_config.curves ?
  551. conn->ssl_config.curves :
  552. (char *)QUIC_GROUPS) != 1) {
  553. failf(data, "wolfSSL failed to set curves");
  554. goto out;
  555. }
  556. /* Open the file if a TLS or QUIC backend has not done this before. */
  557. Curl_tls_keylog_open();
  558. if(Curl_tls_keylog_enabled()) {
  559. #if defined(HAVE_SECRET_CALLBACK)
  560. wolfSSL_CTX_set_keylog_callback(ssl_ctx, keylog_callback);
  561. #else
  562. failf(data, "wolfSSL was built without keylog callback");
  563. goto out;
  564. #endif
  565. }
  566. if(conn->ssl_config.verifypeer) {
  567. const char * const ssl_cafile = conn->ssl_config.CAfile;
  568. const char * const ssl_capath = conn->ssl_config.CApath;
  569. wolfSSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL);
  570. if(conn->ssl_config.CAfile || conn->ssl_config.CApath) {
  571. /* tell wolfSSL where to find CA certificates that are used to verify
  572. the server's certificate. */
  573. if(!wolfSSL_CTX_load_verify_locations(ssl_ctx, ssl_cafile, ssl_capath)) {
  574. /* Fail if we insist on successfully verifying the server. */
  575. failf(data, "error setting certificate verify locations:"
  576. " CAfile: %s CApath: %s",
  577. ssl_cafile ? ssl_cafile : "none",
  578. ssl_capath ? ssl_capath : "none");
  579. goto out;
  580. }
  581. infof(data, " CAfile: %s", ssl_cafile ? ssl_cafile : "none");
  582. infof(data, " CApath: %s", ssl_capath ? ssl_capath : "none");
  583. }
  584. #ifdef CURL_CA_FALLBACK
  585. else {
  586. /* verifying the peer without any CA certificates won't work so
  587. use wolfssl's built-in default as fallback */
  588. wolfSSL_CTX_set_default_verify_paths(ssl_ctx);
  589. }
  590. #endif
  591. }
  592. else {
  593. wolfSSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_NONE, NULL);
  594. }
  595. /* give application a chance to interfere with SSL set up. */
  596. if(data->set.ssl.fsslctx) {
  597. Curl_set_in_callback(data, true);
  598. result = (*data->set.ssl.fsslctx)(data, ssl_ctx,
  599. data->set.ssl.fsslctxp);
  600. Curl_set_in_callback(data, false);
  601. if(result) {
  602. failf(data, "error signaled by ssl ctx callback");
  603. goto out;
  604. }
  605. }
  606. result = CURLE_OK;
  607. out:
  608. *pssl_ctx = result? NULL : ssl_ctx;
  609. if(result && ssl_ctx)
  610. SSL_CTX_free(ssl_ctx);
  611. return result;
  612. }
  613. /** SSL callbacks ***/
  614. static CURLcode quic_init_ssl(struct Curl_cfilter *cf,
  615. struct Curl_easy *data)
  616. {
  617. struct cf_ngtcp2_ctx *ctx = cf->ctx;
  618. const uint8_t *alpn = NULL;
  619. size_t alpnlen = 0;
  620. /* this will need some attention when HTTPS proxy over QUIC get fixed */
  621. const char * const hostname = cf->conn->host.name;
  622. (void)data;
  623. DEBUGASSERT(!ctx->ssl);
  624. ctx->ssl = wolfSSL_new(ctx->sslctx);
  625. wolfSSL_set_app_data(ctx->ssl, &ctx->conn_ref);
  626. wolfSSL_set_connect_state(ctx->ssl);
  627. wolfSSL_set_quic_use_legacy_codepoint(ctx->ssl, 0);
  628. alpn = (const uint8_t *)H3_ALPN_H3_29 H3_ALPN_H3;
  629. alpnlen = sizeof(H3_ALPN_H3_29) - 1 + sizeof(H3_ALPN_H3) - 1;
  630. if(alpn)
  631. wolfSSL_set_alpn_protos(ctx->ssl, alpn, (int)alpnlen);
  632. /* set SNI */
  633. wolfSSL_UseSNI(ctx->ssl, WOLFSSL_SNI_HOST_NAME,
  634. hostname, (unsigned short)strlen(hostname));
  635. return CURLE_OK;
  636. }
  637. #endif /* defined(USE_WOLFSSL) */
  638. static int cb_handshake_completed(ngtcp2_conn *tconn, void *user_data)
  639. {
  640. (void)user_data;
  641. (void)tconn;
  642. return 0;
  643. }
  644. static void report_consumed_data(struct Curl_cfilter *cf,
  645. struct Curl_easy *data,
  646. size_t consumed)
  647. {
  648. struct h3_stream_ctx *stream = H3_STREAM_CTX(data);
  649. struct cf_ngtcp2_ctx *ctx = cf->ctx;
  650. if(!stream)
  651. return;
  652. /* the HTTP/1.1 response headers are written to the buffer, but
  653. * consuming those does not count against flow control. */
  654. if(stream->recv_buf_nonflow) {
  655. if(consumed >= stream->recv_buf_nonflow) {
  656. consumed -= stream->recv_buf_nonflow;
  657. stream->recv_buf_nonflow = 0;
  658. }
  659. else {
  660. stream->recv_buf_nonflow -= consumed;
  661. consumed = 0;
  662. }
  663. }
  664. if(consumed > 0) {
  665. CURL_TRC_CF(data, cf, "[%" PRId64 "] ACK %zu bytes of DATA",
  666. stream->id, consumed);
  667. ngtcp2_conn_extend_max_stream_offset(ctx->qconn, stream->id,
  668. consumed);
  669. ngtcp2_conn_extend_max_offset(ctx->qconn, consumed);
  670. }
  671. }
  672. static int cb_recv_stream_data(ngtcp2_conn *tconn, uint32_t flags,
  673. int64_t stream_id, uint64_t offset,
  674. const uint8_t *buf, size_t buflen,
  675. void *user_data, void *stream_user_data)
  676. {
  677. struct Curl_cfilter *cf = user_data;
  678. struct cf_ngtcp2_ctx *ctx = cf->ctx;
  679. nghttp3_ssize nconsumed;
  680. int fin = (flags & NGTCP2_STREAM_DATA_FLAG_FIN) ? 1 : 0;
  681. struct Curl_easy *data = stream_user_data;
  682. (void)offset;
  683. (void)data;
  684. nconsumed =
  685. nghttp3_conn_read_stream(ctx->h3conn, stream_id, buf, buflen, fin);
  686. CURL_TRC_CF(data, cf, "[%" PRId64 "] read_stream(len=%zu) -> %zd",
  687. stream_id, buflen, nconsumed);
  688. if(nconsumed < 0) {
  689. ngtcp2_ccerr_set_application_error(
  690. &ctx->last_error,
  691. nghttp3_err_infer_quic_app_error_code((int)nconsumed), NULL, 0);
  692. return NGTCP2_ERR_CALLBACK_FAILURE;
  693. }
  694. /* number of bytes inside buflen which consists of framing overhead
  695. * including QPACK HEADERS. In other words, it does not consume payload of
  696. * DATA frame. */
  697. ngtcp2_conn_extend_max_stream_offset(tconn, stream_id, nconsumed);
  698. ngtcp2_conn_extend_max_offset(tconn, nconsumed);
  699. return 0;
  700. }
  701. static int
  702. cb_acked_stream_data_offset(ngtcp2_conn *tconn, int64_t stream_id,
  703. uint64_t offset, uint64_t datalen, void *user_data,
  704. void *stream_user_data)
  705. {
  706. struct Curl_cfilter *cf = user_data;
  707. struct cf_ngtcp2_ctx *ctx = cf->ctx;
  708. int rv;
  709. (void)stream_id;
  710. (void)tconn;
  711. (void)offset;
  712. (void)datalen;
  713. (void)stream_user_data;
  714. rv = nghttp3_conn_add_ack_offset(ctx->h3conn, stream_id, datalen);
  715. if(rv) {
  716. return NGTCP2_ERR_CALLBACK_FAILURE;
  717. }
  718. return 0;
  719. }
  720. static int cb_stream_close(ngtcp2_conn *tconn, uint32_t flags,
  721. int64_t stream3_id, uint64_t app_error_code,
  722. void *user_data, void *stream_user_data)
  723. {
  724. struct Curl_cfilter *cf = user_data;
  725. struct Curl_easy *data = stream_user_data;
  726. struct cf_ngtcp2_ctx *ctx = cf->ctx;
  727. int rv;
  728. (void)tconn;
  729. (void)data;
  730. /* stream is closed... */
  731. if(!(flags & NGTCP2_STREAM_CLOSE_FLAG_APP_ERROR_CODE_SET)) {
  732. app_error_code = NGHTTP3_H3_NO_ERROR;
  733. }
  734. rv = nghttp3_conn_close_stream(ctx->h3conn, stream3_id,
  735. app_error_code);
  736. CURL_TRC_CF(data, cf, "[%" PRId64 "] quic close(err=%"
  737. PRIu64 ") -> %d", stream3_id, app_error_code, rv);
  738. if(rv) {
  739. ngtcp2_ccerr_set_application_error(
  740. &ctx->last_error, nghttp3_err_infer_quic_app_error_code(rv), NULL, 0);
  741. return NGTCP2_ERR_CALLBACK_FAILURE;
  742. }
  743. return 0;
  744. }
  745. static int cb_stream_reset(ngtcp2_conn *tconn, int64_t stream_id,
  746. uint64_t final_size, uint64_t app_error_code,
  747. void *user_data, void *stream_user_data)
  748. {
  749. struct Curl_cfilter *cf = user_data;
  750. struct cf_ngtcp2_ctx *ctx = cf->ctx;
  751. struct Curl_easy *data = stream_user_data;
  752. int rv;
  753. (void)tconn;
  754. (void)final_size;
  755. (void)app_error_code;
  756. (void)data;
  757. rv = nghttp3_conn_shutdown_stream_read(ctx->h3conn, stream_id);
  758. CURL_TRC_CF(data, cf, "[%" PRId64 "] reset -> %d", stream_id, rv);
  759. if(rv) {
  760. return NGTCP2_ERR_CALLBACK_FAILURE;
  761. }
  762. return 0;
  763. }
  764. static int cb_stream_stop_sending(ngtcp2_conn *tconn, int64_t stream_id,
  765. uint64_t app_error_code, void *user_data,
  766. void *stream_user_data)
  767. {
  768. struct Curl_cfilter *cf = user_data;
  769. struct cf_ngtcp2_ctx *ctx = cf->ctx;
  770. int rv;
  771. (void)tconn;
  772. (void)app_error_code;
  773. (void)stream_user_data;
  774. rv = nghttp3_conn_shutdown_stream_read(ctx->h3conn, stream_id);
  775. if(rv) {
  776. return NGTCP2_ERR_CALLBACK_FAILURE;
  777. }
  778. return 0;
  779. }
  780. static int cb_extend_max_local_streams_bidi(ngtcp2_conn *tconn,
  781. uint64_t max_streams,
  782. void *user_data)
  783. {
  784. (void)tconn;
  785. (void)max_streams;
  786. (void)user_data;
  787. return 0;
  788. }
  789. static int cb_extend_max_stream_data(ngtcp2_conn *tconn, int64_t stream_id,
  790. uint64_t max_data, void *user_data,
  791. void *stream_user_data)
  792. {
  793. struct Curl_cfilter *cf = user_data;
  794. struct cf_ngtcp2_ctx *ctx = cf->ctx;
  795. int rv;
  796. (void)tconn;
  797. (void)max_data;
  798. (void)stream_user_data;
  799. rv = nghttp3_conn_unblock_stream(ctx->h3conn, stream_id);
  800. if(rv) {
  801. return NGTCP2_ERR_CALLBACK_FAILURE;
  802. }
  803. return 0;
  804. }
  805. static void cb_rand(uint8_t *dest, size_t destlen,
  806. const ngtcp2_rand_ctx *rand_ctx)
  807. {
  808. CURLcode result;
  809. (void)rand_ctx;
  810. result = Curl_rand(NULL, dest, destlen);
  811. if(result) {
  812. /* cb_rand is only used for non-cryptographic context. If Curl_rand
  813. failed, just fill 0 and call it *random*. */
  814. memset(dest, 0, destlen);
  815. }
  816. }
  817. static int cb_get_new_connection_id(ngtcp2_conn *tconn, ngtcp2_cid *cid,
  818. uint8_t *token, size_t cidlen,
  819. void *user_data)
  820. {
  821. CURLcode result;
  822. (void)tconn;
  823. (void)user_data;
  824. result = Curl_rand(NULL, cid->data, cidlen);
  825. if(result)
  826. return NGTCP2_ERR_CALLBACK_FAILURE;
  827. cid->datalen = cidlen;
  828. result = Curl_rand(NULL, token, NGTCP2_STATELESS_RESET_TOKENLEN);
  829. if(result)
  830. return NGTCP2_ERR_CALLBACK_FAILURE;
  831. return 0;
  832. }
  833. static int cb_recv_rx_key(ngtcp2_conn *tconn, ngtcp2_encryption_level level,
  834. void *user_data)
  835. {
  836. struct Curl_cfilter *cf = user_data;
  837. (void)tconn;
  838. if(level != NGTCP2_ENCRYPTION_LEVEL_1RTT) {
  839. return 0;
  840. }
  841. if(init_ngh3_conn(cf) != CURLE_OK) {
  842. return NGTCP2_ERR_CALLBACK_FAILURE;
  843. }
  844. return 0;
  845. }
  846. static ngtcp2_callbacks ng_callbacks = {
  847. ngtcp2_crypto_client_initial_cb,
  848. NULL, /* recv_client_initial */
  849. ngtcp2_crypto_recv_crypto_data_cb,
  850. cb_handshake_completed,
  851. NULL, /* recv_version_negotiation */
  852. ngtcp2_crypto_encrypt_cb,
  853. ngtcp2_crypto_decrypt_cb,
  854. ngtcp2_crypto_hp_mask_cb,
  855. cb_recv_stream_data,
  856. cb_acked_stream_data_offset,
  857. NULL, /* stream_open */
  858. cb_stream_close,
  859. NULL, /* recv_stateless_reset */
  860. ngtcp2_crypto_recv_retry_cb,
  861. cb_extend_max_local_streams_bidi,
  862. NULL, /* extend_max_local_streams_uni */
  863. cb_rand,
  864. cb_get_new_connection_id,
  865. NULL, /* remove_connection_id */
  866. ngtcp2_crypto_update_key_cb, /* update_key */
  867. NULL, /* path_validation */
  868. NULL, /* select_preferred_addr */
  869. cb_stream_reset,
  870. NULL, /* extend_max_remote_streams_bidi */
  871. NULL, /* extend_max_remote_streams_uni */
  872. cb_extend_max_stream_data,
  873. NULL, /* dcid_status */
  874. NULL, /* handshake_confirmed */
  875. NULL, /* recv_new_token */
  876. ngtcp2_crypto_delete_crypto_aead_ctx_cb,
  877. ngtcp2_crypto_delete_crypto_cipher_ctx_cb,
  878. NULL, /* recv_datagram */
  879. NULL, /* ack_datagram */
  880. NULL, /* lost_datagram */
  881. ngtcp2_crypto_get_path_challenge_data_cb,
  882. cb_stream_stop_sending,
  883. NULL, /* version_negotiation */
  884. cb_recv_rx_key,
  885. NULL, /* recv_tx_key */
  886. NULL, /* early_data_rejected */
  887. };
  888. /**
  889. * Connection maintenance like timeouts on packet ACKs etc. are done by us, not
  890. * the OS like for TCP. POLL events on the socket therefore are not
  891. * sufficient.
  892. * ngtcp2 tells us when it wants to be invoked again. We handle that via
  893. * the `Curl_expire()` mechanisms.
  894. */
  895. static CURLcode check_and_set_expiry(struct Curl_cfilter *cf,
  896. struct Curl_easy *data,
  897. struct pkt_io_ctx *pktx)
  898. {
  899. struct cf_ngtcp2_ctx *ctx = cf->ctx;
  900. struct pkt_io_ctx local_pktx;
  901. ngtcp2_tstamp expiry;
  902. if(!pktx) {
  903. pktx_init(&local_pktx, cf, data);
  904. pktx = &local_pktx;
  905. }
  906. else {
  907. pktx->ts = timestamp();
  908. }
  909. expiry = ngtcp2_conn_get_expiry(ctx->qconn);
  910. if(expiry != UINT64_MAX) {
  911. if(expiry <= pktx->ts) {
  912. CURLcode result;
  913. int rv = ngtcp2_conn_handle_expiry(ctx->qconn, pktx->ts);
  914. if(rv) {
  915. failf(data, "ngtcp2_conn_handle_expiry returned error: %s",
  916. ngtcp2_strerror(rv));
  917. ngtcp2_ccerr_set_liberr(&ctx->last_error, rv, NULL, 0);
  918. return CURLE_SEND_ERROR;
  919. }
  920. result = cf_progress_ingress(cf, data, pktx);
  921. if(result)
  922. return result;
  923. result = cf_progress_egress(cf, data, pktx);
  924. if(result)
  925. return result;
  926. /* ask again, things might have changed */
  927. expiry = ngtcp2_conn_get_expiry(ctx->qconn);
  928. }
  929. if(expiry > pktx->ts) {
  930. ngtcp2_duration timeout = expiry - pktx->ts;
  931. if(timeout % NGTCP2_MILLISECONDS) {
  932. timeout += NGTCP2_MILLISECONDS;
  933. }
  934. Curl_expire(data, timeout / NGTCP2_MILLISECONDS, EXPIRE_QUIC);
  935. }
  936. }
  937. return CURLE_OK;
  938. }
  939. static int cf_ngtcp2_get_select_socks(struct Curl_cfilter *cf,
  940. struct Curl_easy *data,
  941. curl_socket_t *socks)
  942. {
  943. struct cf_ngtcp2_ctx *ctx = cf->ctx;
  944. struct SingleRequest *k = &data->req;
  945. int rv = GETSOCK_BLANK;
  946. struct h3_stream_ctx *stream = H3_STREAM_CTX(data);
  947. struct cf_call_data save;
  948. CF_DATA_SAVE(save, cf, data);
  949. socks[0] = ctx->q.sockfd;
  950. /* in HTTP/3 we can always get a frame, so check read */
  951. rv |= GETSOCK_READSOCK(0);
  952. /* we're still uploading or the HTTP/2 layer wants to send data */
  953. if((k->keepon & KEEP_SENDBITS) == KEEP_SEND &&
  954. ngtcp2_conn_get_cwnd_left(ctx->qconn) &&
  955. ngtcp2_conn_get_max_data_left(ctx->qconn) &&
  956. stream && nghttp3_conn_is_stream_writable(ctx->h3conn, stream->id))
  957. rv |= GETSOCK_WRITESOCK(0);
  958. CF_DATA_RESTORE(cf, save);
  959. return rv;
  960. }
  961. static void h3_drain_stream(struct Curl_cfilter *cf,
  962. struct Curl_easy *data)
  963. {
  964. struct h3_stream_ctx *stream = H3_STREAM_CTX(data);
  965. unsigned char bits;
  966. (void)cf;
  967. bits = CURL_CSELECT_IN;
  968. if(stream && stream->upload_left && !stream->send_closed)
  969. bits |= CURL_CSELECT_OUT;
  970. if(data->state.dselect_bits != bits) {
  971. data->state.dselect_bits = bits;
  972. Curl_expire(data, 0, EXPIRE_RUN_NOW);
  973. }
  974. }
  975. static int cb_h3_stream_close(nghttp3_conn *conn, int64_t stream_id,
  976. uint64_t app_error_code, void *user_data,
  977. void *stream_user_data)
  978. {
  979. struct Curl_cfilter *cf = user_data;
  980. struct Curl_easy *data = stream_user_data;
  981. struct h3_stream_ctx *stream = H3_STREAM_CTX(data);
  982. (void)conn;
  983. (void)stream_id;
  984. /* we might be called by nghttp3 after we already cleaned up */
  985. if(!stream)
  986. return 0;
  987. stream->closed = TRUE;
  988. stream->error3 = app_error_code;
  989. if(stream->error3 != NGHTTP3_H3_NO_ERROR) {
  990. stream->reset = TRUE;
  991. stream->send_closed = TRUE;
  992. CURL_TRC_CF(data, cf, "[%" PRId64 "] RESET: error %" PRId64,
  993. stream->id, stream->error3);
  994. }
  995. else {
  996. CURL_TRC_CF(data, cf, "[%" PRId64 "] CLOSED", stream->id);
  997. }
  998. data->req.keepon &= ~KEEP_SEND_HOLD;
  999. h3_drain_stream(cf, data);
  1000. return 0;
  1001. }
  1002. /*
  1003. * write_resp_raw() copies response data in raw format to the `data`'s
  1004. * receive buffer. If not enough space is available, it appends to the
  1005. * `data`'s overflow buffer.
  1006. */
  1007. static CURLcode write_resp_raw(struct Curl_cfilter *cf,
  1008. struct Curl_easy *data,
  1009. const void *mem, size_t memlen,
  1010. bool flow)
  1011. {
  1012. struct h3_stream_ctx *stream = H3_STREAM_CTX(data);
  1013. CURLcode result = CURLE_OK;
  1014. ssize_t nwritten;
  1015. (void)cf;
  1016. if(!stream) {
  1017. return CURLE_RECV_ERROR;
  1018. }
  1019. nwritten = Curl_bufq_write(&stream->recvbuf, mem, memlen, &result);
  1020. if(nwritten < 0) {
  1021. return result;
  1022. }
  1023. if(!flow)
  1024. stream->recv_buf_nonflow += (size_t)nwritten;
  1025. if((size_t)nwritten < memlen) {
  1026. /* This MUST not happen. Our recbuf is dimensioned to hold the
  1027. * full max_stream_window and then some for this very reason. */
  1028. DEBUGASSERT(0);
  1029. return CURLE_RECV_ERROR;
  1030. }
  1031. return result;
  1032. }
  1033. static int cb_h3_recv_data(nghttp3_conn *conn, int64_t stream3_id,
  1034. const uint8_t *buf, size_t buflen,
  1035. void *user_data, void *stream_user_data)
  1036. {
  1037. struct Curl_cfilter *cf = user_data;
  1038. struct Curl_easy *data = stream_user_data;
  1039. struct h3_stream_ctx *stream = H3_STREAM_CTX(data);
  1040. CURLcode result;
  1041. (void)conn;
  1042. (void)stream3_id;
  1043. if(!stream)
  1044. return NGHTTP3_ERR_CALLBACK_FAILURE;
  1045. result = write_resp_raw(cf, data, buf, buflen, TRUE);
  1046. if(result) {
  1047. CURL_TRC_CF(data, cf, "[%" PRId64 "] DATA len=%zu, ERROR receiving %d",
  1048. stream->id, buflen, result);
  1049. return NGHTTP3_ERR_CALLBACK_FAILURE;
  1050. }
  1051. CURL_TRC_CF(data, cf, "[%" PRId64 "] DATA len=%zu", stream->id, buflen);
  1052. h3_drain_stream(cf, data);
  1053. return 0;
  1054. }
  1055. static int cb_h3_deferred_consume(nghttp3_conn *conn, int64_t stream3_id,
  1056. size_t consumed, void *user_data,
  1057. void *stream_user_data)
  1058. {
  1059. struct Curl_cfilter *cf = user_data;
  1060. struct cf_ngtcp2_ctx *ctx = cf->ctx;
  1061. (void)conn;
  1062. (void)stream_user_data;
  1063. /* nghttp3 has consumed bytes on the QUIC stream and we need to
  1064. * tell the QUIC connection to increase its flow control */
  1065. ngtcp2_conn_extend_max_stream_offset(ctx->qconn, stream3_id, consumed);
  1066. ngtcp2_conn_extend_max_offset(ctx->qconn, consumed);
  1067. return 0;
  1068. }
  1069. static int cb_h3_end_headers(nghttp3_conn *conn, int64_t stream_id,
  1070. int fin, void *user_data, void *stream_user_data)
  1071. {
  1072. struct Curl_cfilter *cf = user_data;
  1073. struct Curl_easy *data = stream_user_data;
  1074. struct h3_stream_ctx *stream = H3_STREAM_CTX(data);
  1075. CURLcode result = CURLE_OK;
  1076. (void)conn;
  1077. (void)stream_id;
  1078. (void)fin;
  1079. (void)cf;
  1080. if(!stream)
  1081. return 0;
  1082. /* add a CRLF only if we've received some headers */
  1083. result = write_resp_raw(cf, data, "\r\n", 2, FALSE);
  1084. if(result) {
  1085. return -1;
  1086. }
  1087. CURL_TRC_CF(data, cf, "[%" PRId64 "] end_headers, status=%d",
  1088. stream_id, stream->status_code);
  1089. if(stream->status_code / 100 != 1) {
  1090. stream->resp_hds_complete = TRUE;
  1091. }
  1092. h3_drain_stream(cf, data);
  1093. return 0;
  1094. }
  1095. static int cb_h3_recv_header(nghttp3_conn *conn, int64_t stream_id,
  1096. int32_t token, nghttp3_rcbuf *name,
  1097. nghttp3_rcbuf *value, uint8_t flags,
  1098. void *user_data, void *stream_user_data)
  1099. {
  1100. struct Curl_cfilter *cf = user_data;
  1101. nghttp3_vec h3name = nghttp3_rcbuf_get_buf(name);
  1102. nghttp3_vec h3val = nghttp3_rcbuf_get_buf(value);
  1103. struct Curl_easy *data = stream_user_data;
  1104. struct h3_stream_ctx *stream = H3_STREAM_CTX(data);
  1105. CURLcode result = CURLE_OK;
  1106. (void)conn;
  1107. (void)stream_id;
  1108. (void)token;
  1109. (void)flags;
  1110. (void)cf;
  1111. /* we might have cleaned up this transfer already */
  1112. if(!stream)
  1113. return 0;
  1114. if(token == NGHTTP3_QPACK_TOKEN__STATUS) {
  1115. char line[14]; /* status line is always 13 characters long */
  1116. size_t ncopy;
  1117. result = Curl_http_decode_status(&stream->status_code,
  1118. (const char *)h3val.base, h3val.len);
  1119. if(result)
  1120. return -1;
  1121. ncopy = msnprintf(line, sizeof(line), "HTTP/3 %03d \r\n",
  1122. stream->status_code);
  1123. CURL_TRC_CF(data, cf, "[%" PRId64 "] status: %s", stream_id, line);
  1124. result = write_resp_raw(cf, data, line, ncopy, FALSE);
  1125. if(result) {
  1126. return -1;
  1127. }
  1128. }
  1129. else {
  1130. /* store as an HTTP1-style header */
  1131. CURL_TRC_CF(data, cf, "[%" PRId64 "] header: %.*s: %.*s",
  1132. stream_id, (int)h3name.len, h3name.base,
  1133. (int)h3val.len, h3val.base);
  1134. result = write_resp_raw(cf, data, h3name.base, h3name.len, FALSE);
  1135. if(result) {
  1136. return -1;
  1137. }
  1138. result = write_resp_raw(cf, data, ": ", 2, FALSE);
  1139. if(result) {
  1140. return -1;
  1141. }
  1142. result = write_resp_raw(cf, data, h3val.base, h3val.len, FALSE);
  1143. if(result) {
  1144. return -1;
  1145. }
  1146. result = write_resp_raw(cf, data, "\r\n", 2, FALSE);
  1147. if(result) {
  1148. return -1;
  1149. }
  1150. }
  1151. return 0;
  1152. }
  1153. static int cb_h3_stop_sending(nghttp3_conn *conn, int64_t stream_id,
  1154. uint64_t app_error_code, void *user_data,
  1155. void *stream_user_data)
  1156. {
  1157. struct Curl_cfilter *cf = user_data;
  1158. struct cf_ngtcp2_ctx *ctx = cf->ctx;
  1159. int rv;
  1160. (void)conn;
  1161. (void)stream_user_data;
  1162. rv = ngtcp2_conn_shutdown_stream_read(ctx->qconn, 0, stream_id,
  1163. app_error_code);
  1164. if(rv && rv != NGTCP2_ERR_STREAM_NOT_FOUND) {
  1165. return NGTCP2_ERR_CALLBACK_FAILURE;
  1166. }
  1167. return 0;
  1168. }
  1169. static int cb_h3_reset_stream(nghttp3_conn *conn, int64_t stream_id,
  1170. uint64_t app_error_code, void *user_data,
  1171. void *stream_user_data) {
  1172. struct Curl_cfilter *cf = user_data;
  1173. struct cf_ngtcp2_ctx *ctx = cf->ctx;
  1174. struct Curl_easy *data = stream_user_data;
  1175. int rv;
  1176. (void)conn;
  1177. (void)data;
  1178. rv = ngtcp2_conn_shutdown_stream_write(ctx->qconn, 0, stream_id,
  1179. app_error_code);
  1180. CURL_TRC_CF(data, cf, "[%" PRId64 "] reset -> %d", stream_id, rv);
  1181. if(rv && rv != NGTCP2_ERR_STREAM_NOT_FOUND) {
  1182. return NGTCP2_ERR_CALLBACK_FAILURE;
  1183. }
  1184. return 0;
  1185. }
  1186. static nghttp3_callbacks ngh3_callbacks = {
  1187. cb_h3_acked_req_body, /* acked_stream_data */
  1188. cb_h3_stream_close,
  1189. cb_h3_recv_data,
  1190. cb_h3_deferred_consume,
  1191. NULL, /* begin_headers */
  1192. cb_h3_recv_header,
  1193. cb_h3_end_headers,
  1194. NULL, /* begin_trailers */
  1195. cb_h3_recv_header,
  1196. NULL, /* end_trailers */
  1197. cb_h3_stop_sending,
  1198. NULL, /* end_stream */
  1199. cb_h3_reset_stream,
  1200. NULL, /* shutdown */
  1201. NULL /* recv_settings */
  1202. };
  1203. static int init_ngh3_conn(struct Curl_cfilter *cf)
  1204. {
  1205. struct cf_ngtcp2_ctx *ctx = cf->ctx;
  1206. CURLcode result;
  1207. int rc;
  1208. int64_t ctrl_stream_id, qpack_enc_stream_id, qpack_dec_stream_id;
  1209. if(ngtcp2_conn_get_streams_uni_left(ctx->qconn) < 3) {
  1210. return CURLE_QUIC_CONNECT_ERROR;
  1211. }
  1212. nghttp3_settings_default(&ctx->h3settings);
  1213. rc = nghttp3_conn_client_new(&ctx->h3conn,
  1214. &ngh3_callbacks,
  1215. &ctx->h3settings,
  1216. nghttp3_mem_default(),
  1217. cf);
  1218. if(rc) {
  1219. result = CURLE_OUT_OF_MEMORY;
  1220. goto fail;
  1221. }
  1222. rc = ngtcp2_conn_open_uni_stream(ctx->qconn, &ctrl_stream_id, NULL);
  1223. if(rc) {
  1224. result = CURLE_QUIC_CONNECT_ERROR;
  1225. goto fail;
  1226. }
  1227. rc = nghttp3_conn_bind_control_stream(ctx->h3conn, ctrl_stream_id);
  1228. if(rc) {
  1229. result = CURLE_QUIC_CONNECT_ERROR;
  1230. goto fail;
  1231. }
  1232. rc = ngtcp2_conn_open_uni_stream(ctx->qconn, &qpack_enc_stream_id, NULL);
  1233. if(rc) {
  1234. result = CURLE_QUIC_CONNECT_ERROR;
  1235. goto fail;
  1236. }
  1237. rc = ngtcp2_conn_open_uni_stream(ctx->qconn, &qpack_dec_stream_id, NULL);
  1238. if(rc) {
  1239. result = CURLE_QUIC_CONNECT_ERROR;
  1240. goto fail;
  1241. }
  1242. rc = nghttp3_conn_bind_qpack_streams(ctx->h3conn, qpack_enc_stream_id,
  1243. qpack_dec_stream_id);
  1244. if(rc) {
  1245. result = CURLE_QUIC_CONNECT_ERROR;
  1246. goto fail;
  1247. }
  1248. return CURLE_OK;
  1249. fail:
  1250. return result;
  1251. }
  1252. static ssize_t recv_closed_stream(struct Curl_cfilter *cf,
  1253. struct Curl_easy *data,
  1254. struct h3_stream_ctx *stream,
  1255. CURLcode *err)
  1256. {
  1257. ssize_t nread = -1;
  1258. (void)cf;
  1259. if(stream->reset) {
  1260. failf(data,
  1261. "HTTP/3 stream %" PRId64 " reset by server", stream->id);
  1262. *err = stream->resp_hds_complete? CURLE_PARTIAL_FILE : CURLE_HTTP3;
  1263. goto out;
  1264. }
  1265. else if(!stream->resp_hds_complete) {
  1266. failf(data,
  1267. "HTTP/3 stream %" PRId64 " was closed cleanly, but before getting"
  1268. " all response header fields, treated as error",
  1269. stream->id);
  1270. *err = CURLE_HTTP3;
  1271. goto out;
  1272. }
  1273. *err = CURLE_OK;
  1274. nread = 0;
  1275. out:
  1276. return nread;
  1277. }
  1278. /* incoming data frames on the h3 stream */
  1279. static ssize_t cf_ngtcp2_recv(struct Curl_cfilter *cf, struct Curl_easy *data,
  1280. char *buf, size_t len, CURLcode *err)
  1281. {
  1282. struct cf_ngtcp2_ctx *ctx = cf->ctx;
  1283. struct h3_stream_ctx *stream = H3_STREAM_CTX(data);
  1284. ssize_t nread = -1;
  1285. struct cf_call_data save;
  1286. struct pkt_io_ctx pktx;
  1287. (void)ctx;
  1288. CF_DATA_SAVE(save, cf, data);
  1289. DEBUGASSERT(cf->connected);
  1290. DEBUGASSERT(ctx);
  1291. DEBUGASSERT(ctx->qconn);
  1292. DEBUGASSERT(ctx->h3conn);
  1293. *err = CURLE_OK;
  1294. pktx_init(&pktx, cf, data);
  1295. if(!stream) {
  1296. *err = CURLE_RECV_ERROR;
  1297. goto out;
  1298. }
  1299. if(!Curl_bufq_is_empty(&stream->recvbuf)) {
  1300. nread = Curl_bufq_read(&stream->recvbuf,
  1301. (unsigned char *)buf, len, err);
  1302. if(nread < 0) {
  1303. CURL_TRC_CF(data, cf, "[%" PRId64 "] read recvbuf(len=%zu) "
  1304. "-> %zd, %d", stream->id, len, nread, *err);
  1305. goto out;
  1306. }
  1307. report_consumed_data(cf, data, nread);
  1308. }
  1309. if(cf_progress_ingress(cf, data, &pktx)) {
  1310. *err = CURLE_RECV_ERROR;
  1311. nread = -1;
  1312. goto out;
  1313. }
  1314. /* recvbuf had nothing before, maybe after progressing ingress? */
  1315. if(nread < 0 && !Curl_bufq_is_empty(&stream->recvbuf)) {
  1316. nread = Curl_bufq_read(&stream->recvbuf,
  1317. (unsigned char *)buf, len, err);
  1318. if(nread < 0) {
  1319. CURL_TRC_CF(data, cf, "[%" PRId64 "] read recvbuf(len=%zu) "
  1320. "-> %zd, %d", stream->id, len, nread, *err);
  1321. goto out;
  1322. }
  1323. report_consumed_data(cf, data, nread);
  1324. }
  1325. if(nread > 0) {
  1326. h3_drain_stream(cf, data);
  1327. }
  1328. else {
  1329. if(stream->closed) {
  1330. nread = recv_closed_stream(cf, data, stream, err);
  1331. goto out;
  1332. }
  1333. *err = CURLE_AGAIN;
  1334. nread = -1;
  1335. }
  1336. out:
  1337. if(cf_progress_egress(cf, data, &pktx)) {
  1338. *err = CURLE_SEND_ERROR;
  1339. nread = -1;
  1340. }
  1341. else {
  1342. CURLcode result2 = check_and_set_expiry(cf, data, &pktx);
  1343. if(result2) {
  1344. *err = result2;
  1345. nread = -1;
  1346. }
  1347. }
  1348. CURL_TRC_CF(data, cf, "[%" PRId64 "] cf_recv(len=%zu) -> %zd, %d",
  1349. stream? stream->id : -1, len, nread, *err);
  1350. CF_DATA_RESTORE(cf, save);
  1351. return nread;
  1352. }
  1353. static int cb_h3_acked_req_body(nghttp3_conn *conn, int64_t stream_id,
  1354. uint64_t datalen, void *user_data,
  1355. void *stream_user_data)
  1356. {
  1357. struct Curl_cfilter *cf = user_data;
  1358. struct Curl_easy *data = stream_user_data;
  1359. struct h3_stream_ctx *stream = H3_STREAM_CTX(data);
  1360. size_t skiplen;
  1361. (void)cf;
  1362. if(!stream)
  1363. return 0;
  1364. /* The server acknowledged `datalen` of bytes from our request body.
  1365. * This is a delta. We have kept this data in `sendbuf` for
  1366. * re-transmissions and can free it now. */
  1367. if(datalen >= (uint64_t)stream->sendbuf_len_in_flight)
  1368. skiplen = stream->sendbuf_len_in_flight;
  1369. else
  1370. skiplen = (size_t)datalen;
  1371. Curl_bufq_skip(&stream->sendbuf, skiplen);
  1372. stream->sendbuf_len_in_flight -= skiplen;
  1373. /* Everything ACKed, we resume upload processing */
  1374. if(!stream->sendbuf_len_in_flight) {
  1375. int rv = nghttp3_conn_resume_stream(conn, stream_id);
  1376. if(rv) {
  1377. return NGTCP2_ERR_CALLBACK_FAILURE;
  1378. }
  1379. if((data->req.keepon & KEEP_SEND_HOLD) &&
  1380. (data->req.keepon & KEEP_SEND)) {
  1381. data->req.keepon &= ~KEEP_SEND_HOLD;
  1382. h3_drain_stream(cf, data);
  1383. CURL_TRC_CF(data, cf, "[%" PRId64 "] unpausing acks", stream_id);
  1384. }
  1385. }
  1386. return 0;
  1387. }
  1388. static nghttp3_ssize
  1389. cb_h3_read_req_body(nghttp3_conn *conn, int64_t stream_id,
  1390. nghttp3_vec *vec, size_t veccnt,
  1391. uint32_t *pflags, void *user_data,
  1392. void *stream_user_data)
  1393. {
  1394. struct Curl_cfilter *cf = user_data;
  1395. struct Curl_easy *data = stream_user_data;
  1396. struct h3_stream_ctx *stream = H3_STREAM_CTX(data);
  1397. ssize_t nwritten = 0;
  1398. size_t nvecs = 0;
  1399. (void)cf;
  1400. (void)conn;
  1401. (void)stream_id;
  1402. (void)user_data;
  1403. (void)veccnt;
  1404. if(!stream)
  1405. return NGHTTP3_ERR_CALLBACK_FAILURE;
  1406. /* nghttp3 keeps references to the sendbuf data until it is ACKed
  1407. * by the server (see `cb_h3_acked_req_body()` for updates).
  1408. * `sendbuf_len_in_flight` is the amount of bytes in `sendbuf`
  1409. * that we have already passed to nghttp3, but which have not been
  1410. * ACKed yet.
  1411. * Any amount beyond `sendbuf_len_in_flight` we need still to pass
  1412. * to nghttp3. Do that now, if we can. */
  1413. if(stream->sendbuf_len_in_flight < Curl_bufq_len(&stream->sendbuf)) {
  1414. nvecs = 0;
  1415. while(nvecs < veccnt &&
  1416. Curl_bufq_peek_at(&stream->sendbuf,
  1417. stream->sendbuf_len_in_flight,
  1418. (const unsigned char **)&vec[nvecs].base,
  1419. &vec[nvecs].len)) {
  1420. stream->sendbuf_len_in_flight += vec[nvecs].len;
  1421. nwritten += vec[nvecs].len;
  1422. ++nvecs;
  1423. }
  1424. DEBUGASSERT(nvecs > 0); /* we SHOULD have been be able to peek */
  1425. }
  1426. if(nwritten > 0 && stream->upload_left != -1)
  1427. stream->upload_left -= nwritten;
  1428. /* When we stopped sending and everything in `sendbuf` is "in flight",
  1429. * we are at the end of the request body. */
  1430. if(stream->upload_left == 0) {
  1431. *pflags = NGHTTP3_DATA_FLAG_EOF;
  1432. stream->send_closed = TRUE;
  1433. }
  1434. else if(!nwritten) {
  1435. /* Not EOF, and nothing to give, we signal WOULDBLOCK. */
  1436. CURL_TRC_CF(data, cf, "[%" PRId64 "] read req body -> AGAIN",
  1437. stream->id);
  1438. return NGHTTP3_ERR_WOULDBLOCK;
  1439. }
  1440. CURL_TRC_CF(data, cf, "[%" PRId64 "] read req body -> "
  1441. "%d vecs%s with %zu (buffered=%zu, left=%"
  1442. CURL_FORMAT_CURL_OFF_T ")",
  1443. stream->id, (int)nvecs,
  1444. *pflags == NGHTTP3_DATA_FLAG_EOF?" EOF":"",
  1445. nwritten, Curl_bufq_len(&stream->sendbuf),
  1446. stream->upload_left);
  1447. return (nghttp3_ssize)nvecs;
  1448. }
  1449. /* Index where :authority header field will appear in request header
  1450. field list. */
  1451. #define AUTHORITY_DST_IDX 3
  1452. static ssize_t h3_stream_open(struct Curl_cfilter *cf,
  1453. struct Curl_easy *data,
  1454. const void *buf, size_t len,
  1455. CURLcode *err)
  1456. {
  1457. struct cf_ngtcp2_ctx *ctx = cf->ctx;
  1458. struct h3_stream_ctx *stream = NULL;
  1459. struct dynhds h2_headers;
  1460. size_t nheader;
  1461. nghttp3_nv *nva = NULL;
  1462. int rc = 0;
  1463. unsigned int i;
  1464. ssize_t nwritten = -1;
  1465. nghttp3_data_reader reader;
  1466. nghttp3_data_reader *preader = NULL;
  1467. Curl_dynhds_init(&h2_headers, 0, DYN_HTTP_REQUEST);
  1468. *err = h3_data_setup(cf, data);
  1469. if(*err)
  1470. goto out;
  1471. stream = H3_STREAM_CTX(data);
  1472. DEBUGASSERT(stream);
  1473. nwritten = Curl_h1_req_parse_read(&stream->h1, buf, len, NULL, 0, err);
  1474. if(nwritten < 0)
  1475. goto out;
  1476. if(!stream->h1.done) {
  1477. /* need more data */
  1478. goto out;
  1479. }
  1480. DEBUGASSERT(stream->h1.req);
  1481. *err = Curl_http_req_to_h2(&h2_headers, stream->h1.req, data);
  1482. if(*err) {
  1483. nwritten = -1;
  1484. goto out;
  1485. }
  1486. /* no longer needed */
  1487. Curl_h1_req_parse_free(&stream->h1);
  1488. nheader = Curl_dynhds_count(&h2_headers);
  1489. nva = malloc(sizeof(nghttp3_nv) * nheader);
  1490. if(!nva) {
  1491. *err = CURLE_OUT_OF_MEMORY;
  1492. nwritten = -1;
  1493. goto out;
  1494. }
  1495. for(i = 0; i < nheader; ++i) {
  1496. struct dynhds_entry *e = Curl_dynhds_getn(&h2_headers, i);
  1497. nva[i].name = (unsigned char *)e->name;
  1498. nva[i].namelen = e->namelen;
  1499. nva[i].value = (unsigned char *)e->value;
  1500. nva[i].valuelen = e->valuelen;
  1501. nva[i].flags = NGHTTP3_NV_FLAG_NONE;
  1502. }
  1503. rc = ngtcp2_conn_open_bidi_stream(ctx->qconn, &stream->id, NULL);
  1504. if(rc) {
  1505. failf(data, "can get bidi streams");
  1506. *err = CURLE_SEND_ERROR;
  1507. goto out;
  1508. }
  1509. switch(data->state.httpreq) {
  1510. case HTTPREQ_POST:
  1511. case HTTPREQ_POST_FORM:
  1512. case HTTPREQ_POST_MIME:
  1513. case HTTPREQ_PUT:
  1514. /* known request body size or -1 */
  1515. if(data->state.infilesize != -1)
  1516. stream->upload_left = data->state.infilesize;
  1517. else
  1518. /* data sending without specifying the data amount up front */
  1519. stream->upload_left = -1; /* unknown */
  1520. break;
  1521. default:
  1522. /* there is not request body */
  1523. stream->upload_left = 0; /* no request body */
  1524. break;
  1525. }
  1526. stream->send_closed = (stream->upload_left == 0);
  1527. if(!stream->send_closed) {
  1528. reader.read_data = cb_h3_read_req_body;
  1529. preader = &reader;
  1530. }
  1531. rc = nghttp3_conn_submit_request(ctx->h3conn, stream->id,
  1532. nva, nheader, preader, data);
  1533. if(rc) {
  1534. switch(rc) {
  1535. case NGHTTP3_ERR_CONN_CLOSING:
  1536. CURL_TRC_CF(data, cf, "h3sid[%"PRId64"] failed to send, "
  1537. "connection is closing", stream->id);
  1538. break;
  1539. default:
  1540. CURL_TRC_CF(data, cf, "h3sid[%"PRId64"] failed to send -> %d (%s)",
  1541. stream->id, rc, ngtcp2_strerror(rc));
  1542. break;
  1543. }
  1544. *err = CURLE_SEND_ERROR;
  1545. nwritten = -1;
  1546. goto out;
  1547. }
  1548. if(Curl_trc_is_verbose(data)) {
  1549. infof(data, "[HTTP/3] [%" PRId64 "] OPENED stream for %s",
  1550. stream->id, data->state.url);
  1551. for(i = 0; i < nheader; ++i) {
  1552. infof(data, "[HTTP/3] [%" PRId64 "] [%.*s: %.*s]", stream->id,
  1553. (int)nva[i].namelen, nva[i].name,
  1554. (int)nva[i].valuelen, nva[i].value);
  1555. }
  1556. }
  1557. out:
  1558. free(nva);
  1559. Curl_dynhds_free(&h2_headers);
  1560. return nwritten;
  1561. }
  1562. static ssize_t cf_ngtcp2_send(struct Curl_cfilter *cf, struct Curl_easy *data,
  1563. const void *buf, size_t len, CURLcode *err)
  1564. {
  1565. struct cf_ngtcp2_ctx *ctx = cf->ctx;
  1566. struct h3_stream_ctx *stream = H3_STREAM_CTX(data);
  1567. ssize_t sent = 0;
  1568. struct cf_call_data save;
  1569. struct pkt_io_ctx pktx;
  1570. CURLcode result;
  1571. CF_DATA_SAVE(save, cf, data);
  1572. DEBUGASSERT(cf->connected);
  1573. DEBUGASSERT(ctx->qconn);
  1574. DEBUGASSERT(ctx->h3conn);
  1575. pktx_init(&pktx, cf, data);
  1576. *err = CURLE_OK;
  1577. result = cf_progress_ingress(cf, data, &pktx);
  1578. if(result) {
  1579. *err = result;
  1580. sent = -1;
  1581. }
  1582. if(!stream || stream->id < 0) {
  1583. sent = h3_stream_open(cf, data, buf, len, err);
  1584. if(sent < 0) {
  1585. CURL_TRC_CF(data, cf, "failed to open stream -> %d", *err);
  1586. goto out;
  1587. }
  1588. stream = H3_STREAM_CTX(data);
  1589. }
  1590. else if(stream->upload_blocked_len) {
  1591. /* the data in `buf` has already been submitted or added to the
  1592. * buffers, but have been EAGAINed on the last invocation. */
  1593. DEBUGASSERT(len >= stream->upload_blocked_len);
  1594. if(len < stream->upload_blocked_len) {
  1595. /* Did we get called again with a smaller `len`? This should not
  1596. * happen. We are not prepared to handle that. */
  1597. failf(data, "HTTP/3 send again with decreased length");
  1598. *err = CURLE_HTTP3;
  1599. sent = -1;
  1600. goto out;
  1601. }
  1602. sent = (ssize_t)stream->upload_blocked_len;
  1603. stream->upload_blocked_len = 0;
  1604. }
  1605. else if(stream->closed) {
  1606. if(stream->resp_hds_complete) {
  1607. /* Server decided to close the stream after having sent us a final
  1608. * response. This is valid if it is not interested in the request
  1609. * body. This happens on 30x or 40x responses.
  1610. * We silently discard the data sent, since this is not a transport
  1611. * error situation. */
  1612. CURL_TRC_CF(data, cf, "[%" PRId64 "] discarding data"
  1613. "on closed stream with response", stream->id);
  1614. *err = CURLE_OK;
  1615. sent = (ssize_t)len;
  1616. goto out;
  1617. }
  1618. *err = CURLE_HTTP3;
  1619. sent = -1;
  1620. goto out;
  1621. }
  1622. else {
  1623. sent = Curl_bufq_write(&stream->sendbuf, buf, len, err);
  1624. CURL_TRC_CF(data, cf, "[%" PRId64 "] cf_send, add to "
  1625. "sendbuf(len=%zu) -> %zd, %d",
  1626. stream->id, len, sent, *err);
  1627. if(sent < 0) {
  1628. goto out;
  1629. }
  1630. (void)nghttp3_conn_resume_stream(ctx->h3conn, stream->id);
  1631. }
  1632. result = cf_progress_egress(cf, data, &pktx);
  1633. if(result) {
  1634. *err = result;
  1635. sent = -1;
  1636. }
  1637. if(stream && sent > 0 && stream->sendbuf_len_in_flight) {
  1638. /* We have unacknowledged DATA and cannot report success to our
  1639. * caller. Instead we EAGAIN and remember how much we have already
  1640. * "written" into our various internal connection buffers.
  1641. * We put the stream upload on HOLD, until this gets ACKed. */
  1642. stream->upload_blocked_len = sent;
  1643. CURL_TRC_CF(data, cf, "[%" PRId64 "] cf_send(len=%zu), "
  1644. "%zu bytes in flight -> EGAIN", stream->id, len,
  1645. stream->sendbuf_len_in_flight);
  1646. *err = CURLE_AGAIN;
  1647. sent = -1;
  1648. data->req.keepon |= KEEP_SEND_HOLD;
  1649. }
  1650. out:
  1651. result = check_and_set_expiry(cf, data, &pktx);
  1652. if(result) {
  1653. *err = result;
  1654. sent = -1;
  1655. }
  1656. CURL_TRC_CF(data, cf, "[%" PRId64 "] cf_send(len=%zu) -> %zd, %d",
  1657. stream? stream->id : -1, len, sent, *err);
  1658. CF_DATA_RESTORE(cf, save);
  1659. return sent;
  1660. }
  1661. static CURLcode qng_verify_peer(struct Curl_cfilter *cf,
  1662. struct Curl_easy *data)
  1663. {
  1664. struct cf_ngtcp2_ctx *ctx = cf->ctx;
  1665. CURLcode result = CURLE_OK;
  1666. const char *hostname, *disp_hostname;
  1667. int port;
  1668. char *snihost;
  1669. Curl_conn_get_host(data, cf->sockindex, &hostname, &disp_hostname, &port);
  1670. snihost = Curl_ssl_snihost(data, hostname, NULL);
  1671. if(!snihost)
  1672. return CURLE_PEER_FAILED_VERIFICATION;
  1673. cf->conn->bits.multiplex = TRUE; /* at least potentially multiplexed */
  1674. cf->conn->httpversion = 30;
  1675. cf->conn->bundle->multiuse = BUNDLE_MULTIPLEX;
  1676. if(cf->conn->ssl_config.verifyhost) {
  1677. #ifdef USE_OPENSSL
  1678. X509 *server_cert;
  1679. server_cert = SSL_get_peer_certificate(ctx->ssl);
  1680. if(!server_cert) {
  1681. return CURLE_PEER_FAILED_VERIFICATION;
  1682. }
  1683. result = Curl_ossl_verifyhost(data, cf->conn, server_cert);
  1684. X509_free(server_cert);
  1685. if(result)
  1686. return result;
  1687. #elif defined(USE_GNUTLS)
  1688. result = Curl_gtls_verifyserver(data, ctx->gtls->session,
  1689. &cf->conn->ssl_config, &data->set.ssl,
  1690. hostname, disp_hostname,
  1691. data->set.str[STRING_SSL_PINNEDPUBLICKEY]);
  1692. if(result)
  1693. return result;
  1694. #elif defined(USE_WOLFSSL)
  1695. if(wolfSSL_check_domain_name(ctx->ssl, snihost) == SSL_FAILURE)
  1696. return CURLE_PEER_FAILED_VERIFICATION;
  1697. #endif
  1698. infof(data, "Verified certificate just fine");
  1699. }
  1700. else
  1701. infof(data, "Skipped certificate verification");
  1702. #ifdef USE_OPENSSL
  1703. if(data->set.ssl.certinfo)
  1704. /* asked to gather certificate info */
  1705. (void)Curl_ossl_certchain(data, ctx->ssl);
  1706. #endif
  1707. return result;
  1708. }
  1709. static CURLcode recv_pkt(const unsigned char *pkt, size_t pktlen,
  1710. struct sockaddr_storage *remote_addr,
  1711. socklen_t remote_addrlen, int ecn,
  1712. void *userp)
  1713. {
  1714. struct pkt_io_ctx *pktx = userp;
  1715. struct cf_ngtcp2_ctx *ctx = pktx->cf->ctx;
  1716. ngtcp2_pkt_info pi;
  1717. ngtcp2_path path;
  1718. int rv;
  1719. ++pktx->pkt_count;
  1720. ngtcp2_addr_init(&path.local, (struct sockaddr *)&ctx->q.local_addr,
  1721. ctx->q.local_addrlen);
  1722. ngtcp2_addr_init(&path.remote, (struct sockaddr *)remote_addr,
  1723. remote_addrlen);
  1724. pi.ecn = (uint8_t)ecn;
  1725. rv = ngtcp2_conn_read_pkt(ctx->qconn, &path, &pi, pkt, pktlen, pktx->ts);
  1726. if(rv) {
  1727. CURL_TRC_CF(pktx->data, pktx->cf, "ingress, read_pkt -> %s",
  1728. ngtcp2_strerror(rv));
  1729. if(!ctx->last_error.error_code) {
  1730. if(rv == NGTCP2_ERR_CRYPTO) {
  1731. ngtcp2_ccerr_set_tls_alert(&ctx->last_error,
  1732. ngtcp2_conn_get_tls_alert(ctx->qconn),
  1733. NULL, 0);
  1734. }
  1735. else {
  1736. ngtcp2_ccerr_set_liberr(&ctx->last_error, rv, NULL, 0);
  1737. }
  1738. }
  1739. if(rv == NGTCP2_ERR_CRYPTO)
  1740. /* this is a "TLS problem", but a failed certificate verification
  1741. is a common reason for this */
  1742. return CURLE_PEER_FAILED_VERIFICATION;
  1743. return CURLE_RECV_ERROR;
  1744. }
  1745. return CURLE_OK;
  1746. }
  1747. static CURLcode cf_progress_ingress(struct Curl_cfilter *cf,
  1748. struct Curl_easy *data,
  1749. struct pkt_io_ctx *pktx)
  1750. {
  1751. struct cf_ngtcp2_ctx *ctx = cf->ctx;
  1752. struct pkt_io_ctx local_pktx;
  1753. size_t pkts_chunk = 128, i;
  1754. size_t pkts_max = 10 * pkts_chunk;
  1755. CURLcode result = CURLE_OK;
  1756. if(!pktx) {
  1757. pktx_init(&local_pktx, cf, data);
  1758. pktx = &local_pktx;
  1759. }
  1760. else {
  1761. pktx->ts = timestamp();
  1762. }
  1763. #ifdef USE_OPENSSL
  1764. if(!ctx->x509_store_setup) {
  1765. result = Curl_ssl_setup_x509_store(cf, data, ctx->sslctx);
  1766. if(result)
  1767. return result;
  1768. ctx->x509_store_setup = TRUE;
  1769. }
  1770. #endif
  1771. for(i = 0; i < pkts_max; i += pkts_chunk) {
  1772. pktx->pkt_count = 0;
  1773. result = vquic_recv_packets(cf, data, &ctx->q, pkts_chunk,
  1774. recv_pkt, pktx);
  1775. if(result) /* error */
  1776. break;
  1777. if(pktx->pkt_count < pkts_chunk) /* got less than we could */
  1778. break;
  1779. /* give egress a chance before we receive more */
  1780. result = cf_progress_egress(cf, data, pktx);
  1781. if(result) /* error */
  1782. break;
  1783. }
  1784. return result;
  1785. }
  1786. /**
  1787. * Read a network packet to send from ngtcp2 into `buf`.
  1788. * Return number of bytes written or -1 with *err set.
  1789. */
  1790. static ssize_t read_pkt_to_send(void *userp,
  1791. unsigned char *buf, size_t buflen,
  1792. CURLcode *err)
  1793. {
  1794. struct pkt_io_ctx *x = userp;
  1795. struct cf_ngtcp2_ctx *ctx = x->cf->ctx;
  1796. nghttp3_vec vec[16];
  1797. nghttp3_ssize veccnt;
  1798. ngtcp2_ssize ndatalen;
  1799. uint32_t flags;
  1800. int64_t stream_id;
  1801. int fin;
  1802. ssize_t nwritten, n;
  1803. veccnt = 0;
  1804. stream_id = -1;
  1805. fin = 0;
  1806. /* ngtcp2 may want to put several frames from different streams into
  1807. * this packet. `NGTCP2_WRITE_STREAM_FLAG_MORE` tells it to do so.
  1808. * When `NGTCP2_ERR_WRITE_MORE` is returned, we *need* to make
  1809. * another iteration.
  1810. * When ngtcp2 is happy (because it has no other frame that would fit
  1811. * or it has nothing more to send), it returns the total length
  1812. * of the assembled packet. This may be 0 if there was nothing to send. */
  1813. nwritten = 0;
  1814. *err = CURLE_OK;
  1815. for(;;) {
  1816. if(ctx->h3conn && ngtcp2_conn_get_max_data_left(ctx->qconn)) {
  1817. veccnt = nghttp3_conn_writev_stream(ctx->h3conn, &stream_id, &fin, vec,
  1818. sizeof(vec) / sizeof(vec[0]));
  1819. if(veccnt < 0) {
  1820. failf(x->data, "nghttp3_conn_writev_stream returned error: %s",
  1821. nghttp3_strerror((int)veccnt));
  1822. ngtcp2_ccerr_set_application_error(
  1823. &ctx->last_error,
  1824. nghttp3_err_infer_quic_app_error_code((int)veccnt), NULL, 0);
  1825. *err = CURLE_SEND_ERROR;
  1826. return -1;
  1827. }
  1828. }
  1829. flags = NGTCP2_WRITE_STREAM_FLAG_MORE |
  1830. (fin ? NGTCP2_WRITE_STREAM_FLAG_FIN : 0);
  1831. n = ngtcp2_conn_writev_stream(ctx->qconn, &x->ps.path,
  1832. NULL, buf, buflen,
  1833. &ndatalen, flags, stream_id,
  1834. (const ngtcp2_vec *)vec, veccnt, x->ts);
  1835. if(n == 0) {
  1836. /* nothing to send */
  1837. *err = CURLE_AGAIN;
  1838. nwritten = -1;
  1839. goto out;
  1840. }
  1841. else if(n < 0) {
  1842. switch(n) {
  1843. case NGTCP2_ERR_STREAM_DATA_BLOCKED:
  1844. DEBUGASSERT(ndatalen == -1);
  1845. nghttp3_conn_block_stream(ctx->h3conn, stream_id);
  1846. n = 0;
  1847. break;
  1848. case NGTCP2_ERR_STREAM_SHUT_WR:
  1849. DEBUGASSERT(ndatalen == -1);
  1850. nghttp3_conn_shutdown_stream_write(ctx->h3conn, stream_id);
  1851. n = 0;
  1852. break;
  1853. case NGTCP2_ERR_WRITE_MORE:
  1854. /* ngtcp2 wants to send more. update the flow of the stream whose data
  1855. * is in the buffer and continue */
  1856. DEBUGASSERT(ndatalen >= 0);
  1857. n = 0;
  1858. break;
  1859. default:
  1860. DEBUGASSERT(ndatalen == -1);
  1861. failf(x->data, "ngtcp2_conn_writev_stream returned error: %s",
  1862. ngtcp2_strerror((int)n));
  1863. ngtcp2_ccerr_set_liberr(&ctx->last_error, (int)n, NULL, 0);
  1864. *err = CURLE_SEND_ERROR;
  1865. nwritten = -1;
  1866. goto out;
  1867. }
  1868. }
  1869. if(ndatalen >= 0) {
  1870. /* we add the amount of data bytes to the flow windows */
  1871. int rv = nghttp3_conn_add_write_offset(ctx->h3conn, stream_id, ndatalen);
  1872. if(rv) {
  1873. failf(x->data, "nghttp3_conn_add_write_offset returned error: %s\n",
  1874. nghttp3_strerror(rv));
  1875. return CURLE_SEND_ERROR;
  1876. }
  1877. }
  1878. if(n > 0) {
  1879. /* packet assembled, leave */
  1880. nwritten = n;
  1881. goto out;
  1882. }
  1883. }
  1884. out:
  1885. return nwritten;
  1886. }
  1887. static CURLcode cf_progress_egress(struct Curl_cfilter *cf,
  1888. struct Curl_easy *data,
  1889. struct pkt_io_ctx *pktx)
  1890. {
  1891. struct cf_ngtcp2_ctx *ctx = cf->ctx;
  1892. ssize_t nread;
  1893. size_t max_payload_size, path_max_payload_size, max_pktcnt;
  1894. size_t pktcnt = 0;
  1895. size_t gsolen = 0; /* this disables gso until we have a clue */
  1896. CURLcode curlcode;
  1897. struct pkt_io_ctx local_pktx;
  1898. if(!pktx) {
  1899. pktx_init(&local_pktx, cf, data);
  1900. pktx = &local_pktx;
  1901. }
  1902. else {
  1903. pktx->ts = timestamp();
  1904. ngtcp2_path_storage_zero(&pktx->ps);
  1905. }
  1906. curlcode = vquic_flush(cf, data, &ctx->q);
  1907. if(curlcode) {
  1908. if(curlcode == CURLE_AGAIN) {
  1909. Curl_expire(data, 1, EXPIRE_QUIC);
  1910. return CURLE_OK;
  1911. }
  1912. return curlcode;
  1913. }
  1914. /* In UDP, there is a maximum theoretical packet paload length and
  1915. * a minimum payload length that is "guarantueed" to work.
  1916. * To detect if this minimum payload can be increased, ngtcp2 sends
  1917. * now and then a packet payload larger than the minimum. It that
  1918. * is ACKed by the peer, both parties know that it works and
  1919. * the subsequent packets can use a larger one.
  1920. * This is called PMTUD (Path Maximum Transmission Unit Discovery).
  1921. * Since a PMTUD might be rejected right on send, we do not want it
  1922. * be followed by other packets of lesser size. Because those would
  1923. * also fail then. So, if we detect a PMTUD while buffering, we flush.
  1924. */
  1925. max_payload_size = ngtcp2_conn_get_max_tx_udp_payload_size(ctx->qconn);
  1926. path_max_payload_size =
  1927. ngtcp2_conn_get_path_max_tx_udp_payload_size(ctx->qconn);
  1928. /* maximum number of packets buffered before we flush to the socket */
  1929. max_pktcnt = CURLMIN(MAX_PKT_BURST,
  1930. ctx->q.sendbuf.chunk_size / max_payload_size);
  1931. for(;;) {
  1932. /* add the next packet to send, if any, to our buffer */
  1933. nread = Curl_bufq_sipn(&ctx->q.sendbuf, max_payload_size,
  1934. read_pkt_to_send, pktx, &curlcode);
  1935. if(nread < 0) {
  1936. if(curlcode != CURLE_AGAIN)
  1937. return curlcode;
  1938. /* Nothing more to add, flush and leave */
  1939. curlcode = vquic_send(cf, data, &ctx->q, gsolen);
  1940. if(curlcode) {
  1941. if(curlcode == CURLE_AGAIN) {
  1942. Curl_expire(data, 1, EXPIRE_QUIC);
  1943. return CURLE_OK;
  1944. }
  1945. return curlcode;
  1946. }
  1947. goto out;
  1948. }
  1949. DEBUGASSERT(nread > 0);
  1950. if(pktcnt == 0) {
  1951. /* first packet in buffer. This is either of a known, "good"
  1952. * payload size or it is a PMTUD. We'll see. */
  1953. gsolen = (size_t)nread;
  1954. }
  1955. else if((size_t)nread > gsolen ||
  1956. (gsolen > path_max_payload_size && (size_t)nread != gsolen)) {
  1957. /* The just added packet is a PMTUD *or* the one(s) before the
  1958. * just added were PMTUD and the last one is smaller.
  1959. * Flush the buffer before the last add. */
  1960. curlcode = vquic_send_tail_split(cf, data, &ctx->q,
  1961. gsolen, nread, nread);
  1962. if(curlcode) {
  1963. if(curlcode == CURLE_AGAIN) {
  1964. Curl_expire(data, 1, EXPIRE_QUIC);
  1965. return CURLE_OK;
  1966. }
  1967. return curlcode;
  1968. }
  1969. pktcnt = 0;
  1970. continue;
  1971. }
  1972. if(++pktcnt >= max_pktcnt || (size_t)nread < gsolen) {
  1973. /* Reached MAX_PKT_BURST *or*
  1974. * the capacity of our buffer *or*
  1975. * last add was shorter than the previous ones, flush */
  1976. curlcode = vquic_send(cf, data, &ctx->q, gsolen);
  1977. if(curlcode) {
  1978. if(curlcode == CURLE_AGAIN) {
  1979. Curl_expire(data, 1, EXPIRE_QUIC);
  1980. return CURLE_OK;
  1981. }
  1982. return curlcode;
  1983. }
  1984. /* pktbuf has been completely sent */
  1985. pktcnt = 0;
  1986. }
  1987. }
  1988. out:
  1989. return CURLE_OK;
  1990. }
  1991. /*
  1992. * Called from transfer.c:data_pending to know if we should keep looping
  1993. * to receive more data from the connection.
  1994. */
  1995. static bool cf_ngtcp2_data_pending(struct Curl_cfilter *cf,
  1996. const struct Curl_easy *data)
  1997. {
  1998. const struct h3_stream_ctx *stream = H3_STREAM_CTX(data);
  1999. (void)cf;
  2000. return stream && !Curl_bufq_is_empty(&stream->recvbuf);
  2001. }
  2002. static CURLcode h3_data_pause(struct Curl_cfilter *cf,
  2003. struct Curl_easy *data,
  2004. bool pause)
  2005. {
  2006. /* TODO: there seems right now no API in ngtcp2 to shrink/enlarge
  2007. * the streams windows. As we do in HTTP/2. */
  2008. if(!pause) {
  2009. h3_drain_stream(cf, data);
  2010. Curl_expire(data, 0, EXPIRE_RUN_NOW);
  2011. }
  2012. return CURLE_OK;
  2013. }
  2014. static CURLcode cf_ngtcp2_data_event(struct Curl_cfilter *cf,
  2015. struct Curl_easy *data,
  2016. int event, int arg1, void *arg2)
  2017. {
  2018. struct cf_ngtcp2_ctx *ctx = cf->ctx;
  2019. CURLcode result = CURLE_OK;
  2020. struct cf_call_data save;
  2021. CF_DATA_SAVE(save, cf, data);
  2022. (void)arg1;
  2023. (void)arg2;
  2024. switch(event) {
  2025. case CF_CTRL_DATA_SETUP:
  2026. break;
  2027. case CF_CTRL_DATA_PAUSE:
  2028. result = h3_data_pause(cf, data, (arg1 != 0));
  2029. break;
  2030. case CF_CTRL_DATA_DONE: {
  2031. h3_data_done(cf, data);
  2032. break;
  2033. }
  2034. case CF_CTRL_DATA_DONE_SEND: {
  2035. struct h3_stream_ctx *stream = H3_STREAM_CTX(data);
  2036. if(stream && !stream->send_closed) {
  2037. stream->send_closed = TRUE;
  2038. stream->upload_left = Curl_bufq_len(&stream->sendbuf);
  2039. (void)nghttp3_conn_resume_stream(ctx->h3conn, stream->id);
  2040. }
  2041. break;
  2042. }
  2043. case CF_CTRL_DATA_IDLE: {
  2044. struct h3_stream_ctx *stream = H3_STREAM_CTX(data);
  2045. CURL_TRC_CF(data, cf, "data idle");
  2046. if(stream && !stream->closed) {
  2047. result = check_and_set_expiry(cf, data, NULL);
  2048. if(result)
  2049. CURL_TRC_CF(data, cf, "data idle, check_and_set_expiry -> %d", result);
  2050. }
  2051. break;
  2052. }
  2053. default:
  2054. break;
  2055. }
  2056. CF_DATA_RESTORE(cf, save);
  2057. return result;
  2058. }
  2059. static void cf_ngtcp2_ctx_clear(struct cf_ngtcp2_ctx *ctx)
  2060. {
  2061. struct cf_call_data save = ctx->call_data;
  2062. if(ctx->qlogfd != -1) {
  2063. close(ctx->qlogfd);
  2064. }
  2065. #ifdef USE_OPENSSL
  2066. if(ctx->ssl)
  2067. SSL_free(ctx->ssl);
  2068. if(ctx->sslctx)
  2069. SSL_CTX_free(ctx->sslctx);
  2070. #elif defined(USE_GNUTLS)
  2071. if(ctx->gtls) {
  2072. if(ctx->gtls->cred)
  2073. gnutls_certificate_free_credentials(ctx->gtls->cred);
  2074. if(ctx->gtls->session)
  2075. gnutls_deinit(ctx->gtls->session);
  2076. free(ctx->gtls);
  2077. }
  2078. #elif defined(USE_WOLFSSL)
  2079. if(ctx->ssl)
  2080. wolfSSL_free(ctx->ssl);
  2081. if(ctx->sslctx)
  2082. wolfSSL_CTX_free(ctx->sslctx);
  2083. #endif
  2084. vquic_ctx_free(&ctx->q);
  2085. if(ctx->h3conn)
  2086. nghttp3_conn_del(ctx->h3conn);
  2087. if(ctx->qconn)
  2088. ngtcp2_conn_del(ctx->qconn);
  2089. Curl_bufcp_free(&ctx->stream_bufcp);
  2090. memset(ctx, 0, sizeof(*ctx));
  2091. ctx->qlogfd = -1;
  2092. ctx->call_data = save;
  2093. }
  2094. static void cf_ngtcp2_close(struct Curl_cfilter *cf, struct Curl_easy *data)
  2095. {
  2096. struct cf_ngtcp2_ctx *ctx = cf->ctx;
  2097. struct cf_call_data save;
  2098. CF_DATA_SAVE(save, cf, data);
  2099. if(ctx && ctx->qconn) {
  2100. char buffer[NGTCP2_MAX_UDP_PAYLOAD_SIZE];
  2101. ngtcp2_tstamp ts;
  2102. ngtcp2_ssize rc;
  2103. CURL_TRC_CF(data, cf, "close");
  2104. ts = timestamp();
  2105. rc = ngtcp2_conn_write_connection_close(ctx->qconn, NULL, /* path */
  2106. NULL, /* pkt_info */
  2107. (uint8_t *)buffer, sizeof(buffer),
  2108. &ctx->last_error, ts);
  2109. if(rc > 0) {
  2110. while((send(ctx->q.sockfd, buffer, (SEND_TYPE_ARG3)rc, 0) == -1) &&
  2111. SOCKERRNO == EINTR);
  2112. }
  2113. cf_ngtcp2_ctx_clear(ctx);
  2114. }
  2115. cf->connected = FALSE;
  2116. CF_DATA_RESTORE(cf, save);
  2117. }
  2118. static void cf_ngtcp2_destroy(struct Curl_cfilter *cf, struct Curl_easy *data)
  2119. {
  2120. struct cf_ngtcp2_ctx *ctx = cf->ctx;
  2121. struct cf_call_data save;
  2122. CF_DATA_SAVE(save, cf, data);
  2123. CURL_TRC_CF(data, cf, "destroy");
  2124. if(ctx) {
  2125. cf_ngtcp2_ctx_clear(ctx);
  2126. free(ctx);
  2127. }
  2128. cf->ctx = NULL;
  2129. /* No CF_DATA_RESTORE(cf, save) possible */
  2130. (void)save;
  2131. }
  2132. /*
  2133. * Might be called twice for happy eyeballs.
  2134. */
  2135. static CURLcode cf_connect_start(struct Curl_cfilter *cf,
  2136. struct Curl_easy *data,
  2137. struct pkt_io_ctx *pktx)
  2138. {
  2139. struct cf_ngtcp2_ctx *ctx = cf->ctx;
  2140. int rc;
  2141. int rv;
  2142. CURLcode result;
  2143. const struct Curl_sockaddr_ex *sockaddr = NULL;
  2144. int qfd;
  2145. ctx->version = NGTCP2_PROTO_VER_MAX;
  2146. ctx->max_stream_window = H3_STREAM_WINDOW_SIZE;
  2147. Curl_bufcp_init(&ctx->stream_bufcp, H3_STREAM_CHUNK_SIZE,
  2148. H3_STREAM_POOL_SPARES);
  2149. #ifdef USE_OPENSSL
  2150. result = quic_ssl_ctx(&ctx->sslctx, cf, data);
  2151. if(result)
  2152. return result;
  2153. result = quic_set_client_cert(cf, data);
  2154. if(result)
  2155. return result;
  2156. #elif defined(USE_WOLFSSL)
  2157. result = quic_ssl_ctx(&ctx->sslctx, cf, data);
  2158. if(result)
  2159. return result;
  2160. #endif
  2161. result = quic_init_ssl(cf, data);
  2162. if(result)
  2163. return result;
  2164. ctx->dcid.datalen = NGTCP2_MAX_CIDLEN;
  2165. result = Curl_rand(data, ctx->dcid.data, NGTCP2_MAX_CIDLEN);
  2166. if(result)
  2167. return result;
  2168. ctx->scid.datalen = NGTCP2_MAX_CIDLEN;
  2169. result = Curl_rand(data, ctx->scid.data, NGTCP2_MAX_CIDLEN);
  2170. if(result)
  2171. return result;
  2172. (void)Curl_qlogdir(data, ctx->scid.data, NGTCP2_MAX_CIDLEN, &qfd);
  2173. ctx->qlogfd = qfd; /* -1 if failure above */
  2174. quic_settings(ctx, data, pktx);
  2175. result = vquic_ctx_init(&ctx->q);
  2176. if(result)
  2177. return result;
  2178. Curl_cf_socket_peek(cf->next, data, &ctx->q.sockfd,
  2179. &sockaddr, NULL, NULL, NULL, NULL);
  2180. if(!sockaddr)
  2181. return CURLE_QUIC_CONNECT_ERROR;
  2182. ctx->q.local_addrlen = sizeof(ctx->q.local_addr);
  2183. rv = getsockname(ctx->q.sockfd, (struct sockaddr *)&ctx->q.local_addr,
  2184. &ctx->q.local_addrlen);
  2185. if(rv == -1)
  2186. return CURLE_QUIC_CONNECT_ERROR;
  2187. ngtcp2_addr_init(&ctx->connected_path.local,
  2188. (struct sockaddr *)&ctx->q.local_addr,
  2189. ctx->q.local_addrlen);
  2190. ngtcp2_addr_init(&ctx->connected_path.remote,
  2191. &sockaddr->sa_addr, sockaddr->addrlen);
  2192. rc = ngtcp2_conn_client_new(&ctx->qconn, &ctx->dcid, &ctx->scid,
  2193. &ctx->connected_path,
  2194. NGTCP2_PROTO_VER_V1, &ng_callbacks,
  2195. &ctx->settings, &ctx->transport_params,
  2196. NULL, cf);
  2197. if(rc)
  2198. return CURLE_QUIC_CONNECT_ERROR;
  2199. #ifdef USE_GNUTLS
  2200. ngtcp2_conn_set_tls_native_handle(ctx->qconn, ctx->gtls->session);
  2201. #else
  2202. ngtcp2_conn_set_tls_native_handle(ctx->qconn, ctx->ssl);
  2203. #endif
  2204. ngtcp2_ccerr_default(&ctx->last_error);
  2205. ctx->conn_ref.get_conn = get_conn;
  2206. ctx->conn_ref.user_data = cf;
  2207. return CURLE_OK;
  2208. }
  2209. static CURLcode cf_ngtcp2_connect(struct Curl_cfilter *cf,
  2210. struct Curl_easy *data,
  2211. bool blocking, bool *done)
  2212. {
  2213. struct cf_ngtcp2_ctx *ctx = cf->ctx;
  2214. CURLcode result = CURLE_OK;
  2215. struct cf_call_data save;
  2216. struct curltime now;
  2217. struct pkt_io_ctx pktx;
  2218. if(cf->connected) {
  2219. *done = TRUE;
  2220. return CURLE_OK;
  2221. }
  2222. /* Connect the UDP filter first */
  2223. if(!cf->next->connected) {
  2224. result = Curl_conn_cf_connect(cf->next, data, blocking, done);
  2225. if(result || !*done)
  2226. return result;
  2227. }
  2228. *done = FALSE;
  2229. now = Curl_now();
  2230. pktx_init(&pktx, cf, data);
  2231. CF_DATA_SAVE(save, cf, data);
  2232. if(ctx->reconnect_at.tv_sec && Curl_timediff(now, ctx->reconnect_at) < 0) {
  2233. /* Not time yet to attempt the next connect */
  2234. CURL_TRC_CF(data, cf, "waiting for reconnect time");
  2235. goto out;
  2236. }
  2237. if(!ctx->qconn) {
  2238. ctx->started_at = now;
  2239. result = cf_connect_start(cf, data, &pktx);
  2240. if(result)
  2241. goto out;
  2242. result = cf_progress_egress(cf, data, &pktx);
  2243. /* we do not expect to be able to recv anything yet */
  2244. goto out;
  2245. }
  2246. result = cf_progress_ingress(cf, data, &pktx);
  2247. if(result)
  2248. goto out;
  2249. result = cf_progress_egress(cf, data, &pktx);
  2250. if(result)
  2251. goto out;
  2252. if(ngtcp2_conn_get_handshake_completed(ctx->qconn)) {
  2253. ctx->handshake_at = now;
  2254. CURL_TRC_CF(data, cf, "handshake complete after %dms",
  2255. (int)Curl_timediff(now, ctx->started_at));
  2256. result = qng_verify_peer(cf, data);
  2257. if(!result) {
  2258. CURL_TRC_CF(data, cf, "peer verified");
  2259. cf->connected = TRUE;
  2260. cf->conn->alpn = CURL_HTTP_VERSION_3;
  2261. *done = TRUE;
  2262. connkeep(cf->conn, "HTTP/3 default");
  2263. }
  2264. }
  2265. out:
  2266. if(result == CURLE_RECV_ERROR && ctx->qconn &&
  2267. ngtcp2_conn_in_draining_period(ctx->qconn)) {
  2268. /* When a QUIC server instance is shutting down, it may send us a
  2269. * CONNECTION_CLOSE right away. Our connection then enters the DRAINING
  2270. * state.
  2271. * This may be a stopping of the service or it may be that the server
  2272. * is reloading and a new instance will start serving soon.
  2273. * In any case, we tear down our socket and start over with a new one.
  2274. * We re-open the underlying UDP cf right now, but do not start
  2275. * connecting until called again.
  2276. */
  2277. int reconn_delay_ms = 200;
  2278. CURL_TRC_CF(data, cf, "connect, remote closed, reconnect after %dms",
  2279. reconn_delay_ms);
  2280. Curl_conn_cf_close(cf->next, data);
  2281. cf_ngtcp2_ctx_clear(ctx);
  2282. result = Curl_conn_cf_connect(cf->next, data, FALSE, done);
  2283. if(!result && *done) {
  2284. *done = FALSE;
  2285. ctx->reconnect_at = now;
  2286. ctx->reconnect_at.tv_usec += reconn_delay_ms * 1000;
  2287. Curl_expire(data, reconn_delay_ms, EXPIRE_QUIC);
  2288. result = CURLE_OK;
  2289. }
  2290. }
  2291. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  2292. if(result) {
  2293. const char *r_ip = NULL;
  2294. int r_port = 0;
  2295. Curl_cf_socket_peek(cf->next, data, NULL, NULL,
  2296. &r_ip, &r_port, NULL, NULL);
  2297. infof(data, "QUIC connect to %s port %u failed: %s",
  2298. r_ip, r_port, curl_easy_strerror(result));
  2299. }
  2300. #endif
  2301. if(!result && ctx->qconn) {
  2302. result = check_and_set_expiry(cf, data, &pktx);
  2303. }
  2304. if(result || *done)
  2305. CURL_TRC_CF(data, cf, "connect -> %d, done=%d", result, *done);
  2306. CF_DATA_RESTORE(cf, save);
  2307. return result;
  2308. }
  2309. static CURLcode cf_ngtcp2_query(struct Curl_cfilter *cf,
  2310. struct Curl_easy *data,
  2311. int query, int *pres1, void *pres2)
  2312. {
  2313. struct cf_ngtcp2_ctx *ctx = cf->ctx;
  2314. struct cf_call_data save;
  2315. switch(query) {
  2316. case CF_QUERY_MAX_CONCURRENT: {
  2317. const ngtcp2_transport_params *rp;
  2318. DEBUGASSERT(pres1);
  2319. CF_DATA_SAVE(save, cf, data);
  2320. rp = ngtcp2_conn_get_remote_transport_params(ctx->qconn);
  2321. if(rp)
  2322. *pres1 = (rp->initial_max_streams_bidi > INT_MAX)?
  2323. INT_MAX : (int)rp->initial_max_streams_bidi;
  2324. else /* not arrived yet? */
  2325. *pres1 = Curl_multi_max_concurrent_streams(data->multi);
  2326. CURL_TRC_CF(data, cf, "query max_conncurrent -> %d", *pres1);
  2327. CF_DATA_RESTORE(cf, save);
  2328. return CURLE_OK;
  2329. }
  2330. case CF_QUERY_CONNECT_REPLY_MS:
  2331. if(ctx->got_first_byte) {
  2332. timediff_t ms = Curl_timediff(ctx->first_byte_at, ctx->started_at);
  2333. *pres1 = (ms < INT_MAX)? (int)ms : INT_MAX;
  2334. }
  2335. else
  2336. *pres1 = -1;
  2337. return CURLE_OK;
  2338. case CF_QUERY_TIMER_CONNECT: {
  2339. struct curltime *when = pres2;
  2340. if(ctx->got_first_byte)
  2341. *when = ctx->first_byte_at;
  2342. return CURLE_OK;
  2343. }
  2344. case CF_QUERY_TIMER_APPCONNECT: {
  2345. struct curltime *when = pres2;
  2346. if(cf->connected)
  2347. *when = ctx->handshake_at;
  2348. return CURLE_OK;
  2349. }
  2350. default:
  2351. break;
  2352. }
  2353. return cf->next?
  2354. cf->next->cft->query(cf->next, data, query, pres1, pres2) :
  2355. CURLE_UNKNOWN_OPTION;
  2356. }
  2357. static bool cf_ngtcp2_conn_is_alive(struct Curl_cfilter *cf,
  2358. struct Curl_easy *data,
  2359. bool *input_pending)
  2360. {
  2361. bool alive = TRUE;
  2362. *input_pending = FALSE;
  2363. if(!cf->next || !cf->next->cft->is_alive(cf->next, data, input_pending))
  2364. return FALSE;
  2365. if(*input_pending) {
  2366. /* This happens before we've sent off a request and the connection is
  2367. not in use by any other transfer, there shouldn't be any data here,
  2368. only "protocol frames" */
  2369. *input_pending = FALSE;
  2370. if(cf_progress_ingress(cf, data, NULL))
  2371. alive = FALSE;
  2372. else {
  2373. alive = TRUE;
  2374. }
  2375. }
  2376. return alive;
  2377. }
  2378. struct Curl_cftype Curl_cft_http3 = {
  2379. "HTTP/3",
  2380. CF_TYPE_IP_CONNECT | CF_TYPE_SSL | CF_TYPE_MULTIPLEX,
  2381. 0,
  2382. cf_ngtcp2_destroy,
  2383. cf_ngtcp2_connect,
  2384. cf_ngtcp2_close,
  2385. Curl_cf_def_get_host,
  2386. cf_ngtcp2_get_select_socks,
  2387. cf_ngtcp2_data_pending,
  2388. cf_ngtcp2_send,
  2389. cf_ngtcp2_recv,
  2390. cf_ngtcp2_data_event,
  2391. cf_ngtcp2_conn_is_alive,
  2392. Curl_cf_def_conn_keep_alive,
  2393. cf_ngtcp2_query,
  2394. };
  2395. CURLcode Curl_cf_ngtcp2_create(struct Curl_cfilter **pcf,
  2396. struct Curl_easy *data,
  2397. struct connectdata *conn,
  2398. const struct Curl_addrinfo *ai)
  2399. {
  2400. struct cf_ngtcp2_ctx *ctx = NULL;
  2401. struct Curl_cfilter *cf = NULL, *udp_cf = NULL;
  2402. CURLcode result;
  2403. (void)data;
  2404. ctx = calloc(sizeof(*ctx), 1);
  2405. if(!ctx) {
  2406. result = CURLE_OUT_OF_MEMORY;
  2407. goto out;
  2408. }
  2409. ctx->qlogfd = -1;
  2410. cf_ngtcp2_ctx_clear(ctx);
  2411. result = Curl_cf_create(&cf, &Curl_cft_http3, ctx);
  2412. if(result)
  2413. goto out;
  2414. result = Curl_cf_udp_create(&udp_cf, data, conn, ai, TRNSPRT_QUIC);
  2415. if(result)
  2416. goto out;
  2417. cf->conn = conn;
  2418. udp_cf->conn = cf->conn;
  2419. udp_cf->sockindex = cf->sockindex;
  2420. cf->next = udp_cf;
  2421. out:
  2422. *pcf = (!result)? cf : NULL;
  2423. if(result) {
  2424. if(udp_cf)
  2425. Curl_conn_cf_discard_sub(cf, udp_cf, data, TRUE);
  2426. Curl_safefree(cf);
  2427. Curl_safefree(ctx);
  2428. }
  2429. return result;
  2430. }
  2431. bool Curl_conn_is_ngtcp2(const struct Curl_easy *data,
  2432. const struct connectdata *conn,
  2433. int sockindex)
  2434. {
  2435. struct Curl_cfilter *cf = conn? conn->cfilter[sockindex] : NULL;
  2436. (void)data;
  2437. for(; cf; cf = cf->next) {
  2438. if(cf->cft == &Curl_cft_http3)
  2439. return TRUE;
  2440. if(cf->cft->flags & CF_TYPE_IP_CONNECT)
  2441. return FALSE;
  2442. }
  2443. return FALSE;
  2444. }
  2445. #endif