@amritk/nish-aarch64-linux 0.37.0 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/std/net/fetch.ts CHANGED
@@ -16,10 +16,13 @@
16
16
  * **The async `fetch`** answers a `Result`: a `FetchResponse` whose body was
17
17
  * read whole before it answered (up to `maxBodyBytes`, 256 MiB by default,
18
18
  * else `HTTP_E_BODY_TOO_LARGE`), or a `FetchError` with the `HTTP_E_*` code.
19
- * The connect, every write and every read wait on the executor; the name
20
- * lookup still blocks, and only `http://` is driven (an `https://` URL answers
21
- * `HTTP_E_TLS` naming `fetchSync`, never a silent block). A `FetchPool` handed
22
- * in through `RequestInit.pool` keeps idle connections per route, capped.
19
+ * The name lookup, the connect, the TLS handshake, every write and every
20
+ * read wait on the executor, so a slow resolver or server stalls only its own
21
+ * task. An `https://` URL is checked as `fetchSync` checks it: the caller's
22
+ * roots or the system's, the host name and the wall clock, with no setting
23
+ * that skips it. A `FetchPool` handed in through `RequestInit.pool` keeps
24
+ * idle http connections per route, capped; an https one is closed after its
25
+ * fetch, never pooled.
23
26
  * Policy, proxies, redirects and error codes are the shared code below, so
24
27
  * both clients behave alike. It does not run under `--emit-ts`.
25
28
  *
@@ -99,9 +102,15 @@ import {
99
102
  } from "nish/net/http1-client-codec"
100
103
  import { httpFieldBytes } from "nish/net/http-fields"
101
104
  import { Url, urlDecode, urlDefaultPort, urlOrigin, urlParse, urlResolve } from "nish/net/url"
102
- import { resolveHost } from "nish/net/dns"
105
+ import { DnsClient, dnsLoadSystem, dnsLookupWith, resolveHost } from "nish/net/dns"
106
+ import { DnsConfig, DnsHosts, dnsParseAddress } from "nish/net/dns-config"
103
107
  import { DNS_ADDRESS_BYTES } from "nish/net/dns-message"
104
- import { DNS_RESOLVE_MAX_ADDRESSES, DNS_RESOLVE_TIMEOUT } from "nish/net/dns-resolver"
108
+ import {
109
+ DNS_RESOLVE_MAX_ADDRESSES,
110
+ DNS_RESOLVE_PENDING,
111
+ DNS_RESOLVE_TIMEOUT,
112
+ DnsResolver,
113
+ } from "nish/net/dns-resolver"
105
114
  import { OutboundPolicy, outboundAddressText, outboundFilter, outboundHostAllowed } from "nish/net/outbound"
