curl_ngtcp2.c 79 KB

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