curl_ngtcp2.c 75 KB

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