106
115
  import {
107
116
  connectResult,
@@ -115,7 +124,7 @@ import {
115
124
  pollWait,
116
125
  tcpConnect,
117
126
  } from "nish:net"
118
- import { readable, writable } from "nish:async"
127
+ import { cancelled, readable, readableWithin, sleep, writable, writableWithin } from "nish:async"
119
128
  import { getenv, monotonicNanos, wallClockNanos } from "nish:process"
120
129
  import { PkiRoots, pkiLoadRoots, pkiLoadSystemRoots } from "nish/crypto/pki-roots"
121
130
  import { TlsClient, TlsClientConfig, tlsClientIsIpLiteral } from "nish/net/tls/client"
@@ -159,6 +168,8 @@ export const HTTP_E_IO: i32 = 15
159
168
  export const HTTP_E_PROXY: i32 = 16
160
169
  /** The outbound policy refused the URL's host or every address it resolved to. */
161
170
  export const HTTP_E_BLOCKED: i32 = 17
171
+ /** The async fetch's task was cancelled (`nish:async`'s `cancel`, or a deadline set with `cancelAfter`). */
172
+ export const HTTP_E_CANCELLED: i32 = 18
162
173
 
163
174
  /** A typed zero: a bare literal is an `f64` under `--number-mode f64`. */
164
175
  const HTTP_CLIENT_ZERO: i32 = 0
@@ -188,6 +199,14 @@ const HTTP_CLIENT_READABLE: i32 = 1
188
199
  const HTTP_CLIENT_WRITABLE: i32 = 2
189
200
  /** The size of the client random and of each ephemeral private key a TLS handshake draws. */
190
201
  const HTTP_CLIENT_TLS_KEY_BYTES: i32 = 32
202
+ /** The longest an async lookup sleeps between checks of its sockets, in milliseconds. */
203
+ const HTTP_CLIENT_DNS_SLICE_MS: i32 = 16
204
+ /**
205
+ * The async lookup's answer when it cannot wait on its own sockets (its poll
206
+ * loop could not be made or polled, or its task's sleep failed): below every
207
+ * `DNS_*` code, so it never reads as one of the resolver's.
208
+ */
209
+ const HTTP_CLIENT_LOOKUP_WAIT: i32 = -1000
191
210
 
192
211
  /**
193
212
  * A short name for an `HTTP_E_*` code, for messages: "dns", "read timeout",
@@ -217,6 +236,7 @@ export const httpErrorName = (code: i32): string => {
217
236
  "io",
218
237
  "proxy",
219
238
  "blocked",
239
+ "cancelled",
220
240
  ]
221
241
  return code >= 0 && code < toI32(names.length) ? names[code] : "unknown"
222
242
  }
@@ -281,6 +301,12 @@ export class HttpOptions {
281
301
  * `nish/net/outbound`). Null for none.
282
302
  */
283
303
  outbound: OutboundPolicy | null = null
304
+ /**
305
+ * The resolver settings a name is looked up with, as `dnsParseResolvConf`
306
+ * fills them; null reads `/etc/resolv.conf`. `/etc/hosts` is consulted
307
+ * either way. Only read, so one config can serve many fetches.
308
+ */
309
+ dns: DnsConfig | null = null
284
310
  /** The budget for the lookup and the connect together; 0 or less for none but the total. */
285
311
  connectTimeoutMs: i32 = 10000
286
312
  /** The longest wait for the server to send or take a byte; 0 or less for none. */
@@ -669,14 +695,12 @@ export class FetchSyncClient {
669
695
  if (this.trust !== null) {
670
696
  return true
671
697
  }
672
- const path: string | null = this.options.rootsPemPath
673
- const roots: PkiRoots = path !== null ? pkiLoadRoots(path, [], []) : pkiLoadSystemRoots()
674
- if (toI32(roots.roots.length) === 0) {
675
- const where: string = path !== null ? path : "SSL_CERT_FILE, SSL_CERT_DIR or the system's bundle"
676
- this.fail(HTTP_E_CERTIFICATE, `no trusted root certificate could be read from ${where}`)
698
+ const fault: HttpClientFault = new HttpClientFault()
699
+ this.trust = httpClientLoadTrust(this.options, fault)
700
+ if (this.trust === null) {
701
+ this.fail(fault.code, fault.text)
677
702
  return false
678
703
  }
679
- this.trust = tlsClientTrust(roots)
680
704
  return true
681
705
  }
682
706
 
@@ -693,40 +717,17 @@ export class FetchSyncClient {
693
717
  this.fail(HTTP_E_CERTIFICATE, "no trusted root certificates are loaded")
694
718
  return false
695
719
  }
696
- const random: u8[] = new Array<u8>(HTTP_CLIENT_TLS_KEY_BYTES)
697
- const x25519: u8[] = new Array<u8>(HTTP_CLIENT_TLS_KEY_BYTES)
698
- const p256: u8[] = new Array<u8>(HTTP_CLIENT_TLS_KEY_BYTES)
699
- crypto.getRandomValues(random)
700
- crypto.getRandomValues(x25519)
701
- crypto.getRandomValues(p256)
702
- // `TlsClient` copies both keys and zeroes these arrays.
703
- const conn: TlsRecordClient = new TlsRecordClient(
704
- new TlsClient(new TlsClientConfig(host, ["http/1.1"]), random, x25519, p256)
705
- )
720
+ const conn: TlsRecordClient = httpClientTlsStart(host, early)
706
721
  this.tls = conn
707
722
  if (toI32(this.plain.length) === 0) {
708
723
  this.plain = new Array<u8>(HTTP_CLIENT_READ_BYTES)
709
724
  }
710
- if (toI32(early.length) > 0) {
711
- conn.receive(early, HTTP_CLIENT_ZERO, toI32(early.length))
712
- }
725
+ const fault: HttpClientFault = new HttpClientFault()
713
726
  // The connection opens on the server's Finished, with the client's own
714
727
  // perhaps still queued: it is sent before the request is.
715
- while (conn.state !== TLS_RECORD_STATE_OPEN || conn.outputEnd > conn.outputStart) {
716
- if ((conn.interest() & TLS_RECORD_AUTH) !== 0) {
717
- const verdict: i32 = tlsClientVerdict(conn.tls, trust, wallClockNanos() / HTTP_CLIENT_NS_PER_MS)
718
- if (verdict !== 0) {
719
- conn.reject(verdict)
720
- this.fail(
721
- HTTP_E_CERTIFICATE,
722
- `the certificate ${host} presented was refused (TLS alert ${verdict})`
723
- )
724
- return false
725
- }
726
- conn.authenticate(true)
727
- }
728
- if (conn.state === TLS_RECORD_STATE_FAILED) {
729
- this.failTls(conn)
728
+ while (httpClientTlsOpening(conn)) {
729
+ if (!httpClientTlsVerify(conn, trust, host, fault)) {
730
+ this.fail(fault.code, fault.text)
730
731
  return false
731
732
  }
732
733
  const moved: boolean = conn.outputEnd > conn.outputStart ? this.flushTls(conn) : this.receiveTls(conn)
@@ -742,21 +743,10 @@ export class FetchSyncClient {
742
743
  * the proxy answers 2xx, every byte after its head belonging to the tunnel.
743
744
  */
744
745
  private tunnel(host: string, port: i32, proxy: Url): boolean {
745
- const authority: string = `${httpClientHostText(host)}:${port}`
746
- const names: string[] = ["Host"]
747
- const values: string[] = [authority]
748
- const auth: string | null = httpClientProxyAuth(proxy)
749
- if (auth === null) {
750
- this.fail(HTTP_E_PROXY, "the proxy's user name or password is not valid percent-encoding")
751
- return false
752
- }
753
- if (auth !== "") {
754
- names.push("Proxy-Authorization")
755
- values.push(auth)
756
- }
757
- const head: u8[] | null = http1RequestHead("CONNECT", authority, names, values, toI64(-2))
746
+ const fault: HttpClientFault = new HttpClientFault()
747
+ const head: u8[] | null = httpClientConnectHead(host, port, proxy, fault)
758
748
  if (head === null) {
759
- this.fail(HTTP_E_REQUEST, `a CONNECT to ${authority} could not be written`)
749
+ this.fail(fault.code, fault.text)
760
750
  return false
761
751
  }
762
752
  this.gotByte = false
@@ -770,7 +760,10 @@ export class FetchSyncClient {
770
760
  }
771
761
  const status: i32 = this.parser.status
772
762
  if (status < 200 || status > 299) {
773
- this.fail(HTTP_E_PROXY_REFUSED, `the proxy answered CONNECT ${authority} with ${status}`)
763
+ this.fail(
764
+ HTTP_E_PROXY_REFUSED,
765
+ `the proxy answered CONNECT ${httpClientHostText(host)}:${port} with ${status}`
766
+ )
774
767
  return false
775
768
  }
776
769
  // A 2xx has no body: the parser ends it, then reports the tunnel.
@@ -964,13 +957,9 @@ export class FetchSyncClient {
964
957
 
965
958
  /** Sets the error for the failed TLS connection `conn`, saying how it failed. */
966
959
  private failTls(conn: TlsRecordClient): void {
967
- if (conn.ended && !conn.peerClosed) {
968
- this.fail(HTTP_E_TLS, "the server closed the connection without a TLS close_notify")
969
- } else if (conn.peerAlert > 0) {
970
- this.fail(HTTP_E_TLS, `the server sent TLS alert ${conn.peerAlert}`)
971
- } else {
972
- this.fail(HTTP_E_TLS, `the TLS connection failed (alert ${conn.failure()})`)
973
- }
960
+ const fault: HttpClientFault = new HttpClientFault()
961
+ httpClientTlsFault(conn, fault)
962
+ this.fail(fault.code, fault.text)
974
963
  }
975
964
 
976
965
  /** Writes `bytes[off, off + len)` on the connection, through TLS for an https origin; false with the error set. */
@@ -1175,13 +1164,7 @@ export class FetchSyncClient {
1175
1164
  private drop(): void {
1176
1165
  const conn: TlsRecordClient | null = this.tls
1177
1166
  if (conn !== null) {
1178
- conn.close()
1179
- // One try, without waiting, so the server sees the close_notify, or
1180
- // the alert a refusal sealed, when the socket has room for it.
1181
- if (this.fd >= 0 && conn.outputEnd > conn.outputStart) {
1182
- netWrite(this.fd, conn.output, conn.outputStart, conn.outputEnd - conn.outputStart)
1183
- }
1184
- conn.wipe()
1167
+ httpClientTlsClose(conn, this.fd)
1185
1168
  this.tls = null
1186
1169
  }
1187
1170
  if (this.fd >= 0) {
@@ -1706,6 +1689,121 @@ class HttpClientFault {
1706
1689
  }
1707
1690
  }
1708
1691
 
1692
+ /**
1693
+ * The roots an https fetch verifies against: the caller's `rootsPemPath`, or
1694
+ * the system's bundle without one; null with `fault` set when none could be
1695
+ * read, which fails the fetch rather than trusting nothing.
1696
+ */
1697
+ const httpClientLoadTrust = (options: HttpOptions, fault: HttpClientFault): TlsClientTrust | null => {
1698
+ const path: string | null = options.rootsPemPath
1699
+ const roots: PkiRoots = path !== null ? pkiLoadRoots(path, [], []) : pkiLoadSystemRoots()
1700
+ if (toI32(roots.roots.length) === 0) {
1701
+ const where: string = path !== null ? path : "SSL_CERT_FILE, SSL_CERT_DIR or the system's bundle"
1702
+ fault.fail(HTTP_E_CERTIFICATE, `no trusted root certificate could be read from ${where}`)
1703
+ return null
1704
+ }
1705
+ return tlsClientTrust(roots)
1706
+ }
1707
+
1708
+ /**
1709
+ * A fresh TLS client for `host`, offering http/1.1, its random and key
1710
+ * shares drawn from `crypto.getRandomValues`; `early`, bytes read past a
1711
+ * proxy's CONNECT answer, are fed to it first.
1712
+ */
1713
+ const httpClientTlsStart = (host: string, early: u8[]): TlsRecordClient => {
1714
+ const random: u8[] = new Array<u8>(HTTP_CLIENT_TLS_KEY_BYTES)
1715
+ const x25519: u8[] = new Array<u8>(HTTP_CLIENT_TLS_KEY_BYTES)
1716
+ const p256: u8[] = new Array<u8>(HTTP_CLIENT_TLS_KEY_BYTES)
1717
+ crypto.getRandomValues(random)
1718
+ crypto.getRandomValues(x25519)
1719
+ crypto.getRandomValues(p256)
1720
+ // `TlsClient` copies both keys and zeroes these arrays.
1721
+ const conn: TlsRecordClient = new TlsRecordClient(
1722
+ new TlsClient(new TlsClientConfig(host, ["http/1.1"]), random, x25519, p256)
1723
+ )
1724
+ if (toI32(early.length) > 0) {
1725
+ conn.receive(early, HTTP_CLIENT_ZERO, toI32(early.length))
1726
+ }
1727
+ return conn
1728
+ }
1729
+
1730
+ /** Whether the handshake on `conn` still has a step to take: it is not open, or its last flight is unsent. */
1731
+ const httpClientTlsOpening = (conn: TlsRecordClient): boolean =>
1732
+ conn.state !== TLS_RECORD_STATE_OPEN || conn.outputEnd > conn.outputStart
1733
+
1734
+ /** Sets `fault` for the failed TLS connection `conn`, saying how it failed. */
1735
+ const httpClientTlsFault = (conn: TlsRecordClient, fault: HttpClientFault): void => {
1736
+ if (conn.ended && !conn.peerClosed) {
1737
+ fault.fail(HTTP_E_TLS, "the server closed the connection without a TLS close_notify")
1738
+ } else if (conn.peerAlert > 0) {
1739
+ fault.fail(HTTP_E_TLS, `the server sent TLS alert ${conn.peerAlert}`)
1740
+ } else {
1741
+ fault.fail(HTTP_E_TLS, `the TLS connection failed (alert ${conn.failure()})`)
1742
+ }
1743
+ }
1744
+
1745
+ /**
1746
+ * One verification step of a handshake: when `conn` waits on the server's
1747
+ * chain, checks it against `trust`, the name `host` and the wall clock, and
1748
+ * refuses it with its alert or accepts it. False with `fault` set when the
1749
+ * chain was refused or `conn` has failed. There is no setting that skips it.
1750
+ */
1751
+ const httpClientTlsVerify = (
1752
+ conn: TlsRecordClient,
1753
+ trust: TlsClientTrust,
1754
+ host: string,
1755
+ fault: HttpClientFault
1756
+ ): boolean => {
1757
+ if ((conn.interest() & TLS_RECORD_AUTH) !== 0) {
1758
+ const verdict: i32 = tlsClientVerdict(conn.tls, trust, wallClockNanos() / HTTP_CLIENT_NS_PER_MS)
1759
+ if (verdict !== 0) {
1760
+ conn.reject(verdict)
1761
+ fault.fail(HTTP_E_CERTIFICATE, `the certificate ${host} presented was refused (TLS alert ${verdict})`)
1762
+ return false
1763
+ }
1764
+ conn.authenticate(true)
1765
+ }
1766
+ if (conn.state === TLS_RECORD_STATE_FAILED) {
1767
+ httpClientTlsFault(conn, fault)
1768
+ return false
1769
+ }
1770
+ return true
1771
+ }
1772
+
1773
+ /**
1774
+ * Closes the TLS layer of a connection on `fd`: seals a close_notify, tries
1775
+ * one write of what is pending without waiting, so the server sees it or the
1776
+ * alert a refusal sealed when the socket has room, and wipes the keys.
1777
+ */
1778
+ const httpClientTlsClose = (conn: TlsRecordClient, fd: i32): void => {
1779
+ conn.close()
1780
+ if (fd >= 0 && conn.outputEnd > conn.outputStart) {
1781
+ netWrite(fd, conn.output, conn.outputStart, conn.outputEnd - conn.outputStart)
1782
+ }
1783
+ conn.wipe()
1784
+ }
1785
+
1786
+ /** The head of a CONNECT asking `proxy` for a tunnel to `host:port`, with its credentials; null with `fault` set. */
1787
+ const httpClientConnectHead = (host: string, port: i32, proxy: Url, fault: HttpClientFault): u8[] | null => {
1788
+ const authority: string = `${httpClientHostText(host)}:${port}`
1789
+ const names: string[] = ["Host"]
1790
+ const values: string[] = [authority]
1791
+ const auth: string | null = httpClientProxyAuth(proxy)
1792
+ if (auth === null) {
1793
+ fault.fail(HTTP_E_PROXY, "the proxy's user name or password is not valid percent-encoding")
1794
+ return null
1795
+ }
1796
+ if (auth !== "") {
1797
+ names.push("Proxy-Authorization")
1798
+ values.push(auth)
1799
+ }
1800
+ const head: u8[] | null = http1RequestHead("CONNECT", authority, names, values, toI64(-2))
1801
+ if (head === null) {
1802
+ fault.fail(HTTP_E_REQUEST, `a CONNECT to ${authority} could not be written`)
1803
+ }
1804
+ return head
1805
+ }
1806
+
1709
1807
  /** Why the outbound policy refuses to let a URL name `url`'s host; "" when there is no policy or it allows the host. */
1710
1808
  const httpClientHostRefusal = (options: HttpOptions, url: Url): string => {
1711
1809
  const policy: OutboundPolicy | null = options.outbound
@@ -1983,7 +2081,8 @@ const httpClientWaitText = (code: i32, options: HttpOptions, text: string): stri
1983
2081
  /**
1984
2082
  * Looks `host` up within `start`..`until` into `addresses` and keeps those
1985
2083
  * the outbound policy allows: how many to try, or -1 with `fault` set (`code`
1986
- * names the deadline a lookup that timed out ran past). The lookup blocks.
2084
+ * names the deadline a lookup that timed out ran past), with `options.dns`
2085
+ * when it is set. The lookup blocks: this is `fetchSync`'s.
1987
2086
  */
1988
2087
  const httpClientResolve = (
1989
2088
  host: string,
@@ -2002,7 +2101,33 @@ const httpClientResolve = (
2002
2101
  lookupMs = toI64(2147483647)
2003
2102
  }
2004
2103
  const ttls: i32[] = new Array<i32>(DNS_RESOLVE_MAX_ADDRESSES)
2005
- const count: i32 = resolveHost(host, toI32(lookupMs), port, addresses, ttls)
2104
+ const dns: DnsConfig | null = options.dns
2105
+ let count: i32 = 0
2106
+ if (dns === null) {
2107
+ count = resolveHost(host, toI32(lookupMs), port, addresses, ttls)
2108
+ } else {
2109
+ const hosts: DnsHosts = new DnsHosts()
2110
+ dnsLoadSystem(null, hosts)
2111
+ count = dnsLookupWith(dns, hosts, host, toI32(lookupMs), port, addresses, ttls)
2112
+ }
2113
+ return httpClientAnswers(host, count, options, until, code, addresses, fault)
2114
+ }
2115
+
2116
+ /**
2117
+ * What a lookup of `host` that answered `count` leaves to try: the addresses
2118
+ * the outbound policy allows, kept at the front of `addresses`, or -1 with
2119
+ * `fault` set (`code` names the deadline a lookup that timed out ran past).
2120
+ * The blocking and the async lookup share it, so both refuse alike.
2121
+ */
2122
+ const httpClientAnswers = (
2123
+ host: string,
2124
+ count: i32,
2125
+ options: HttpOptions,
2126
+ until: i64,
2127
+ code: i32,
2128
+ addresses: u8[],
2129
+ fault: HttpClientFault
2130
+ ): i32 => {
2006
2131
  if (count === DNS_RESOLVE_TIMEOUT && until < HTTP_CLIENT_NEVER) {
2007
2132
  fault.fail(
2008
2133
  code,
@@ -2010,6 +2135,14 @@ const httpClientResolve = (
2010
2135
  )
2011
2136
  return -1
2012
2137
  }
2138
+ if (count === HTTP_CLIENT_LOOKUP_WAIT && cancelled()) {
2139
+ fault.fail(HTTP_E_CANCELLED, `the lookup of ${host} was cancelled with its task`)
2140
+ return -1
2141
+ }
2142
+ if (count === HTTP_CLIENT_LOOKUP_WAIT) {
2143
+ fault.fail(HTTP_E_DNS, `${host} could not be looked up (the lookup could not wait on its sockets)`)
2144
+ return -1
2145
+ }
2013
2146
  if (count <= 0) {
2014
2147
  fault.fail(
2015
2148
  HTTP_E_DNS,
@@ -2118,7 +2251,8 @@ export class FetchResponse {
2118
2251
  * place, held by the caller and handed in through `RequestInit.pool`. At
2119
2252
  * most `maxIdlePerOrigin` wait per route and 64 in all; a kept connection
2120
2253
  * the server closed, or sent a byte on unasked, is closed when it is next
2121
- * looked at. A fetch under an outbound policy never keeps or takes one.
2254
+ * looked at. A fetch under an outbound policy never keeps or takes one, and
2255
+ * nor does an https fetch: the pool holds sockets, not their TLS state.
2122
2256
  */
2123
2257
  export class FetchPool {
2124
2258
  /** The most idle connections kept for one route (origin, or proxy). */
@@ -2214,11 +2348,13 @@ export class FetchPool {
2214
2348
 
2215
2349
  /**
2216
2350
  * What an async `fetch` sends and how it behaves. `options` are
2217
- * `HttpOptions` as `fetchSync` reads them, except that `readTimeoutMs`
2218
- * bounds no wait (a wait has no deadline yet), `connectTimeoutMs` bounds
2219
- * only the name lookup, and `totalTimeoutMs` is checked each time a wait
2220
- * ends. `pool` keeps connections for later fetches; null closes each one
2221
- * when its fetch is done.
2351
+ * `HttpOptions` as `fetchSync` reads them, with the same deadlines:
2352
+ * `connectTimeoutMs` bounds the lookup and the connect, `readTimeoutMs`
2353
+ * each wait on the server, and `totalTimeoutMs` the whole fetch, each wait
2354
+ * parked with `readableWithin` or `writableWithin` until the nearest of
2355
+ * them. A fetch whose task is cancelled fails with `HTTP_E_CANCELLED`.
2356
+ * `pool` keeps connections for later fetches; null closes each one when
2357
+ * its fetch is done.
2222
2358
  */
2223
2359
  export class RequestInit {
2224
2360
  /** The request method, sent as given; `GET` by default. */
@@ -2254,6 +2390,67 @@ export class RequestInit {
2254
2390
  }
2255
2391
  }
2256
2392
 
2393
+ /**
2394
+ * Parks the task until `fd` is ready to read (or, with `write`, to write) or
2395
+ * `until` passes: `HTTP_E_NONE` when it is ready, `code` once `until` has
2396
+ * passed, `HTTP_E_CANCELLED` when the task was cancelled, or `HTTP_E_IO`
2397
+ * when the wait itself failed. A deadline past `HTTP_CLIENT_MAX_WAIT_MS` is
2398
+ * waited for in slices of that, so the milliseconds fit an `i32`.
2399
+ */
2400
+ const httpClientWaitAsync = async (fd: i32, write: boolean, until: i64, code: i32): Promise<i32> => {
2401
+ while (true) {
2402
+ let ready: boolean = false
2403
+ let bounded: boolean = false
2404
+ let sliceEnd: i64 = 0
2405
+ if (until >= HTTP_CLIENT_NEVER) {
2406
+ if (write) {
2407
+ ready = await writable(fd)
2408
+ } else {
2409
+ ready = await readable(fd)
2410
+ }
2411
+ } else {
2412
+ const left: i64 = until - monotonicNanos()
2413
+ if (left <= 0) {
2414
+ return code
2415
+ }
2416
+ let ms: i64 = (left + HTTP_CLIENT_NS_PER_MS - 1) / HTTP_CLIENT_NS_PER_MS
2417
+ if (ms > HTTP_CLIENT_MAX_WAIT_MS) {
2418
+ ms = HTTP_CLIENT_MAX_WAIT_MS
2419
+ }
2420
+ bounded = true
2421
+ sliceEnd = monotonicNanos() + ms * HTTP_CLIENT_NS_PER_MS
2422
+ if (write) {
2423
+ ready = await writableWithin(fd, toI32(ms))
2424
+ } else {
2425
+ ready = await readableWithin(fd, toI32(ms))
2426
+ }
2427
+ }
2428
+ if (ready) {
2429
+ return HTTP_E_NONE
2430
+ }
2431
+ if (cancelled()) {
2432
+ return HTTP_E_CANCELLED
2433
+ }
2434
+ if (!bounded || monotonicNanos() < sliceEnd) {
2435
+ // The wait failed before its time was up (a descriptor the poller
2436
+ // refused): waiting again would fail again at once, and spin.
2437
+ return HTTP_E_IO
2438
+ }
2439
+ // The timer fired: the deadline, or one slice of a far one.
2440
+ }
2441
+ }
2442
+
2443
+ /** The sentence for an async wait that ended with `code`; `text` says what timed out. */
2444
+ const httpClientAsyncWaitText = (code: i32, options: HttpOptions, text: string): string => {
2445
+ if (code === HTTP_E_CANCELLED) {
2446
+ return "the fetch's task was cancelled"
2447
+ }
2448
+ if (code === HTTP_E_IO) {
2449
+ return "the wait for the server failed"
2450
+ }
2451
+ return httpClientWaitText(code, options, text)
2452
+ }
2453
+
2257
2454
  /** One connection an async fetch drives, and the state of the exchange on it. */
2258
2455
  class HttpClientConn {
2259
2456
  deadline: i64
@@ -2269,12 +2466,19 @@ class HttpClientConn {
2269
2466
  gotByte: boolean = false
2270
2467
  lost: boolean = false
2271
2468
  reused: boolean = false
2469
+ /** The TLS layer of an https connection; null on a plain one. */
2470
+ tls: TlsRecordClient | null = null
2471
+ /** Where TLS opens records into, before the parser sees them; empty until a handshake starts. */
2472
+ plain: u8[]
2473
+ /** The roots https servers are checked against, read once per fetch, before its first dial. */
2474
+ trust: TlsClientTrust | null = null
2272
2475
 
2273
2476
  constructor(options: HttpOptions) {
2274
2477
  this.options = options
2275
2478
  this.deadline = httpClientDeadline(options)
2276
2479
  this.parser = httpClientParser(options)
2277
2480
  this.rbuf = new Array<u8>(HTTP_CLIENT_READ_BYTES)
2481
+ this.plain = []
2278
2482
  this.fault = new HttpClientFault()
2279
2483
  const proxies: string[] = httpClientEnvProxies(options)
2280
2484
  this.httpProxy = proxies[0]
@@ -2291,19 +2495,29 @@ class HttpClientConn {
2291
2495
  return false
2292
2496
  }
2293
2497
 
2294
- /** Closes the connection, if one is open. */
2498
+ /** Closes the connection, if one is open: an https one with its close_notify, its keys wiped. */
2295
2499
  close(): void {
2500
+ const conn: TlsRecordClient | null = this.tls
2501
+ if (conn !== null) {
2502
+ httpClientTlsClose(conn, this.fd)
2503
+ this.tls = null
2504
+ }
2296
2505
  if (this.fd >= 0) {
2297
2506
  netClose(this.fd)
2298
2507
  this.fd = -1
2299
2508
  }
2300
2509
  }
2301
2510
 
2302
- /** Hands the connection back to `pool` when the response left it clean to reuse, else closes it. */
2511
+ /**
2512
+ * Hands the connection back to `pool` when the response left it clean to
2513
+ * reuse, else closes it. An https connection is never pooled: the pool
2514
+ * keeps fds, and its TLS state lives with this task, so it is closed.
2515
+ */
2303
2516
  release(pool: FetchPool | null): void {
2304
2517
  if (
2305
2518
  pool !== null &&
2306
2519
  this.fd >= 0 &&
2520
+ this.tls === null &&
2307
2521
  this.options.outbound === null &&
2308
2522
  this.parser.keepAlive() &&
2309
2523
  this.parser.buffered() === 0
@@ -2316,34 +2530,249 @@ class HttpClientConn {
2316
2530
  }
2317
2531
  }
2318
2532
 
2319
- /** One read of the response into the parser, parking the task until the socket has bytes; false with the fault set. */
2320
- const httpClientFillAsync = async (conn: HttpClientConn): Promise<boolean> => {
2533
+ /**
2534
+ * Parks the task until `conn`'s socket is ready to read (or, with `write`,
2535
+ * to write), within `readTimeoutMs` and the fetch's deadline: false with the
2536
+ * fault set when the wait timed out, was cancelled or failed.
2537
+ */
2538
+ const httpClientWaitPeerAsync = async (conn: HttpClientConn, write: boolean): Promise<boolean> => {
2539
+ const ms: i32 = conn.options.readTimeoutMs
2540
+ let until: i64 = ms > 0 ? monotonicNanos() + toI64(ms) * HTTP_CLIENT_NS_PER_MS : HTTP_CLIENT_NEVER
2541
+ let code: i32 = HTTP_E_READ_TIMEOUT
2542
+ if (conn.deadline < until) {
2543
+ until = conn.deadline
2544
+ code = HTTP_E_TOTAL_TIMEOUT
2545
+ }
2546
+ const waited = await httpClientWaitAsync(conn.fd, write, until, code)
2547
+ if (waited === HTTP_E_NONE) {
2548
+ return true
2549
+ }
2550
+ const what: string = write ? "took" : "sent"
2551
+ conn.fault.fail(
2552
+ waited,
2553
+ httpClientAsyncWaitText(waited, conn.options, `the server ${what} nothing for ${ms} ms`)
2554
+ )
2555
+ return false
2556
+ }
2557
+
2558
+ /**
2559
+ * One read of up to `want` bytes from the socket into `rbuf`, parking the
2560
+ * task until it has some: the count, 0 at the end of the stream, or -1 with
2561
+ * the fault set.
2562
+ */
2563
+ const httpClientReadRawAsync = async (conn: HttpClientConn, want: i32): Promise<i32> => {
2321
2564
  if (conn.overdue()) {
2322
- return false
2565
+ return -1
2323
2566
  }
2324
- let n: i32 = netRead(conn.fd, conn.rbuf, HTTP_CLIENT_ZERO, HTTP_CLIENT_READ_BYTES)
2567
+ let n: i32 = netRead(conn.fd, conn.rbuf, HTTP_CLIENT_ZERO, want)
2325
2568
  while (n === HTTP_CLIENT_WOULD_BLOCK) {
2326
- const ready = await readable(conn.fd)
2569
+ const ready = await httpClientWaitPeerAsync(conn, false)
2327
2570
  if (!ready) {
2328
- conn.fault.fail(HTTP_E_IO, "the wait for the server failed")
2329
- return false
2571
+ return -1
2572
+ }
2573
+ if (conn.overdue()) {
2574
+ return -1
2330
2575
  }
2576
+ n = netRead(conn.fd, conn.rbuf, HTTP_CLIENT_ZERO, want)
2577
+ }
2578
+ if (n < 0) {
2579
+ conn.lost = true
2580
+ conn.fault.fail(HTTP_E_IO, `reading from the server failed (errno ${-n})`)
2581
+ return -1
2582
+ }
2583
+ return n
2584
+ }
2585
+
2586
+ /** Writes `bytes[off, off + len)` to the socket, parking the task while it is full; false with the fault set. */
2587
+ const httpClientWriteRawAsync = async (
2588
+ conn: HttpClientConn,
2589
+ bytes: u8[],
2590
+ off: i32,
2591
+ len: i32
2592
+ ): Promise<boolean> => {
2593
+ let at: i32 = off
2594
+ const end: i32 = off + len
2595
+ while (at < end) {
2331
2596
  if (conn.overdue()) {
2332
2597
  return false
2333
2598
  }
2334
- n = netRead(conn.fd, conn.rbuf, HTTP_CLIENT_ZERO, HTTP_CLIENT_READ_BYTES)
2599
+ const n: i32 = netWrite(conn.fd, bytes, at, end - at)
2600
+ if (n > 0) {
2601
+ at += n
2602
+ } else if (n === HTTP_CLIENT_WOULD_BLOCK || n === 0) {
2603
+ const ready = await httpClientWaitPeerAsync(conn, true)
2604
+ if (!ready) {
2605
+ return false
2606
+ }
2607
+ } else {
2608
+ conn.lost = true
2609
+ conn.fault.fail(HTTP_E_IO, `writing to the server failed (errno ${-n})`)
2610
+ return false
2611
+ }
2612
+ }
2613
+ return true
2614
+ }
2615
+
2616
+ /** Feeds `tls` the next bytes the server sent, or the end of its stream; false with the fault set. */
2617
+ const httpClientReceiveTlsAsync = async (conn: HttpClientConn, tls: TlsRecordClient): Promise<boolean> => {
2618
+ const room: i32 = tls.space()
2619
+ const want: i32 = room < HTTP_CLIENT_READ_BYTES ? room : HTTP_CLIENT_READ_BYTES
2620
+ if (want <= 0) {
2621
+ conn.fault.fail(HTTP_E_TLS, "the TLS connection has no room for the server's next record")
2622
+ return false
2623
+ }
2624
+ const n = await httpClientReadRawAsync(conn, want)
2625
+ if (n < 0) {
2626
+ tls.abort()
2627
+ return false
2628
+ }
2629
+ if (n === 0) {
2630
+ // Before the server's close_notify this is truncation, which fails `tls`.
2631
+ tls.end()
2632
+ } else {
2633
+ tls.receive(conn.rbuf, HTTP_CLIENT_ZERO, n)
2634
+ }
2635
+ return true
2636
+ }
2637
+
2638
+ /** Sends everything `tls` has sealed, parking the task while the socket is full; false with the fault set. */
2639
+ const httpClientFlushTlsAsync = async (conn: HttpClientConn, tls: TlsRecordClient): Promise<boolean> => {
2640
+ while (tls.outputEnd > tls.outputStart) {
2641
+ const len: i32 = tls.outputEnd - tls.outputStart
2642
+ const wrote = await httpClientWriteRawAsync(conn, tls.output, tls.outputStart, len)
2643
+ if (!wrote) {
2644
+ tls.abort()
2645
+ return false
2646
+ }
2647
+ tls.consume(len)
2648
+ }
2649
+ return true
2650
+ }
2651
+
2652
+ /**
2653
+ * Runs the TLS handshake for `host` on the connected socket, `early` being
2654
+ * bytes already read past a proxy's CONNECT answer: the server's chain is
2655
+ * checked as `fetchSync` checks it. False with the fault set.
2656
+ */
2657
+ const httpClientSecureAsync = async (conn: HttpClientConn, host: string, early: u8[]): Promise<boolean> => {
2658
+ const trust: TlsClientTrust | null = conn.trust
2659
+ if (trust === null) {
2660
+ conn.fault.fail(HTTP_E_CERTIFICATE, "no trusted root certificates are loaded")
2661
+ return false
2662
+ }
2663
+ const tls: TlsRecordClient = httpClientTlsStart(host, early)
2664
+ conn.tls = tls
2665
+ if (toI32(conn.plain.length) === 0) {
2666
+ conn.plain = new Array<u8>(HTTP_CLIENT_READ_BYTES)
2667
+ }
2668
+ while (httpClientTlsOpening(tls)) {
2669
+ if (!httpClientTlsVerify(tls, trust, host, conn.fault)) {
2670
+ return false
2671
+ }
2672
+ let moved: boolean = false
2673
+ if (tls.outputEnd > tls.outputStart) {
2674
+ moved = await httpClientFlushTlsAsync(conn, tls)
2675
+ } else {
2676
+ moved = await httpClientReceiveTlsAsync(conn, tls)
2677
+ }
2678
+ if (!moved) {
2679
+ return false
2680
+ }
2681
+ }
2682
+ return true
2683
+ }
2684
+
2685
+ /**
2686
+ * Asks `proxy`, on the fresh socket, for a tunnel to `host:port`. True once
2687
+ * the proxy answers 2xx, every byte after its head belonging to the tunnel.
2688
+ */
2689
+ const httpClientTunnelAsync = async (
2690
+ conn: HttpClientConn,
2691
+ host: string,
2692
+ port: i32,
2693
+ proxy: Url
2694
+ ): Promise<boolean> => {
2695
+ const head: u8[] | null = httpClientConnectHead(host, port, proxy, conn.fault)
2696
+ if (head === null) {
2697
+ return false
2698
+ }
2699
+ conn.gotByte = false
2700
+ conn.parser.expect(false, true)
2701
+ const wrote = await httpClientWriteRawAsync(conn, head, HTTP_CLIENT_ZERO, toI32(head.length))
2702
+ if (!wrote) {
2703
+ return false
2704
+ }
2705
+ let event: i32 = await httpClientPumpAsync(conn)
2706
+ while (event === HTTP1_INFORMATIONAL) {
2707
+ event = await httpClientPumpAsync(conn)
2708
+ }
2709
+ if (event < 0) {
2710
+ return false
2711
+ }
2712
+ if (event !== HTTP1_HEAD) {
2713
+ conn.fault.fail(HTTP_E_PROTOCOL, `the response ended before its head (event ${event})`)
2714
+ return false
2715
+ }
2716
+ const status: i32 = conn.parser.status
2717
+ if (status < 200 || status > 299) {
2718
+ conn.fault.fail(
2719
+ HTTP_E_PROXY_REFUSED,
2720
+ `the proxy answered CONNECT ${httpClientHostText(host)}:${port} with ${status}`
2721
+ )
2722
+ return false
2335
2723
  }
2336
- if (n > 0) {
2724
+ // A 2xx has no body: the parser ends it, then reports the tunnel.
2725
+ event = await httpClientPumpAsync(conn)
2726
+ while (event >= 0 && event !== HTTP1_UPGRADE) {
2727
+ event = await httpClientPumpAsync(conn)
2728
+ }
2729
+ return event === HTTP1_UPGRADE
2730
+ }
2731
+
2732
+ /**
2733
+ * One read of the response into the parser, through TLS on an https
2734
+ * connection, parking the task until the socket has bytes; false with the
2735
+ * fault set. Over TLS the stream ends only at the server's close_notify.
2736
+ */
2737
+ const httpClientFillAsync = async (conn: HttpClientConn): Promise<boolean> => {
2738
+ const tls: TlsRecordClient | null = conn.tls
2739
+ if (tls === null) {
2740
+ const n = await httpClientReadRawAsync(conn, HTTP_CLIENT_READ_BYTES)
2741
+ if (n > 0) {
2742
+ conn.gotByte = true
2743
+ conn.parser.feed(conn.rbuf, HTTP_CLIENT_ZERO, n)
2744
+ } else if (n === 0) {
2745
+ conn.parser.finish()
2746
+ }
2747
+ return n >= 0
2748
+ }
2749
+ if (conn.overdue()) {
2750
+ return false
2751
+ }
2752
+ let got: i32 = tls.read(conn.plain, HTTP_CLIENT_ZERO, toI32(conn.plain.length))
2753
+ while (got === TLS_RECORD_AGAIN) {
2754
+ const flushed = await httpClientFlushTlsAsync(conn, tls)
2755
+ if (!flushed) {
2756
+ return false
2757
+ }
2758
+ const received = await httpClientReceiveTlsAsync(conn, tls)
2759
+ if (!received) {
2760
+ return false
2761
+ }
2762
+ got = tls.read(conn.plain, HTTP_CLIENT_ZERO, toI32(conn.plain.length))
2763
+ }
2764
+ if (got > 0) {
2337
2765
  conn.gotByte = true
2338
- conn.parser.feed(conn.rbuf, HTTP_CLIENT_ZERO, n)
2766
+ conn.parser.feed(conn.plain, HTTP_CLIENT_ZERO, got)
2339
2767
  return true
2340
2768
  }
2341
- if (n === 0) {
2769
+ if (got === 0) {
2770
+ // The server's close_notify: the orderly end of its stream.
2342
2771
  conn.parser.finish()
2343
2772
  return true
2344
2773
  }
2345
2774
  conn.lost = true
2346
- conn.fault.fail(HTTP_E_IO, `reading from the server failed (errno ${-n})`)
2775
+ httpClientTlsFault(tls, conn.fault)
2347
2776
  return false
2348
2777
  }
2349
2778
 
@@ -2364,36 +2793,138 @@ const httpClientPumpAsync = async (conn: HttpClientConn): Promise<i32> => {
2364
2793
  return event
2365
2794
  }
2366
2795
 
2367
- /** Writes `bytes`, parking the task while the socket is full; false with the fault set. */
2796
+ /** Writes `bytes`, through TLS on an https connection, parking the task while the socket is full; false with the fault set. */
2368
2797
  const httpClientWriteAsync = async (conn: HttpClientConn, bytes: u8[]): Promise<boolean> => {
2798
+ const tls: TlsRecordClient | null = conn.tls
2799
+ if (tls === null) {
2800
+ const wrote = await httpClientWriteRawAsync(conn, bytes, HTTP_CLIENT_ZERO, toI32(bytes.length))
2801
+ return wrote
2802
+ }
2369
2803
  let at: i32 = 0
2370
2804
  const end: i32 = toI32(bytes.length)
2371
2805
  while (at < end) {
2372
- if (conn.overdue()) {
2373
- return false
2374
- }
2375
- const n: i32 = netWrite(conn.fd, bytes, at, end - at)
2806
+ const n: i32 = tls.write(bytes, at, end - at)
2376
2807
  if (n > 0) {
2377
2808
  at += n
2378
- } else if (n === HTTP_CLIENT_WOULD_BLOCK || n === 0) {
2379
- const ready = await writable(conn.fd)
2380
- if (!ready) {
2381
- conn.fault.fail(HTTP_E_IO, "the wait for the server failed")
2382
- return false
2383
- }
2384
- } else {
2809
+ } else if (n !== TLS_RECORD_AGAIN || tls.outputEnd === tls.outputStart) {
2385
2810
  conn.lost = true
2386
- conn.fault.fail(HTTP_E_IO, `writing to the server failed (errno ${-n})`)
2811
+ httpClientTlsFault(tls, conn.fault)
2812
+ return false
2813
+ }
2814
+ const flushed = await httpClientFlushTlsAsync(conn, tls)
2815
+ if (!flushed) {
2387
2816
  return false
2388
2817
  }
2389
2818
  }
2390
- return true
2819
+ const done = await httpClientFlushTlsAsync(conn, tls)
2820
+ return done
2391
2821
  }
2392
2822
 
2393
2823
  /**
2394
- * Looks `host` up (blocking, within `connectTimeoutMs`) and connects to its
2395
- * addresses in turn, parking the task while each connect is in flight: the
2396
- * connected fd, or -1 with the fault set.
2824
+ * Looks `host` up without blocking the process: a `DnsClient` on its own
2825
+ * poll loop, with `dns` (or the system's resolv.conf) and the hosts file, sends the queries
2826
+ * over non-blocking sockets and the task sleeps between non-blocking checks
2827
+ * of that loop, a slice that grows from 1 ms to `HTTP_CLIENT_DNS_SLICE_MS`
2828
+ * and never passes the resolver's next retry. No network wait blocks; the
2829
+ * hosts file (and resolv.conf, when `dns` is null) is read synchronously,
2830
+ * once per lookup, as `resolveHost` reads them. An address literal (ASCII
2831
+ * only, as the resolver's own check) is parsed here, with no resolver and
2832
+ * no file read; localhost or a hosts entry answers without a query. Past `until` the lookup is cancelled
2833
+ * and answers `DNS_RESOLVE_TIMEOUT`. `readable` on the loop is not used: it
2834
+ * has no deadline, and a lookup must stop at `until` even when nothing comes.
2835
+ *
2836
+ * @returns The resolver's answer, as `resolveHost`'s, into `addresses` and
2837
+ * `ttls`, or `HTTP_CLIENT_LOOKUP_WAIT` when the lookup could not wait.
2838
+ */
2839
+ const httpClientLookupAsync = async (
2840
+ host: string,
2841
+ port: i32,
2842
+ dns: DnsConfig | null,
2843
+ until: i64,
2844
+ addresses: u8[],
2845
+ ttls: i32[]
2846
+ ): Promise<i32> => {
2847
+ let high: i32 = 0
2848
+ const name: u8[] = new Array<u8>(host.length)
2849
+ for (let i: i32 = 0; i < toI32(host.length); i += 1) {
2850
+ const c: i32 = toI32(host.charCodeAt(i))
2851
+ high = high | c
2852
+ if (i < toI32(name.length)) {
2853
+ name[i] = toU8(c & 0x7f)
2854
+ }
2855
+ }
2856
+ if (high <= 127 && dnsParseAddress(name, 0, toI32(name.length), addresses, 0, port)) {
2857
+ ttls[0] = 0
2858
+ return 1
2859
+ }
2860
+ const hosts: DnsHosts = new DnsHosts()
2861
+ let config: DnsConfig = new DnsConfig()
2862
+ if (dns !== null) {
2863
+ dnsLoadSystem(null, hosts)
2864
+ config = dns
2865
+ } else {
2866
+ dnsLoadSystem(config, hosts)
2867
+ }
2868
+ const loop: i32 = pollCreate()
2869
+ if (loop < 0) {
2870
+ return HTTP_CLIENT_LOOKUP_WAIT
2871
+ }
2872
+ const client: DnsClient = new DnsClient(new DnsResolver(config, hosts, 1), loop, 0)
2873
+ const lookup: i32 = client.start(host, port, monotonicNanos())
2874
+ if (lookup < 0) {
2875
+ netClose(loop)
2876
+ return lookup
2877
+ }
2878
+ const ready: i32[] = new Array<i32>(8)
2879
+ let slice: i32 = 1
2880
+ let status: i32 = client.result(lookup, addresses, ttls)
2881
+ while (status === DNS_RESOLVE_PENDING) {
2882
+ const now: i64 = monotonicNanos()
2883
+ if (now >= until) {
2884
+ client.cancel(lookup, now)
2885
+ status = DNS_RESOLVE_TIMEOUT
2886
+ break
2887
+ }
2888
+ let own: i32 = slice
2889
+ if (until < HTTP_CLIENT_NEVER) {
2890
+ const left: i64 = (until - now + HTTP_CLIENT_NS_PER_MS - toI64(1)) / HTTP_CLIENT_NS_PER_MS
2891
+ if (left < toI64(own)) {
2892
+ own = toI32(left)
2893
+ }
2894
+ }
2895
+ const wait: i32 = client.timeoutMs(now, own)
2896
+ if (wait > 0) {
2897
+ const slept = await sleep(wait)
2898
+ if (!slept) {
2899
+ client.cancel(lookup, monotonicNanos())
2900
+ status = HTTP_CLIENT_LOOKUP_WAIT
2901
+ break
2902
+ }
2903
+ }
2904
+ const count: i32 = pollWait(loop, ready, 0)
2905
+ const after: i64 = monotonicNanos()
2906
+ if (count < 0) {
2907
+ client.cancel(lookup, after)
2908
+ status = HTTP_CLIENT_LOOKUP_WAIT
2909
+ break
2910
+ }
2911
+ for (let k: i32 = 0; k < count && 2 * k + 1 < toI32(ready.length); k += 1) {
2912
+ if (client.owns(ready[2 * k])) {
2913
+ client.ready(ready[2 * k], ready[2 * k + 1], after)
2914
+ }
2915
+ }
2916
+ client.tick(after)
2917
+ status = client.result(lookup, addresses, ttls)
2918
+ slice = slice * 2 < HTTP_CLIENT_DNS_SLICE_MS ? slice * 2 : HTTP_CLIENT_DNS_SLICE_MS
2919
+ }
2920
+ netClose(loop)
2921
+ return status
2922
+ }
2923
+
2924
+ /**
2925
+ * Looks `host` up within `connectTimeoutMs` and connects to its addresses in
2926
+ * turn, parking the task while the lookup and each connect are in flight:
2927
+ * the connected fd, or -1 with the fault set.
2397
2928
  */
2398
2929
  const httpClientDialAsync = async (conn: HttpClientConn, host: string, port: i32): Promise<i32> => {
2399
2930
  const start: i64 = monotonicNanos()
@@ -2409,7 +2940,9 @@ const httpClientDialAsync = async (conn: HttpClientConn, host: string, port: i32
2409
2940
  return -1
2410
2941
  }
2411
2942
  const addresses: u8[] = new Array<u8>(DNS_RESOLVE_MAX_ADDRESSES * DNS_ADDRESS_BYTES)
2412
- const usable: i32 = httpClientResolve(host, port, conn.options, start, until, code, addresses, conn.fault)
2943
+ const ttls: i32[] = new Array<i32>(DNS_RESOLVE_MAX_ADDRESSES)
2944
+ const count = await httpClientLookupAsync(host, port, conn.options.dns, until, addresses, ttls)
2945
+ const usable: i32 = httpClientAnswers(host, count, conn.options, until, code, addresses, conn.fault)
2413
2946
  if (usable < 0) {
2414
2947
  return -1
2415
2948
  }
@@ -2422,12 +2955,20 @@ const httpClientDialAsync = async (conn: HttpClientConn, host: string, port: i32
2422
2955
  last = fd
2423
2956
  continue
2424
2957
  }
2425
- const ready = await writable(fd)
2426
- if (conn.overdue()) {
2958
+ const waited = await httpClientWaitAsync(fd, true, until, code)
2959
+ if (waited !== HTTP_E_NONE) {
2427
2960
  netClose(fd)
2961
+ conn.fault.fail(
2962
+ waited,
2963
+ httpClientAsyncWaitText(
2964
+ waited,
2965
+ conn.options,
2966
+ `no address of ${host} answered on port ${port} within ${budget} ms`
2967
+ )
2968
+ )
2428
2969
  return -1
2429
2970
  }
2430
- const result: i32 = ready ? connectResult(fd) : -5
2971
+ const result: i32 = connectResult(fd)
2431
2972
  if (result === 0) {
2432
2973
  return fd
2433
2974
  }
@@ -2440,9 +2981,9 @@ const httpClientDialAsync = async (conn: HttpClientConn, host: string, port: i32
2440
2981
 
2441
2982
  /**
2442
2983
  * Makes `conn` a connection to where `url` goes: one the pool kept when
2443
- * there is one, else a new one, through an http proxy when the settings say
2444
- * so. False with the fault set; an https URL is refused before anything is
2445
- * dialled, since its TLS handshake would block the process.
2984
+ * there is one, else a new one, through a proxy when the settings say so.
2985
+ * An https URL gets a TLS handshake, tunnelled through an https proxy's
2986
+ * CONNECT, and is never taken from the pool. False with the fault set.
2446
2987
  */
2447
2988
  const httpClientOpenAsync = async (
2448
2989
  conn: HttpClientConn,
@@ -2450,13 +2991,7 @@ const httpClientOpenAsync = async (
2450
2991
  pool: FetchPool | null,
2451
2992
  fresh: boolean
2452
2993
  ): Promise<boolean> => {
2453
- if (url.scheme === "https") {
2454
- conn.fault.fail(
2455
- HTTP_E_TLS,
2456
- `${httpClientRedact(url)} is https, which the async fetch does not drive yet; use fetchSync`
2457
- )
2458
- return false
2459
- }
2994
+ const secure: boolean = url.scheme === "https"
2460
2995
  const way: HttpClientRoute | null = httpClientRoute(
2461
2996
  url,
2462
2997
  conn.options,
@@ -2471,7 +3006,7 @@ const httpClientOpenAsync = async (
2471
3006
  conn.route = way.route
2472
3007
  conn.parser = httpClientParser(conn.options)
2473
3008
  conn.reused = false
2474
- if (pool !== null && !fresh && conn.options.outbound === null) {
3009
+ if (pool !== null && !fresh && !secure && conn.options.outbound === null) {
2475
3010
  const kept: i32 = pool.take(way.route)
2476
3011
  if (kept >= 0) {
2477
3012
  conn.fd = kept
@@ -2479,11 +3014,37 @@ const httpClientOpenAsync = async (
2479
3014
  return true
2480
3015
  }
2481
3016
  }
3017
+ // The roots come first, so a fetch with none never reaches the network.
3018
+ if (secure && conn.trust === null) {
3019
+ conn.trust = httpClientLoadTrust(conn.options, conn.fault)
3020
+ if (conn.trust === null) {
3021
+ return false
3022
+ }
3023
+ }
2482
3024
  const fd: i32 = await httpClientDialAsync(conn, way.dialHost, way.dialPort)
2483
3025
  if (fd < 0) {
2484
3026
  return false
2485
3027
  }
2486
3028
  conn.fd = fd
3029
+ if (!secure) {
3030
+ return true
3031
+ }
3032
+ let early: u8[] = []
3033
+ const proxy: Url | null = way.proxy
3034
+ if (proxy !== null) {
3035
+ const tunnelled = await httpClientTunnelAsync(conn, url.host, way.port, proxy)
3036
+ if (!tunnelled) {
3037
+ conn.close()
3038
+ return false
3039
+ }
3040
+ early = conn.parser.tunnelBytes()
3041
+ conn.parser = httpClientParser(conn.options)
3042
+ }
3043
+ const secured = await httpClientSecureAsync(conn, url.host, early)
3044
+ if (!secured) {
3045
+ conn.close()
3046
+ return false
3047
+ }
2487
3048
  return true
2488
3049
  }
2489
3050
 
@@ -2680,12 +3241,13 @@ const httpClientFetchAsync = async (
2680
3241
  * Fetches `url` without blocking the process: the task waits on the
2681
3242
  * executor while the connection is made, the request written and the
2682
3243
  * response read, so other tasks run meanwhile and `awaitAll(fetch(a),
2683
- * fetch(b))` overlaps the two. The body is read whole, up to
2684
- * `maxBodyBytes`, before the answer comes. Only http is driven this way: an
2685
- * https URL answers `HTTP_E_TLS` (use `fetchSync`). The name lookup still
2686
- * blocks. Policy, proxy, redirect and error rules are `fetchSync`'s.
3244
+ * fetch(b))` overlaps the two. The name lookup does not block either: it
3245
+ * runs on non-blocking sockets within `connectTimeoutMs`. An https URL gets
3246
+ * the TLS handshake and checks `fetchSync` gives it. The body is read whole,
3247
+ * up to `maxBodyBytes`, before the answer comes. Policy, proxy, redirect and
3248
+ * error rules are `fetchSync`'s.
2687
3249
  *
2688
- * @param url The absolute `http://` URL to fetch.
3250
+ * @param url The absolute `http://` or `https://` URL to fetch.
2689
3251
  * @param init The method, fields, body, options and pool; null for a plain `GET`.
2690
3252
  * @returns The response with its body, or the failure: never a panic.
2691
3253
  */