curl_ngtcp2.c 81 KB

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