@amritk/nish-aarch64-linux 0.36.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/INSTALL.md +92 -71
- package/bin/nish +0 -0
- package/docs/AI.md +75 -14
- package/package.json +1 -1
- package/runtime/async.d.mts +2 -0
- package/runtime/async.mjs +7 -0
- package/runtime/core/arrays.d.ts +4 -0
- package/runtime/core/arrays.mjs +33 -0
- package/runtime/nish.d.ts +1045 -512
- package/runtime/nish.h +53 -6
- package/runtime/page.d.ts +53 -0
- package/runtime/page.mjs +146 -0
- package/runtime/runtime-async.c +740 -0
- package/runtime/runtime-cross.c +2 -1
- package/runtime/runtime-region.c +85 -7
- package/runtime/runtime-text.c +1068 -0
- package/runtime/runtime-wasm.c +65 -9
- package/runtime/runtime.c +50 -961
- package/runtime/vite.mjs +48 -11
- package/scripts/build.sh +231 -31
- package/std/LICENSE-fdlibm +8 -0
- package/std/README.md +109 -82
- package/std/array.ts +266 -0
- package/std/bytes.ts +23 -19
- package/std/compress/checksum.ts +1 -1
- package/std/crypto/aes.ts +48 -43
- package/std/crypto/base64url.ts +7 -5
- package/std/crypto/bcrypt-batch.ts +13 -13
- package/std/crypto/bcrypt.ts +33 -27
- package/std/crypto/chacha20poly1305.ts +16 -14
- package/std/crypto/ed25519.ts +19 -16
- package/std/crypto/hmac.ts +7 -6
- package/std/crypto/jwt.ts +23 -20
- package/std/crypto/p256.ts +63 -56
- package/std/crypto/p384.ts +23 -20
- package/std/crypto/pki.ts +18 -15
- package/std/crypto/rsa.ts +23 -19
- package/std/crypto/x25519.ts +11 -10
- package/std/crypto/x509.ts +69 -62
- package/std/host/ring.ts +124 -0
- package/std/host/text.ts +86 -0
- package/std/json-equal.ts +12 -11
- package/std/json-number.ts +12 -12
- package/std/json-tokenizer.ts +26 -22
- package/std/json-typed.ts +92 -78
- package/std/json-value.ts +38 -33
- package/std/json.ts +32 -28
- package/std/math.ts +743 -41
- package/std/net/dns-resolver.ts +46 -6
- package/std/net/dns.ts +50 -13
- package/std/net/fetch.ts +1744 -295
- package/std/net/handler.ts +30 -0
- package/std/net/hpack.ts +29 -26
- package/std/net/http-compress.ts +42 -28
- package/std/net/http-fields.ts +19 -4
- package/std/net/http1-client-codec.ts +29 -25
- package/std/net/http1-codec.ts +62 -91
- package/std/net/http1-server.ts +79 -57
- package/std/net/http2-frame.ts +17 -16
- package/std/net/http2-tls.ts +17 -15
- package/std/net/http2.ts +67 -54
- package/std/net/http3-frame.ts +11 -10
- package/std/net/http3-server.ts +36 -35
- package/std/net/http3.ts +70 -58
- package/std/net/postgres-async.ts +1005 -0
- package/std/net/postgres.ts +185 -164
- package/std/net/prefork.ts +38 -34
- package/std/net/qpack.ts +15 -14
- package/std/net/quic-conn-ack.ts +1 -0
- package/std/net/quic-conn-cid.ts +11 -0
- package/std/net/quic-conn-params.ts +41 -14
- package/std/net/quic-datagram.ts +7 -0
- package/std/net/quic-frame.ts +48 -12
- package/std/net/quic-listener.ts +61 -44
- package/std/net/quic-packet.ts +71 -52
- package/std/net/quic-recovery.ts +59 -21
- package/std/net/quic-stream.ts +83 -55
- package/std/net/quic.ts +204 -152
- package/std/net/serve.ts +763 -0
- package/std/net/tls/client.ts +1 -0
- package/std/net/tls/codec.ts +81 -12
- package/std/net/tls/record-client.ts +30 -18
- package/std/net/tls/record-server.ts +74 -46
- package/std/net/tls/record.ts +33 -24
- package/std/net/tls/ticket.ts +2 -0
- package/std/net/tls/verify.ts +8 -7
- package/std/net/tls-tcp.ts +58 -50
- package/std/net/tls.ts +55 -43
- package/std/net/url.ts +12 -9
- package/std/net/websocket.ts +23 -19
- package/std/net/webtransport.ts +24 -18
- package/std/random.ts +8 -6
- package/std/regex.ts +70 -59
- package/std/sync/ring.ts +24 -21
- package/std/sync/shm.ts +9 -7
- package/std/term-io.ts +17 -14
- package/std/term-probe.ts +11 -10
- package/std/term-rate.ts +71 -61
- package/std/term.ts +73 -59
- package/std/text.ts +242 -15
- package/std/threads.ts +19 -15
- package/std/yaml-json.ts +17 -15
- package/std/yaml-write.ts +21 -14
package/std/net/fetch.ts
CHANGED
|
@@ -1,8 +1,30 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `nish/net/fetch` —
|
|
3
|
-
* programs:
|
|
2
|
+
* `nish/net/fetch` — an HTTP/1.1 client. `fetchSync(request, options)` is the
|
|
3
|
+
* blocking one for command-line programs: it dials, sends, and answers the
|
|
4
4
|
* response's head with a reader for its body, and a `FetchSyncClient` does the
|
|
5
|
-
* same while keeping one connection alive between fetches.
|
|
5
|
+
* same while keeping one connection alive between fetches. `await fetch(url,
|
|
6
|
+
* init)` is the async one: it parks its task on `nish:async` instead of the
|
|
7
|
+
* thread, so `awaitAll(fetch(a), fetch(b))` overlaps the two.
|
|
8
|
+
*
|
|
9
|
+
* import { fetch } from "nish/net/fetch";
|
|
10
|
+
*
|
|
11
|
+
* const r = await fetch("http://127.0.0.1:8080/health");
|
|
12
|
+
* if (r.isOk()) {
|
|
13
|
+
* const body: string = r.value.text();
|
|
14
|
+
* }
|
|
15
|
+
*
|
|
16
|
+
* **The async `fetch`** answers a `Result`: a `FetchResponse` whose body was
|
|
17
|
+
* read whole before it answered (up to `maxBodyBytes`, 256 MiB by default,
|
|
18
|
+
* else `HTTP_E_BODY_TOO_LARGE`), or a `FetchError` with the `HTTP_E_*` code.
|
|
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.
|
|
26
|
+
* Policy, proxies, redirects and error codes are the shared code below, so
|
|
27
|
+
* both clients behave alike. It does not run under `--emit-ts`.
|
|
6
28
|
*
|
|
7
29
|
* import { HttpOptions, HttpRequest, HttpResponse, fetchSync } from "nish/net/fetch";
|
|
8
30
|
*
|
|
@@ -80,9 +102,15 @@ import {
|
|
|
80
102
|
} from "nish/net/http1-client-codec"
|
|
81
103
|
import { httpFieldBytes } from "nish/net/http-fields"
|
|
82
104
|
import { Url, urlDecode, urlDefaultPort, urlOrigin, urlParse, urlResolve } from "nish/net/url"
|
|
83
|
-
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"
|
|
84
107
|
import { DNS_ADDRESS_BYTES } from "nish/net/dns-message"
|
|
85
|
-
import {
|
|
108
|
+
import {
|
|
109
|
+
DNS_RESOLVE_MAX_ADDRESSES,
|
|
110
|
+
DNS_RESOLVE_PENDING,
|
|
111
|
+
DNS_RESOLVE_TIMEOUT,
|
|
112
|
+
DnsResolver,
|
|
113
|
+
} from "nish/net/dns-resolver"
|
|
86
114
|
import { OutboundPolicy, outboundAddressText, outboundFilter, outboundHostAllowed } from "nish/net/outbound"
|
|
87
115
|
import {
|
|
88
116
|
connectResult,
|
|
@@ -96,6 +124,7 @@ import {
|
|
|
96
124
|
pollWait,
|
|
97
125
|
tcpConnect,
|
|
98
126
|
} from "nish:net"
|
|
127
|
+
import { cancelled, readable, readableWithin, sleep, writable, writableWithin } from "nish:async"
|
|
99
128
|
import { getenv, monotonicNanos, wallClockNanos } from "nish:process"
|
|
100
129
|
import { PkiRoots, pkiLoadRoots, pkiLoadSystemRoots } from "nish/crypto/pki-roots"
|
|
101
130
|
import { TlsClient, TlsClientConfig, tlsClientIsIpLiteral } from "nish/net/tls/client"
|
|
@@ -139,6 +168,8 @@ export const HTTP_E_IO: i32 = 15
|
|
|
139
168
|
export const HTTP_E_PROXY: i32 = 16
|
|
140
169
|
/** The outbound policy refused the URL's host or every address it resolved to. */
|
|
141
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
|
|
142
173
|
|
|
143
174
|
/** A typed zero: a bare literal is an `f64` under `--number-mode f64`. */
|
|
144
175
|
const HTTP_CLIENT_ZERO: i32 = 0
|
|
@@ -157,6 +188,8 @@ const HTTP_CLIENT_PROXY_PORT: i32 = 1080
|
|
|
157
188
|
const HTTP_CLIENT_MAX_WAIT_MS: i64 = 3600000
|
|
158
189
|
/** Nanoseconds in a millisecond. */
|
|
159
190
|
const HTTP_CLIENT_NS_PER_MS: i64 = 1000000
|
|
191
|
+
/** The largest body the async fetch can hold in one array, whatever `maxBodyBytes` says. */
|
|
192
|
+
const HTTP_CLIENT_ASYNC_BODY_MAX: i64 = 2147483647
|
|
160
193
|
/** A deadline that never comes: 146 years of monotonic nanoseconds, far below the overflow of a sum with a timeout. */
|
|
161
194
|
const HTTP_CLIENT_NEVER: i64 = 4611686018 * 1000000000
|
|
162
195
|
/** netRead's and netWrite's answer when the socket has nothing ready. */
|
|
@@ -166,6 +199,14 @@ const HTTP_CLIENT_READABLE: i32 = 1
|
|
|
166
199
|
const HTTP_CLIENT_WRITABLE: i32 = 2
|
|
167
200
|
/** The size of the client random and of each ephemeral private key a TLS handshake draws. */
|
|
168
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
|
|
169
210
|
|
|
170
211
|
/**
|
|
171
212
|
* A short name for an `HTTP_E_*` code, for messages: "dns", "read timeout",
|
|
@@ -195,6 +236,7 @@ export const httpErrorName = (code: i32): string => {
|
|
|
195
236
|
"io",
|
|
196
237
|
"proxy",
|
|
197
238
|
"blocked",
|
|
239
|
+
"cancelled",
|
|
198
240
|
]
|
|
199
241
|
return code >= 0 && code < toI32(names.length) ? names[code] : "unknown"
|
|
200
242
|
}
|
|
@@ -259,6 +301,12 @@ export class HttpOptions {
|
|
|
259
301
|
* `nish/net/outbound`). Null for none.
|
|
260
302
|
*/
|
|
261
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
|
|
262
310
|
/** The budget for the lookup and the connect together; 0 or less for none but the total. */
|
|
263
311
|
connectTimeoutMs: i32 = 10000
|
|
264
312
|
/** The longest wait for the server to send or take a byte; 0 or less for none. */
|
|
@@ -312,13 +360,7 @@ export class HttpResponse {
|
|
|
312
360
|
* @returns The value, or null when the response has no such field.
|
|
313
361
|
*/
|
|
314
362
|
header(name: string): string | null {
|
|
315
|
-
|
|
316
|
-
for (let i: i32 = 0; i < toI32(this.names.length) && i < toI32(this.values.length); i += 1) {
|
|
317
|
-
if (this.names[i] === lower) {
|
|
318
|
-
return this.values[i]
|
|
319
|
-
}
|
|
320
|
-
}
|
|
321
|
-
return null
|
|
363
|
+
return httpClientField(this.names, this.values, name)
|
|
322
364
|
}
|
|
323
365
|
}
|
|
324
366
|
|
|
@@ -480,12 +522,10 @@ export class FetchSyncClient {
|
|
|
480
522
|
this.ready = new Array<i32>(8)
|
|
481
523
|
this.rbuf = new Array<u8>(HTTP_CLIENT_READ_BYTES)
|
|
482
524
|
this.plain = []
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
this.noProxy = httpChooseProxy(getenv("no_proxy"), getenv("NO_PROXY"), true)
|
|
488
|
-
}
|
|
525
|
+
const proxies: string[] = httpClientEnvProxies(options)
|
|
526
|
+
this.httpProxy = proxies[0]
|
|
527
|
+
this.httpsProxy = proxies[1]
|
|
528
|
+
this.noProxy = proxies[2]
|
|
489
529
|
}
|
|
490
530
|
|
|
491
531
|
/**
|
|
@@ -516,29 +556,16 @@ export class FetchSyncClient {
|
|
|
516
556
|
this.drop()
|
|
517
557
|
}
|
|
518
558
|
this.generation += 1
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
let url: Url | null =
|
|
522
|
-
if (url === null
|
|
523
|
-
this.fail(
|
|
524
|
-
return null
|
|
525
|
-
}
|
|
526
|
-
const refusal: string = this.hostRefusal(url)
|
|
527
|
-
if (refusal !== "") {
|
|
528
|
-
this.fail(HTTP_E_BLOCKED, refusal)
|
|
559
|
+
this.deadline = httpClientDeadline(this.options)
|
|
560
|
+
const fault: HttpClientFault = new HttpClientFault()
|
|
561
|
+
let url: Url | null = httpClientTarget(req.url, this.options, fault)
|
|
562
|
+
if (url === null) {
|
|
563
|
+
this.fail(fault.code, fault.text)
|
|
529
564
|
return null
|
|
530
565
|
}
|
|
531
|
-
|
|
532
|
-
let body: u8[] | null = req.body
|
|
533
|
-
const names: string[] = []
|
|
534
|
-
const values: string[] = []
|
|
535
|
-
for (let i: i32 = 0; i < toI32(req.names.length) && i < toI32(req.values.length); i += 1) {
|
|
536
|
-
names.push(req.names[i])
|
|
537
|
-
values.push(req.values[i])
|
|
538
|
-
}
|
|
539
|
-
let hops: i32 = 0
|
|
566
|
+
const hop: HttpClientHop = new HttpClientHop(req.method, req.body, req.names, req.values)
|
|
540
567
|
while (url !== null) {
|
|
541
|
-
const res: HttpResponse | null = this.exchange(url, method, names, values, body)
|
|
568
|
+
const res: HttpResponse | null = this.exchange(url, hop.method, hop.names, hop.values, hop.body)
|
|
542
569
|
if (res === null) {
|
|
543
570
|
return null
|
|
544
571
|
}
|
|
@@ -546,70 +573,16 @@ export class FetchSyncClient {
|
|
|
546
573
|
if (!this.options.followRedirects || location === null || !httpClientIsRedirect(res.status)) {
|
|
547
574
|
return res
|
|
548
575
|
}
|
|
549
|
-
const next: Url | null =
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
return this.refuse(
|
|
553
|
-
HTTP_E_TOO_MANY_REDIRECTS,
|
|
554
|
-
`more than ${maxRedirects} redirects, the last to ${httpClientRedact(next)}`
|
|
555
|
-
)
|
|
556
|
-
}
|
|
557
|
-
if (next === null || (next.scheme !== "http" && next.scheme !== "https")) {
|
|
558
|
-
return this.refuse(
|
|
559
|
-
HTTP_E_REDIRECT_REFUSED,
|
|
560
|
-
`a redirect to ${httpClientRedact(next)}, which is not an http or https URL`
|
|
561
|
-
)
|
|
562
|
-
}
|
|
563
|
-
if (url.scheme === "https" && next.scheme === "http") {
|
|
564
|
-
return this.refuse(
|
|
565
|
-
HTTP_E_REDIRECT_REFUSED,
|
|
566
|
-
`a redirect from https to http (${httpClientRedact(next)})`
|
|
567
|
-
)
|
|
568
|
-
}
|
|
569
|
-
const hopRefusal: string = this.hostRefusal(next)
|
|
570
|
-
if (hopRefusal !== "") {
|
|
571
|
-
return this.refuse(HTTP_E_BLOCKED, hopRefusal)
|
|
572
|
-
}
|
|
573
|
-
const from: string | null = urlOrigin(url)
|
|
574
|
-
const to: string | null = urlOrigin(next)
|
|
575
|
-
if (from === null || to === null || from !== to) {
|
|
576
|
-
if (!this.options.crossOriginRedirects) {
|
|
577
|
-
return this.refuse(
|
|
578
|
-
HTTP_E_REDIRECT_REFUSED,
|
|
579
|
-
`a redirect to another origin (${httpClientRedact(next)})`
|
|
580
|
-
)
|
|
581
|
-
}
|
|
582
|
-
// Credentials were meant for the first origin, not for wherever it points.
|
|
583
|
-
httpClientDropField(names, values, "authorization")
|
|
584
|
-
httpClientDropField(names, values, "proxy-authorization")
|
|
585
|
-
httpClientDropField(names, values, "cookie")
|
|
586
|
-
httpClientDropField(names, values, "host")
|
|
587
|
-
}
|
|
588
|
-
const status: i32 = res.status
|
|
589
|
-
if (
|
|
590
|
-
(status === 303 && method !== "HEAD") ||
|
|
591
|
-
((status === 301 || status === 302) && method === "POST")
|
|
592
|
-
) {
|
|
593
|
-
method = "GET"
|
|
594
|
-
body = null
|
|
595
|
-
httpClientDropField(names, values, "content-type")
|
|
576
|
+
const next: Url | null = httpClientRedirect(hop, this.options, url, res.status, location, fault)
|
|
577
|
+
if (next === null) {
|
|
578
|
+
return this.refuse(fault.code, fault.text)
|
|
596
579
|
}
|
|
597
580
|
this.drain()
|
|
598
|
-
hops += 1
|
|
599
581
|
url = next
|
|
600
582
|
}
|
|
601
583
|
return null
|
|
602
584
|
}
|
|
603
585
|
|
|
604
|
-
/** Why the outbound policy refuses to let a URL name `url`'s host; "" when there is no policy or it allows the host. */
|
|
605
|
-
private hostRefusal(url: Url): string {
|
|
606
|
-
const policy: OutboundPolicy | null = this.options.outbound
|
|
607
|
-
if (policy === null || outboundHostAllowed(policy, url.host)) {
|
|
608
|
-
return ""
|
|
609
|
-
}
|
|
610
|
-
return `${httpClientRedact(url)} names a host the outbound policy does not allow`
|
|
611
|
-
}
|
|
612
|
-
|
|
613
586
|
/** Closes the connection; the client can still fetch, on a new one. */
|
|
614
587
|
close(): void {
|
|
615
588
|
this.drop()
|
|
@@ -656,32 +629,22 @@ export class FetchSyncClient {
|
|
|
656
629
|
* a failure, with the error set.
|
|
657
630
|
*/
|
|
658
631
|
private open(url: Url): boolean {
|
|
659
|
-
const
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
this.options
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
`the proxy setting is not an http:// URL with a host: ${httpClientRedact(
|
|
672
|
-
urlParse(proxyText.indexOf("://") >= 0 ? proxyText : "http://" + proxyText)
|
|
673
|
-
)}`
|
|
674
|
-
)
|
|
675
|
-
return false
|
|
676
|
-
}
|
|
677
|
-
}
|
|
678
|
-
const origin: string = `${url.scheme}://${httpClientHostText(url.host)}:${port}`
|
|
679
|
-
let route: string = origin
|
|
680
|
-
if (proxy !== null && url.scheme === "http") {
|
|
681
|
-
route = `proxy ${httpClientHostText(proxy.host)}:${proxy.port}`
|
|
682
|
-
} else if (proxy !== null) {
|
|
683
|
-
route = `${origin} via ${httpClientHostText(proxy.host)}:${proxy.port}`
|
|
632
|
+
const fault: HttpClientFault = new HttpClientFault()
|
|
633
|
+
const way: HttpClientRoute | null = httpClientRoute(
|
|
634
|
+
url,
|
|
635
|
+
this.options,
|
|
636
|
+
this.httpProxy,
|
|
637
|
+
this.httpsProxy,
|
|
638
|
+
this.noProxy,
|
|
639
|
+
fault
|
|
640
|
+
)
|
|
641
|
+
if (way === null) {
|
|
642
|
+
this.fail(fault.code, fault.text)
|
|
643
|
+
return false
|
|
684
644
|
}
|
|
645
|
+
const proxy: Url | null = way.proxy
|
|
646
|
+
const port: i32 = way.port
|
|
647
|
+
const route: string = way.route
|
|
685
648
|
if (
|
|
686
649
|
this.fd >= 0 &&
|
|
687
650
|
this.route === route &&
|
|
@@ -697,9 +660,7 @@ export class FetchSyncClient {
|
|
|
697
660
|
if (url.scheme === "https" && !this.loadTrust()) {
|
|
698
661
|
return false
|
|
699
662
|
}
|
|
700
|
-
const
|
|
701
|
-
const dialPort: i32 = proxy !== null ? proxy.port : port
|
|
702
|
-
const fd: i32 = this.dial(dialHost, dialPort)
|
|
663
|
+
const fd: i32 = this.dial(way.dialHost, way.dialPort)
|
|
703
664
|
if (fd < 0) {
|
|
704
665
|
return false
|
|
705
666
|
}
|
|
@@ -734,14 +695,12 @@ export class FetchSyncClient {
|
|
|
734
695
|
if (this.trust !== null) {
|
|
735
696
|
return true
|
|
736
697
|
}
|
|
737
|
-
const
|
|
738
|
-
|
|
739
|
-
if (
|
|
740
|
-
|
|
741
|
-
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)
|
|
742
702
|
return false
|
|
743
703
|
}
|
|
744
|
-
this.trust = tlsClientTrust(roots)
|
|
745
704
|
return true
|
|
746
705
|
}
|
|
747
706
|
|
|
@@ -758,40 +717,17 @@ export class FetchSyncClient {
|
|
|
758
717
|
this.fail(HTTP_E_CERTIFICATE, "no trusted root certificates are loaded")
|
|
759
718
|
return false
|
|
760
719
|
}
|
|
761
|
-
const
|
|
762
|
-
const x25519: u8[] = new Array<u8>(HTTP_CLIENT_TLS_KEY_BYTES)
|
|
763
|
-
const p256: u8[] = new Array<u8>(HTTP_CLIENT_TLS_KEY_BYTES)
|
|
764
|
-
crypto.getRandomValues(random)
|
|
765
|
-
crypto.getRandomValues(x25519)
|
|
766
|
-
crypto.getRandomValues(p256)
|
|
767
|
-
// `TlsClient` copies both keys and zeroes these arrays.
|
|
768
|
-
const conn: TlsRecordClient = new TlsRecordClient(
|
|
769
|
-
new TlsClient(new TlsClientConfig(host, ["http/1.1"]), random, x25519, p256)
|
|
770
|
-
)
|
|
720
|
+
const conn: TlsRecordClient = httpClientTlsStart(host, early)
|
|
771
721
|
this.tls = conn
|
|
772
722
|
if (toI32(this.plain.length) === 0) {
|
|
773
723
|
this.plain = new Array<u8>(HTTP_CLIENT_READ_BYTES)
|
|
774
724
|
}
|
|
775
|
-
|
|
776
|
-
conn.receive(early, HTTP_CLIENT_ZERO, toI32(early.length))
|
|
777
|
-
}
|
|
725
|
+
const fault: HttpClientFault = new HttpClientFault()
|
|
778
726
|
// The connection opens on the server's Finished, with the client's own
|
|
779
727
|
// perhaps still queued: it is sent before the request is.
|
|
780
|
-
while (conn
|
|
781
|
-
if ((conn
|
|
782
|
-
|
|
783
|
-
if (verdict !== 0) {
|
|
784
|
-
conn.reject(verdict)
|
|
785
|
-
this.fail(
|
|
786
|
-
HTTP_E_CERTIFICATE,
|
|
787
|
-
`the certificate ${host} presented was refused (TLS alert ${verdict})`
|
|
788
|
-
)
|
|
789
|
-
return false
|
|
790
|
-
}
|
|
791
|
-
conn.authenticate(true)
|
|
792
|
-
}
|
|
793
|
-
if (conn.state === TLS_RECORD_STATE_FAILED) {
|
|
794
|
-
this.failTls(conn)
|
|
728
|
+
while (httpClientTlsOpening(conn)) {
|
|
729
|
+
if (!httpClientTlsVerify(conn, trust, host, fault)) {
|
|
730
|
+
this.fail(fault.code, fault.text)
|
|
795
731
|
return false
|
|
796
732
|
}
|
|
797
733
|
const moved: boolean = conn.outputEnd > conn.outputStart ? this.flushTls(conn) : this.receiveTls(conn)
|
|
@@ -807,21 +743,10 @@ export class FetchSyncClient {
|
|
|
807
743
|
* the proxy answers 2xx, every byte after its head belonging to the tunnel.
|
|
808
744
|
*/
|
|
809
745
|
private tunnel(host: string, port: i32, proxy: Url): boolean {
|
|
810
|
-
const
|
|
811
|
-
const
|
|
812
|
-
const values: string[] = [authority]
|
|
813
|
-
const auth: string | null = httpClientProxyAuth(proxy)
|
|
814
|
-
if (auth === null) {
|
|
815
|
-
this.fail(HTTP_E_PROXY, "the proxy's user name or password is not valid percent-encoding")
|
|
816
|
-
return false
|
|
817
|
-
}
|
|
818
|
-
if (auth !== "") {
|
|
819
|
-
names.push("Proxy-Authorization")
|
|
820
|
-
values.push(auth)
|
|
821
|
-
}
|
|
822
|
-
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)
|
|
823
748
|
if (head === null) {
|
|
824
|
-
this.fail(
|
|
749
|
+
this.fail(fault.code, fault.text)
|
|
825
750
|
return false
|
|
826
751
|
}
|
|
827
752
|
this.gotByte = false
|
|
@@ -835,7 +760,10 @@ export class FetchSyncClient {
|
|
|
835
760
|
}
|
|
836
761
|
const status: i32 = this.parser.status
|
|
837
762
|
if (status < 200 || status > 299) {
|
|
838
|
-
this.fail(
|
|
763
|
+
this.fail(
|
|
764
|
+
HTTP_E_PROXY_REFUSED,
|
|
765
|
+
`the proxy answered CONNECT ${httpClientHostText(host)}:${port} with ${status}`
|
|
766
|
+
)
|
|
839
767
|
return false
|
|
840
768
|
}
|
|
841
769
|
// A 2xx has no body: the parser ends it, then reports the tunnel.
|
|
@@ -854,57 +782,18 @@ export class FetchSyncClient {
|
|
|
854
782
|
values: string[],
|
|
855
783
|
body: u8[] | null
|
|
856
784
|
): HttpResponse | null {
|
|
857
|
-
const
|
|
858
|
-
const
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
const proxyAuth: boolean = httpClientNameIs(name, "proxy-authorization")
|
|
868
|
-
if (proxyAuth && !viaProxy) {
|
|
869
|
-
// Only an http proxy reads it: sent direct or through a tunnel, it
|
|
870
|
-
// would hand the proxy's credentials to the origin.
|
|
871
|
-
continue
|
|
872
|
-
}
|
|
873
|
-
hasProxyAuth = hasProxyAuth || proxyAuth
|
|
874
|
-
sendNames.push(name)
|
|
875
|
-
sendValues.push(value)
|
|
876
|
-
}
|
|
877
|
-
const hostText: string = httpClientHostText(url.host)
|
|
878
|
-
const authority: string = url.port >= 0 ? `${hostText}:${url.port}` : hostText
|
|
879
|
-
if (!hasHost) {
|
|
880
|
-
sendNames.push("Host")
|
|
881
|
-
sendValues.push(authority)
|
|
882
|
-
}
|
|
883
|
-
let target: string = url.path === "" ? "/" : url.path
|
|
884
|
-
const query: string | null = url.query
|
|
885
|
-
if (query !== null) {
|
|
886
|
-
target = target + "?" + query
|
|
887
|
-
}
|
|
888
|
-
if (viaProxy) {
|
|
889
|
-
target = `${url.scheme}://${authority}${target}`
|
|
890
|
-
const proxy: Url | null = httpClientProxyUrl(this.httpProxy)
|
|
891
|
-
const auth: string | null = proxy !== null ? httpClientProxyAuth(proxy) : ""
|
|
892
|
-
if (auth === null) {
|
|
893
|
-
this.fail(HTTP_E_PROXY, "the proxy's user name or password is not valid percent-encoding")
|
|
894
|
-
return null
|
|
895
|
-
}
|
|
896
|
-
if (auth !== "" && !hasProxyAuth) {
|
|
897
|
-
sendNames.push("Proxy-Authorization")
|
|
898
|
-
sendValues.push(auth)
|
|
899
|
-
}
|
|
900
|
-
}
|
|
901
|
-
const bodyLength: i64 = body !== null ? toI64(body.length) : toI64(-2)
|
|
902
|
-
const head: u8[] | null = http1RequestHead(method, target, sendNames, sendValues, bodyLength)
|
|
785
|
+
const fault: HttpClientFault = new HttpClientFault()
|
|
786
|
+
const head: u8[] | null = httpClientRequestHead(
|
|
787
|
+
url,
|
|
788
|
+
method,
|
|
789
|
+
names,
|
|
790
|
+
values,
|
|
791
|
+
body,
|
|
792
|
+
this.route.startsWith("proxy ") ? this.httpProxy : "",
|
|
793
|
+
fault
|
|
794
|
+
)
|
|
903
795
|
if (head === null) {
|
|
904
|
-
this.fail(
|
|
905
|
-
HTTP_E_REQUEST,
|
|
906
|
-
`the request ${method} ${httpClientRedact(url)} was refused: a bad method, target or header field`
|
|
907
|
-
)
|
|
796
|
+
this.fail(fault.code, fault.text)
|
|
908
797
|
return null
|
|
909
798
|
}
|
|
910
799
|
this.gotByte = false
|
|
@@ -960,28 +849,10 @@ export class FetchSyncClient {
|
|
|
960
849
|
}
|
|
961
850
|
event = this.parser.next()
|
|
962
851
|
}
|
|
963
|
-
if (event === HTTP1_ERROR) {
|
|
964
|
-
const
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
HTTP_E_BODY_TOO_LARGE,
|
|
968
|
-
`the body is larger than maxBodyBytes (${httpClientBodyCap(this.options)})`
|
|
969
|
-
)
|
|
970
|
-
} else {
|
|
971
|
-
// A response the server closed part way through is a connection lost,
|
|
972
|
-
// as one closed before any byte is; it is never sent again, because
|
|
973
|
-
// a byte of it came.
|
|
974
|
-
this.lost = code === HTTP1_E_TRUNCATED
|
|
975
|
-
this.fail(
|
|
976
|
-
HTTP_E_PROTOCOL,
|
|
977
|
-
`the response broke HTTP/1.1: ${this.parser.errorText} (http1 error ${code})`
|
|
978
|
-
)
|
|
979
|
-
}
|
|
980
|
-
return -1
|
|
981
|
-
}
|
|
982
|
-
if (event === HTTP1_CLOSED) {
|
|
983
|
-
this.lost = true
|
|
984
|
-
this.fail(HTTP_E_IO, "the server closed the connection before it answered")
|
|
852
|
+
if (event === HTTP1_ERROR || event === HTTP1_CLOSED) {
|
|
853
|
+
const fault: HttpClientFault = new HttpClientFault()
|
|
854
|
+
this.lost = httpClientParserFault(this.parser, event, this.options, fault)
|
|
855
|
+
this.fail(fault.code, fault.text)
|
|
985
856
|
return -1
|
|
986
857
|
}
|
|
987
858
|
return event
|
|
@@ -1086,13 +957,9 @@ export class FetchSyncClient {
|
|
|
1086
957
|
|
|
1087
958
|
/** Sets the error for the failed TLS connection `conn`, saying how it failed. */
|
|
1088
959
|
private failTls(conn: TlsRecordClient): void {
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
this.fail(HTTP_E_TLS, `the server sent TLS alert ${conn.peerAlert}`)
|
|
1093
|
-
} else {
|
|
1094
|
-
this.fail(HTTP_E_TLS, `the TLS connection failed (alert ${conn.failure()})`)
|
|
1095
|
-
}
|
|
960
|
+
const fault: HttpClientFault = new HttpClientFault()
|
|
961
|
+
httpClientTlsFault(conn, fault)
|
|
962
|
+
this.fail(fault.code, fault.text)
|
|
1096
963
|
}
|
|
1097
964
|
|
|
1098
965
|
/** Writes `bytes[off, off + len)` on the connection, through TLS for an https origin; false with the error set. */
|
|
@@ -1162,39 +1029,13 @@ export class FetchSyncClient {
|
|
|
1162
1029
|
this.fail(code, `no time was left to connect to ${host}`)
|
|
1163
1030
|
return -1
|
|
1164
1031
|
}
|
|
1165
|
-
let lookupMs: i64 = (until - start) / HTTP_CLIENT_NS_PER_MS
|
|
1166
|
-
if (lookupMs < toI64(1)) {
|
|
1167
|
-
lookupMs = toI64(1)
|
|
1168
|
-
} else if (lookupMs > toI64(2147483647)) {
|
|
1169
|
-
lookupMs = toI64(2147483647)
|
|
1170
|
-
}
|
|
1171
1032
|
const addresses: u8[] = new Array<u8>(DNS_RESOLVE_MAX_ADDRESSES * DNS_ADDRESS_BYTES)
|
|
1172
|
-
const
|
|
1173
|
-
const
|
|
1174
|
-
if (
|
|
1175
|
-
this.
|
|
1176
|
-
return -1
|
|
1177
|
-
}
|
|
1178
|
-
if (count <= 0) {
|
|
1179
|
-
this.fail(
|
|
1180
|
-
HTTP_E_DNS,
|
|
1181
|
-
`${host} could not be looked up (${count === 0 ? "no address" : `resolver code ${count}`})`
|
|
1182
|
-
)
|
|
1033
|
+
const fault: HttpClientFault = new HttpClientFault()
|
|
1034
|
+
const usable: i32 = httpClientResolve(host, port, this.options, start, until, code, addresses, fault)
|
|
1035
|
+
if (usable < 0) {
|
|
1036
|
+
this.fail(fault.code, fault.text)
|
|
1183
1037
|
return -1
|
|
1184
1038
|
}
|
|
1185
|
-
let usable: i32 = count < DNS_RESOLVE_MAX_ADDRESSES ? count : DNS_RESOLVE_MAX_ADDRESSES
|
|
1186
|
-
const policy: OutboundPolicy | null = this.options.outbound
|
|
1187
|
-
if (policy !== null) {
|
|
1188
|
-
// Only the bytes checked here are connected to: no second lookup a rebinding answer could change.
|
|
1189
|
-
usable = outboundFilter(policy, addresses, usable)
|
|
1190
|
-
if (usable === 0) {
|
|
1191
|
-
this.fail(
|
|
1192
|
-
HTTP_E_BLOCKED,
|
|
1193
|
-
`${host} resolves to ${outboundAddressText(addresses, 0)}, which the outbound policy does not allow`
|
|
1194
|
-
)
|
|
1195
|
-
return -1
|
|
1196
|
-
}
|
|
1197
|
-
}
|
|
1198
1039
|
const one: u8[] = new Array<u8>(DNS_ADDRESS_BYTES)
|
|
1199
1040
|
let last: i32 = 0
|
|
1200
1041
|
for (let i: i32 = 0; i < usable && i < DNS_RESOLVE_MAX_ADDRESSES; i += 1) {
|
|
@@ -1323,13 +1164,7 @@ export class FetchSyncClient {
|
|
|
1323
1164
|
private drop(): void {
|
|
1324
1165
|
const conn: TlsRecordClient | null = this.tls
|
|
1325
1166
|
if (conn !== null) {
|
|
1326
|
-
conn.
|
|
1327
|
-
// One try, without waiting, so the server sees the close_notify, or
|
|
1328
|
-
// the alert a refusal sealed, when the socket has room for it.
|
|
1329
|
-
if (this.fd >= 0 && conn.outputEnd > conn.outputStart) {
|
|
1330
|
-
netWrite(this.fd, conn.output, conn.outputStart, conn.outputEnd - conn.outputStart)
|
|
1331
|
-
}
|
|
1332
|
-
conn.wipe()
|
|
1167
|
+
httpClientTlsClose(conn, this.fd)
|
|
1333
1168
|
this.tls = null
|
|
1334
1169
|
}
|
|
1335
1170
|
if (this.fd >= 0) {
|
|
@@ -1434,13 +1269,7 @@ export class FetchSyncClient {
|
|
|
1434
1269
|
|
|
1435
1270
|
/** Sets the error for a wait that ended with `code`, `text` saying what timed out. */
|
|
1436
1271
|
private failWait(code: i32, text: string): void {
|
|
1437
|
-
|
|
1438
|
-
this.fail(code, `the fetch ran past ${httpClientTotalMs(this.options)} ms`)
|
|
1439
|
-
} else if (code === HTTP_E_IO) {
|
|
1440
|
-
this.fail(code, "the poll loop failed")
|
|
1441
|
-
} else {
|
|
1442
|
-
this.fail(code, text)
|
|
1443
|
-
}
|
|
1272
|
+
this.fail(code, httpClientWaitText(code, this.options, text))
|
|
1444
1273
|
}
|
|
1445
1274
|
|
|
1446
1275
|
/** Refuses a redirect: closes the connection, whose response is left unread, and fails. */
|
|
@@ -1814,3 +1643,1623 @@ const httpClientProxyAuth = (proxy: Url): string | null => {
|
|
|
1814
1643
|
}
|
|
1815
1644
|
return "Basic " + base64Encode(httpFieldBytes(user + ":" + password))
|
|
1816
1645
|
}
|
|
1646
|
+
|
|
1647
|
+
/** The first value of the field `name`, in any case, from parallel name and value lists; null when there is none. */
|
|
1648
|
+
const httpClientField = (names: string[], values: string[], name: string): string | null => {
|
|
1649
|
+
const lower: string = httpClientLower(name)
|
|
1650
|
+
for (let i: i32 = 0; i < toI32(names.length) && i < toI32(values.length); i += 1) {
|
|
1651
|
+
if (names[i] === lower) {
|
|
1652
|
+
return values[i]
|
|
1653
|
+
}
|
|
1654
|
+
}
|
|
1655
|
+
return null
|
|
1656
|
+
}
|
|
1657
|
+
|
|
1658
|
+
/**
|
|
1659
|
+
* The proxy settings the environment gives, as [http, https, no-proxy]; ""
|
|
1660
|
+
* for each when `useEnvProxy` is off. A CGI program (`REQUEST_METHOD` set)
|
|
1661
|
+
* ignores `HTTP_PROXY`, which a request's `Proxy:` header could have set.
|
|
1662
|
+
*/
|
|
1663
|
+
const httpClientEnvProxies = (options: HttpOptions): string[] => {
|
|
1664
|
+
if (!options.useEnvProxy) {
|
|
1665
|
+
return ["", "", ""]
|
|
1666
|
+
}
|
|
1667
|
+
const cgi: boolean = getenv("REQUEST_METHOD") !== null
|
|
1668
|
+
return [
|
|
1669
|
+
httpChooseProxy(getenv("http_proxy"), getenv("HTTP_PROXY"), !cgi),
|
|
1670
|
+
httpChooseProxy(getenv("https_proxy"), getenv("HTTPS_PROXY"), true),
|
|
1671
|
+
httpChooseProxy(getenv("no_proxy"), getenv("NO_PROXY"), true),
|
|
1672
|
+
]
|
|
1673
|
+
}
|
|
1674
|
+
|
|
1675
|
+
/** When a fetch starting now must be done by, on the monotonic clock; `HTTP_CLIENT_NEVER` with no total timeout. */
|
|
1676
|
+
const httpClientDeadline = (options: HttpOptions): i64 => {
|
|
1677
|
+
const total: i32 = httpClientTotalMs(options)
|
|
1678
|
+
return total > 0 ? monotonicNanos() + toI64(total) * HTTP_CLIENT_NS_PER_MS : HTTP_CLIENT_NEVER
|
|
1679
|
+
}
|
|
1680
|
+
|
|
1681
|
+
/** A failure a shared step found: an `HTTP_E_*` code and its sentence, before the code's name is put in front. */
|
|
1682
|
+
class HttpClientFault {
|
|
1683
|
+
code: i32 = 0
|
|
1684
|
+
text: string = ""
|
|
1685
|
+
|
|
1686
|
+
fail(code: i32, text: string): void {
|
|
1687
|
+
this.code = code
|
|
1688
|
+
this.text = text
|
|
1689
|
+
}
|
|
1690
|
+
}
|
|
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
|
+
|
|
1807
|
+
/** Why the outbound policy refuses to let a URL name `url`'s host; "" when there is no policy or it allows the host. */
|
|
1808
|
+
const httpClientHostRefusal = (options: HttpOptions, url: Url): string => {
|
|
1809
|
+
const policy: OutboundPolicy | null = options.outbound
|
|
1810
|
+
if (policy === null || outboundHostAllowed(policy, url.host)) {
|
|
1811
|
+
return ""
|
|
1812
|
+
}
|
|
1813
|
+
return `${httpClientRedact(url)} names a host the outbound policy does not allow`
|
|
1814
|
+
}
|
|
1815
|
+
|
|
1816
|
+
/** The request's URL, parsed and checked against the scheme and the policy; null with `fault` set. */
|
|
1817
|
+
const httpClientTarget = (text: string, options: HttpOptions, fault: HttpClientFault): Url | null => {
|
|
1818
|
+
const url: Url | null = urlParse(text)
|
|
1819
|
+
if (url === null || (url.scheme !== "http" && url.scheme !== "https")) {
|
|
1820
|
+
fault.fail(HTTP_E_URL, `not an absolute http or https URL: ${httpClientRedact(url)}`)
|
|
1821
|
+
return null
|
|
1822
|
+
}
|
|
1823
|
+
const refusal: string = httpClientHostRefusal(options, url)
|
|
1824
|
+
if (refusal !== "") {
|
|
1825
|
+
fault.fail(HTTP_E_BLOCKED, refusal)
|
|
1826
|
+
return null
|
|
1827
|
+
}
|
|
1828
|
+
return url
|
|
1829
|
+
}
|
|
1830
|
+
|
|
1831
|
+
/** What the next hop of a fetch sends: the method, body and fields a redirect may rewrite, and the hops taken. */
|
|
1832
|
+
class HttpClientHop {
|
|
1833
|
+
method: string
|
|
1834
|
+
body: u8[] | null
|
|
1835
|
+
names: string[]
|
|
1836
|
+
values: string[]
|
|
1837
|
+
hops: i32 = 0
|
|
1838
|
+
|
|
1839
|
+
constructor(method: string, body: u8[] | null, names: string[], values: string[]) {
|
|
1840
|
+
this.method = method
|
|
1841
|
+
this.body = body
|
|
1842
|
+
this.names = []
|
|
1843
|
+
this.values = []
|
|
1844
|
+
for (let i: i32 = 0; i < toI32(names.length) && i < toI32(values.length); i += 1) {
|
|
1845
|
+
// Read before any call, which is where the bounds proof forgets a length.
|
|
1846
|
+
const name: string = names[i]
|
|
1847
|
+
const value: string = values[i]
|
|
1848
|
+
this.names.push(name)
|
|
1849
|
+
this.values.push(value)
|
|
1850
|
+
}
|
|
1851
|
+
}
|
|
1852
|
+
}
|
|
1853
|
+
|
|
1854
|
+
/**
|
|
1855
|
+
* Where a redirect from `url` to `location` goes, with `hop` rewritten for
|
|
1856
|
+
* it: credentials dropped across origins, a 303 (or a 301/302 after POST)
|
|
1857
|
+
* turned into GET. Null with `fault` set when the redirect is refused.
|
|
1858
|
+
*/
|
|
1859
|
+
const httpClientRedirect = (
|
|
1860
|
+
hop: HttpClientHop,
|
|
1861
|
+
options: HttpOptions,
|
|
1862
|
+
url: Url,
|
|
1863
|
+
status: i32,
|
|
1864
|
+
location: string,
|
|
1865
|
+
fault: HttpClientFault
|
|
1866
|
+
): Url | null => {
|
|
1867
|
+
const next: Url | null = urlResolve(url, location)
|
|
1868
|
+
const maxRedirects: i32 = httpClientMaxRedirects(options)
|
|
1869
|
+
if (hop.hops >= maxRedirects) {
|
|
1870
|
+
fault.fail(
|
|
1871
|
+
HTTP_E_TOO_MANY_REDIRECTS,
|
|
1872
|
+
`more than ${maxRedirects} redirects, the last to ${httpClientRedact(next)}`
|
|
1873
|
+
)
|
|
1874
|
+
return null
|
|
1875
|
+
}
|
|
1876
|
+
if (next === null || (next.scheme !== "http" && next.scheme !== "https")) {
|
|
1877
|
+
fault.fail(
|
|
1878
|
+
HTTP_E_REDIRECT_REFUSED,
|
|
1879
|
+
`a redirect to ${httpClientRedact(next)}, which is not an http or https URL`
|
|
1880
|
+
)
|
|
1881
|
+
return null
|
|
1882
|
+
}
|
|
1883
|
+
if (url.scheme === "https" && next.scheme === "http") {
|
|
1884
|
+
fault.fail(HTTP_E_REDIRECT_REFUSED, `a redirect from https to http (${httpClientRedact(next)})`)
|
|
1885
|
+
return null
|
|
1886
|
+
}
|
|
1887
|
+
const refusal: string = httpClientHostRefusal(options, next)
|
|
1888
|
+
if (refusal !== "") {
|
|
1889
|
+
fault.fail(HTTP_E_BLOCKED, refusal)
|
|
1890
|
+
return null
|
|
1891
|
+
}
|
|
1892
|
+
const from: string | null = urlOrigin(url)
|
|
1893
|
+
const to: string | null = urlOrigin(next)
|
|
1894
|
+
if (from === null || to === null || from !== to) {
|
|
1895
|
+
if (!options.crossOriginRedirects) {
|
|
1896
|
+
fault.fail(HTTP_E_REDIRECT_REFUSED, `a redirect to another origin (${httpClientRedact(next)})`)
|
|
1897
|
+
return null
|
|
1898
|
+
}
|
|
1899
|
+
// Credentials were meant for the first origin, not for wherever it points.
|
|
1900
|
+
httpClientDropField(hop.names, hop.values, "authorization")
|
|
1901
|
+
httpClientDropField(hop.names, hop.values, "proxy-authorization")
|
|
1902
|
+
httpClientDropField(hop.names, hop.values, "cookie")
|
|
1903
|
+
httpClientDropField(hop.names, hop.values, "host")
|
|
1904
|
+
}
|
|
1905
|
+
if (
|
|
1906
|
+
(status === 303 && hop.method !== "HEAD") ||
|
|
1907
|
+
((status === 301 || status === 302) && hop.method === "POST")
|
|
1908
|
+
) {
|
|
1909
|
+
hop.method = "GET"
|
|
1910
|
+
hop.body = null
|
|
1911
|
+
httpClientDropField(hop.names, hop.values, "content-type")
|
|
1912
|
+
}
|
|
1913
|
+
hop.hops += 1
|
|
1914
|
+
return next
|
|
1915
|
+
}
|
|
1916
|
+
|
|
1917
|
+
/** Where a connection for one URL goes: the address to dial, the proxy if any, and the route a kept connection must match. */
|
|
1918
|
+
class HttpClientRoute {
|
|
1919
|
+
proxy: Url | null = null
|
|
1920
|
+
dialHost: string = ""
|
|
1921
|
+
route: string = ""
|
|
1922
|
+
port: i32 = 0
|
|
1923
|
+
dialPort: i32 = 0
|
|
1924
|
+
}
|
|
1925
|
+
|
|
1926
|
+
/**
|
|
1927
|
+
* The route to `url` under the proxy settings: none under an outbound
|
|
1928
|
+
* policy, since a proxy would look the name up past the policy's address
|
|
1929
|
+
* check. Null with `fault` set when the proxy setting is malformed.
|
|
1930
|
+
*/
|
|
1931
|
+
const httpClientRoute = (
|
|
1932
|
+
url: Url,
|
|
1933
|
+
options: HttpOptions,
|
|
1934
|
+
httpProxy: string,
|
|
1935
|
+
httpsProxy: string,
|
|
1936
|
+
noProxy: string,
|
|
1937
|
+
fault: HttpClientFault
|
|
1938
|
+
): HttpClientRoute | null => {
|
|
1939
|
+
const way: HttpClientRoute = new HttpClientRoute()
|
|
1940
|
+
const port: i32 = url.port >= 0 ? url.port : urlDefaultPort(url.scheme)
|
|
1941
|
+
way.port = port
|
|
1942
|
+
const proxyText: string =
|
|
1943
|
+
options.outbound !== null ? "" : httpProxyFor(url.scheme, url.host, port, httpProxy, httpsProxy, noProxy)
|
|
1944
|
+
let proxy: Url | null = null
|
|
1945
|
+
if (proxyText !== "") {
|
|
1946
|
+
proxy = httpClientProxyUrl(proxyText)
|
|
1947
|
+
if (proxy === null) {
|
|
1948
|
+
fault.fail(
|
|
1949
|
+
HTTP_E_PROXY,
|
|
1950
|
+
`the proxy setting is not an http:// URL with a host: ${httpClientRedact(
|
|
1951
|
+
urlParse(proxyText.indexOf("://") >= 0 ? proxyText : "http://" + proxyText)
|
|
1952
|
+
)}`
|
|
1953
|
+
)
|
|
1954
|
+
return null
|
|
1955
|
+
}
|
|
1956
|
+
}
|
|
1957
|
+
const origin: string = `${url.scheme}://${httpClientHostText(url.host)}:${port}`
|
|
1958
|
+
way.route = origin
|
|
1959
|
+
way.dialHost = url.host
|
|
1960
|
+
way.dialPort = port
|
|
1961
|
+
if (proxy !== null) {
|
|
1962
|
+
way.proxy = proxy
|
|
1963
|
+
way.dialHost = proxy.host
|
|
1964
|
+
way.dialPort = proxy.port
|
|
1965
|
+
way.route =
|
|
1966
|
+
url.scheme === "http"
|
|
1967
|
+
? `proxy ${httpClientHostText(proxy.host)}:${proxy.port}`
|
|
1968
|
+
: `${origin} via ${httpClientHostText(proxy.host)}:${proxy.port}`
|
|
1969
|
+
}
|
|
1970
|
+
return way
|
|
1971
|
+
}
|
|
1972
|
+
|
|
1973
|
+
/**
|
|
1974
|
+
* The bytes of a request's head: `Host` added when the fields lack it, the
|
|
1975
|
+
* absolute-form target and the proxy's credentials when `httpProxy` is the
|
|
1976
|
+
* http proxy the request goes through ("" for none), and a
|
|
1977
|
+
* `Proxy-Authorization` field dropped when it is not. Null with `fault` set.
|
|
1978
|
+
*/
|
|
1979
|
+
const httpClientRequestHead = (
|
|
1980
|
+
url: Url,
|
|
1981
|
+
method: string,
|
|
1982
|
+
names: string[],
|
|
1983
|
+
values: string[],
|
|
1984
|
+
body: u8[] | null,
|
|
1985
|
+
httpProxy: string,
|
|
1986
|
+
fault: HttpClientFault
|
|
1987
|
+
): u8[] | null => {
|
|
1988
|
+
const viaProxy: boolean = httpProxy !== ""
|
|
1989
|
+
const sendNames: string[] = []
|
|
1990
|
+
const sendValues: string[] = []
|
|
1991
|
+
let hasHost: boolean = false
|
|
1992
|
+
let hasProxyAuth: boolean = false
|
|
1993
|
+
for (let i: i32 = 0; i < toI32(names.length) && i < toI32(values.length); i += 1) {
|
|
1994
|
+
// Read before any call, which is where the bounds proof forgets a length.
|
|
1995
|
+
const name: string = names[i]
|
|
1996
|
+
const value: string = values[i]
|
|
1997
|
+
hasHost = hasHost || httpClientNameIs(name, "host")
|
|
1998
|
+
const proxyAuth: boolean = httpClientNameIs(name, "proxy-authorization")
|
|
1999
|
+
if (proxyAuth && !viaProxy) {
|
|
2000
|
+
// Only an http proxy reads it: sent direct or through a tunnel, it
|
|
2001
|
+
// would hand the proxy's credentials to the origin.
|
|
2002
|
+
continue
|
|
2003
|
+
}
|
|
2004
|
+
hasProxyAuth = hasProxyAuth || proxyAuth
|
|
2005
|
+
sendNames.push(name)
|
|
2006
|
+
sendValues.push(value)
|
|
2007
|
+
}
|
|
2008
|
+
const hostText: string = httpClientHostText(url.host)
|
|
2009
|
+
const authority: string = url.port >= 0 ? `${hostText}:${url.port}` : hostText
|
|
2010
|
+
if (!hasHost) {
|
|
2011
|
+
sendNames.push("Host")
|
|
2012
|
+
sendValues.push(authority)
|
|
2013
|
+
}
|
|
2014
|
+
let target: string = url.path === "" ? "/" : url.path
|
|
2015
|
+
const query: string | null = url.query
|
|
2016
|
+
if (query !== null) {
|
|
2017
|
+
target = target + "?" + query
|
|
2018
|
+
}
|
|
2019
|
+
if (viaProxy) {
|
|
2020
|
+
target = `${url.scheme}://${authority}${target}`
|
|
2021
|
+
const proxy: Url | null = httpClientProxyUrl(httpProxy)
|
|
2022
|
+
const auth: string | null = proxy !== null ? httpClientProxyAuth(proxy) : ""
|
|
2023
|
+
if (auth === null) {
|
|
2024
|
+
fault.fail(HTTP_E_PROXY, "the proxy's user name or password is not valid percent-encoding")
|
|
2025
|
+
return null
|
|
2026
|
+
}
|
|
2027
|
+
if (auth !== "" && !hasProxyAuth) {
|
|
2028
|
+
sendNames.push("Proxy-Authorization")
|
|
2029
|
+
sendValues.push(auth)
|
|
2030
|
+
}
|
|
2031
|
+
}
|
|
2032
|
+
const bodyLength: i64 = body !== null ? toI64(body.length) : toI64(-2)
|
|
2033
|
+
const head: u8[] | null = http1RequestHead(method, target, sendNames, sendValues, bodyLength)
|
|
2034
|
+
if (head === null) {
|
|
2035
|
+
fault.fail(
|
|
2036
|
+
HTTP_E_REQUEST,
|
|
2037
|
+
`the request ${method} ${httpClientRedact(url)} was refused: a bad method, target or header field`
|
|
2038
|
+
)
|
|
2039
|
+
}
|
|
2040
|
+
return head
|
|
2041
|
+
}
|
|
2042
|
+
|
|
2043
|
+
/**
|
|
2044
|
+
* The failure behind a parser's `HTTP1_ERROR` or `HTTP1_CLOSED` `event`, in
|
|
2045
|
+
* `fault`: true when the connection was lost (closed before or part way
|
|
2046
|
+
* through the response), which is what lets a kept connection be retried.
|
|
2047
|
+
*/
|
|
2048
|
+
const httpClientParserFault = (
|
|
2049
|
+
parser: Http1ResponseParser,
|
|
2050
|
+
event: i32,
|
|
2051
|
+
options: HttpOptions,
|
|
2052
|
+
fault: HttpClientFault
|
|
2053
|
+
): boolean => {
|
|
2054
|
+
if (event === HTTP1_CLOSED) {
|
|
2055
|
+
fault.fail(HTTP_E_IO, "the server closed the connection before it answered")
|
|
2056
|
+
return true
|
|
2057
|
+
}
|
|
2058
|
+
const code: i32 = parser.error
|
|
2059
|
+
if (code === HTTP1_E_BODY_LIMIT) {
|
|
2060
|
+
fault.fail(HTTP_E_BODY_TOO_LARGE, `the body is larger than maxBodyBytes (${httpClientBodyCap(options)})`)
|
|
2061
|
+
return false
|
|
2062
|
+
}
|
|
2063
|
+
fault.fail(HTTP_E_PROTOCOL, `the response broke HTTP/1.1: ${parser.errorText} (http1 error ${code})`)
|
|
2064
|
+
// A response the server closed part way through is a connection lost, as
|
|
2065
|
+
// one closed before any byte is; it is never sent again, because a byte of
|
|
2066
|
+
// it came.
|
|
2067
|
+
return code === HTTP1_E_TRUNCATED
|
|
2068
|
+
}
|
|
2069
|
+
|
|
2070
|
+
/** The sentence for a failed wait: the total timeout and a broken poll loop have fixed ones, anything else `text`. */
|
|
2071
|
+
const httpClientWaitText = (code: i32, options: HttpOptions, text: string): string => {
|
|
2072
|
+
if (code === HTTP_E_TOTAL_TIMEOUT) {
|
|
2073
|
+
return `the fetch ran past ${httpClientTotalMs(options)} ms`
|
|
2074
|
+
}
|
|
2075
|
+
if (code === HTTP_E_IO) {
|
|
2076
|
+
return "the poll loop failed"
|
|
2077
|
+
}
|
|
2078
|
+
return text
|
|
2079
|
+
}
|
|
2080
|
+
|
|
2081
|
+
/**
|
|
2082
|
+
* Looks `host` up within `start`..`until` into `addresses` and keeps those
|
|
2083
|
+
* the outbound policy allows: how many to try, or -1 with `fault` set (`code`
|
|
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.
|
|
2086
|
+
*/
|
|
2087
|
+
const httpClientResolve = (
|
|
2088
|
+
host: string,
|
|
2089
|
+
port: i32,
|
|
2090
|
+
options: HttpOptions,
|
|
2091
|
+
start: i64,
|
|
2092
|
+
until: i64,
|
|
2093
|
+
code: i32,
|
|
2094
|
+
addresses: u8[],
|
|
2095
|
+
fault: HttpClientFault
|
|
2096
|
+
): i32 => {
|
|
2097
|
+
let lookupMs: i64 = (until - start) / HTTP_CLIENT_NS_PER_MS
|
|
2098
|
+
if (lookupMs < toI64(1)) {
|
|
2099
|
+
lookupMs = toI64(1)
|
|
2100
|
+
} else if (lookupMs > toI64(2147483647)) {
|
|
2101
|
+
lookupMs = toI64(2147483647)
|
|
2102
|
+
}
|
|
2103
|
+
const ttls: i32[] = new Array<i32>(DNS_RESOLVE_MAX_ADDRESSES)
|
|
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 => {
|
|
2131
|
+
if (count === DNS_RESOLVE_TIMEOUT && until < HTTP_CLIENT_NEVER) {
|
|
2132
|
+
fault.fail(
|
|
2133
|
+
code,
|
|
2134
|
+
httpClientWaitText(code, options, `${host} was not looked up within ${options.connectTimeoutMs} ms`)
|
|
2135
|
+
)
|
|
2136
|
+
return -1
|
|
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
|
+
}
|
|
2146
|
+
if (count <= 0) {
|
|
2147
|
+
fault.fail(
|
|
2148
|
+
HTTP_E_DNS,
|
|
2149
|
+
`${host} could not be looked up (${count === 0 ? "no address" : `resolver code ${count}`})`
|
|
2150
|
+
)
|
|
2151
|
+
return -1
|
|
2152
|
+
}
|
|
2153
|
+
let usable: i32 = count < DNS_RESOLVE_MAX_ADDRESSES ? count : DNS_RESOLVE_MAX_ADDRESSES
|
|
2154
|
+
const policy: OutboundPolicy | null = options.outbound
|
|
2155
|
+
if (policy !== null) {
|
|
2156
|
+
// Only the bytes checked here are connected to: no second lookup a rebinding answer could change.
|
|
2157
|
+
usable = outboundFilter(policy, addresses, usable)
|
|
2158
|
+
if (usable === 0) {
|
|
2159
|
+
fault.fail(
|
|
2160
|
+
HTTP_E_BLOCKED,
|
|
2161
|
+
`${host} resolves to ${outboundAddressText(addresses, 0)}, which the outbound policy does not allow`
|
|
2162
|
+
)
|
|
2163
|
+
return -1
|
|
2164
|
+
}
|
|
2165
|
+
}
|
|
2166
|
+
return usable
|
|
2167
|
+
}
|
|
2168
|
+
|
|
2169
|
+
// ---- The async fetch ---------------------------------------------------------
|
|
2170
|
+
|
|
2171
|
+
/** How many idle connections a `FetchPool` holds at most, over every route. */
|
|
2172
|
+
const FETCH_POOL_SLOTS: i32 = 64
|
|
2173
|
+
|
|
2174
|
+
/**
|
|
2175
|
+
* Why an async `fetch` failed: an `HTTP_E_*` code and its sentence, the
|
|
2176
|
+
* code's name first, as `FetchSyncClient.errorText` reads. The text never
|
|
2177
|
+
* holds a URL's credentials or query.
|
|
2178
|
+
*/
|
|
2179
|
+
export class FetchError {
|
|
2180
|
+
/** The `HTTP_E_*` code. */
|
|
2181
|
+
code: i32
|
|
2182
|
+
/** The code's name, a colon and what went wrong, such as `dns: example.invalid could not be looked up`. */
|
|
2183
|
+
text: string
|
|
2184
|
+
|
|
2185
|
+
/**
|
|
2186
|
+
* A failure with its code and text.
|
|
2187
|
+
* @param code The `HTTP_E_*` code.
|
|
2188
|
+
* @param text The code's name, a colon and the sentence.
|
|
2189
|
+
*/
|
|
2190
|
+
constructor(code: i32, text: string) {
|
|
2191
|
+
this.code = code
|
|
2192
|
+
this.text = text
|
|
2193
|
+
}
|
|
2194
|
+
}
|
|
2195
|
+
|
|
2196
|
+
/**
|
|
2197
|
+
* A response `fetch` answered, its body already read whole: the body is
|
|
2198
|
+
* read before `fetch` answers, up to `maxBodyBytes`, so `text()` and
|
|
2199
|
+
* `bytes()` are plain calls. `names` are lower-cased and in the order they
|
|
2200
|
+
* arrived, beside `values`; `url` is the URL that answered.
|
|
2201
|
+
*/
|
|
2202
|
+
export class FetchResponse {
|
|
2203
|
+
/** The status code, such as 200. */
|
|
2204
|
+
status: i32 = 0
|
|
2205
|
+
/** The reason phrase the server sent beside the status. */
|
|
2206
|
+
reason: string = ""
|
|
2207
|
+
/** The URL that answered, which differs from the request's after a redirect. */
|
|
2208
|
+
url: string = ""
|
|
2209
|
+
/** The header field names, lower-cased, in the order they arrived. */
|
|
2210
|
+
names: string[]
|
|
2211
|
+
/** The header field values, each beside its name in `names`. */
|
|
2212
|
+
values: string[]
|
|
2213
|
+
/** The body, de-chunked; empty for a `HEAD` or a status that has none. */
|
|
2214
|
+
body: u8[]
|
|
2215
|
+
|
|
2216
|
+
/** A response with no status, fields or body yet; `fetch` fills them in. */
|
|
2217
|
+
constructor() {
|
|
2218
|
+
this.names = []
|
|
2219
|
+
this.values = []
|
|
2220
|
+
this.body = []
|
|
2221
|
+
}
|
|
2222
|
+
|
|
2223
|
+
/**
|
|
2224
|
+
* The first value of the field `name`, in any case.
|
|
2225
|
+
* @param name The field name to look for.
|
|
2226
|
+
* @returns The value, or null when the response has no such field.
|
|
2227
|
+
*/
|
|
2228
|
+
header(name: string): string | null {
|
|
2229
|
+
return httpClientField(this.names, this.values, name)
|
|
2230
|
+
}
|
|
2231
|
+
|
|
2232
|
+
/**
|
|
2233
|
+
* The body as a string, its bytes unchanged: nothing checks that they are UTF-8.
|
|
2234
|
+
* @returns The body's text.
|
|
2235
|
+
*/
|
|
2236
|
+
text(): string {
|
|
2237
|
+
return String.fromBytes(this.body, HTTP_CLIENT_ZERO, toI32(this.body.length))
|
|
2238
|
+
}
|
|
2239
|
+
|
|
2240
|
+
/**
|
|
2241
|
+
* The body's bytes.
|
|
2242
|
+
* @returns The body, the same array as `body`.
|
|
2243
|
+
*/
|
|
2244
|
+
bytes(): u8[] {
|
|
2245
|
+
return this.body
|
|
2246
|
+
}
|
|
2247
|
+
}
|
|
2248
|
+
|
|
2249
|
+
/**
|
|
2250
|
+
* Connections an async `fetch` leaves open for the next one to the same
|
|
2251
|
+
* place, held by the caller and handed in through `RequestInit.pool`. At
|
|
2252
|
+
* most `maxIdlePerOrigin` wait per route and 64 in all; a kept connection
|
|
2253
|
+
* the server closed, or sent a byte on unasked, is closed when it is next
|
|
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.
|
|
2256
|
+
*/
|
|
2257
|
+
export class FetchPool {
|
|
2258
|
+
/** The most idle connections kept for one route (origin, or proxy). */
|
|
2259
|
+
maxIdlePerOrigin: i32
|
|
2260
|
+
private fds: i32[]
|
|
2261
|
+
private routes: string[]
|
|
2262
|
+
private probe: u8[]
|
|
2263
|
+
|
|
2264
|
+
/**
|
|
2265
|
+
* An empty pool.
|
|
2266
|
+
* @param maxIdlePerOrigin The most idle connections kept for one route; 0 keeps none.
|
|
2267
|
+
*/
|
|
2268
|
+
constructor(maxIdlePerOrigin: i32 = 4) {
|
|
2269
|
+
this.maxIdlePerOrigin = maxIdlePerOrigin
|
|
2270
|
+
this.fds = []
|
|
2271
|
+
this.routes = []
|
|
2272
|
+
this.probe = new Array<u8>(1)
|
|
2273
|
+
for (let i: i32 = 0; i < FETCH_POOL_SLOTS; i += 1) {
|
|
2274
|
+
this.fds.push(toI32(-1))
|
|
2275
|
+
this.routes.push("")
|
|
2276
|
+
}
|
|
2277
|
+
}
|
|
2278
|
+
|
|
2279
|
+
/**
|
|
2280
|
+
* How many idle connections the pool holds.
|
|
2281
|
+
* @returns The count, over every route.
|
|
2282
|
+
*/
|
|
2283
|
+
idle(): i32 {
|
|
2284
|
+
let count: i32 = 0
|
|
2285
|
+
for (let i: i32 = 0; i < FETCH_POOL_SLOTS; i += 1) {
|
|
2286
|
+
if (this.fds[i] >= 0) {
|
|
2287
|
+
count += 1
|
|
2288
|
+
}
|
|
2289
|
+
}
|
|
2290
|
+
return count
|
|
2291
|
+
}
|
|
2292
|
+
|
|
2293
|
+
/** Closes every idle connection; the pool can still keep new ones. */
|
|
2294
|
+
close(): void {
|
|
2295
|
+
for (let i: i32 = 0; i < FETCH_POOL_SLOTS; i += 1) {
|
|
2296
|
+
this.drop(i)
|
|
2297
|
+
}
|
|
2298
|
+
}
|
|
2299
|
+
|
|
2300
|
+
/**
|
|
2301
|
+
* A quiet idle connection for `route`, taken out of the pool; -1 for none.
|
|
2302
|
+
* A connection that reads anything, its end included, is closed instead.
|
|
2303
|
+
* @internal
|
|
2304
|
+
*/
|
|
2305
|
+
take(route: string): i32 {
|
|
2306
|
+
for (let i: i32 = 0; i < FETCH_POOL_SLOTS; i += 1) {
|
|
2307
|
+
if (this.fds[i] < 0 || this.routes[i] !== route) {
|
|
2308
|
+
continue
|
|
2309
|
+
}
|
|
2310
|
+
const fd: i32 = this.fds[i]
|
|
2311
|
+
if (netRead(fd, this.probe, HTTP_CLIENT_ZERO, 1) === HTTP_CLIENT_WOULD_BLOCK) {
|
|
2312
|
+
this.fds[i] = -1
|
|
2313
|
+
this.routes[i] = ""
|
|
2314
|
+
return fd
|
|
2315
|
+
}
|
|
2316
|
+
this.drop(i)
|
|
2317
|
+
}
|
|
2318
|
+
return -1
|
|
2319
|
+
}
|
|
2320
|
+
|
|
2321
|
+
/** Keeps `fd` for `route` when there is room, else closes it. @internal */
|
|
2322
|
+
put(route: string, fd: i32): void {
|
|
2323
|
+
let same: i32 = 0
|
|
2324
|
+
let free: i32 = -1
|
|
2325
|
+
for (let i: i32 = 0; i < FETCH_POOL_SLOTS; i += 1) {
|
|
2326
|
+
if (this.fds[i] < 0) {
|
|
2327
|
+
free = free < 0 ? i : free
|
|
2328
|
+
} else if (this.routes[i] === route) {
|
|
2329
|
+
same += 1
|
|
2330
|
+
}
|
|
2331
|
+
}
|
|
2332
|
+
if (same >= this.maxIdlePerOrigin || free < 0) {
|
|
2333
|
+
netClose(fd)
|
|
2334
|
+
return
|
|
2335
|
+
}
|
|
2336
|
+
this.fds[free] = fd
|
|
2337
|
+
this.routes[free] = route
|
|
2338
|
+
}
|
|
2339
|
+
|
|
2340
|
+
private drop(i: i32): void {
|
|
2341
|
+
if (this.fds[i] >= 0) {
|
|
2342
|
+
netClose(this.fds[i])
|
|
2343
|
+
}
|
|
2344
|
+
this.fds[i] = -1
|
|
2345
|
+
this.routes[i] = ""
|
|
2346
|
+
}
|
|
2347
|
+
}
|
|
2348
|
+
|
|
2349
|
+
/**
|
|
2350
|
+
* What an async `fetch` sends and how it behaves. `options` are
|
|
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.
|
|
2358
|
+
*/
|
|
2359
|
+
export class RequestInit {
|
|
2360
|
+
/** The request method, sent as given; `GET` by default. */
|
|
2361
|
+
method: string = "GET"
|
|
2362
|
+
/** The header field names, in the order they are sent. */
|
|
2363
|
+
names: string[]
|
|
2364
|
+
/** The header field values, each beside its name in `names`. */
|
|
2365
|
+
values: string[]
|
|
2366
|
+
/** Null for no body at all; an empty array sends `Content-Length: 0`. */
|
|
2367
|
+
body: u8[] | null = null
|
|
2368
|
+
/** The limits, policy and redirect and proxy settings (see above for the timeouts). */
|
|
2369
|
+
options: HttpOptions
|
|
2370
|
+
/** Where idle connections are kept between fetches; null for none. */
|
|
2371
|
+
pool: FetchPool | null = null
|
|
2372
|
+
|
|
2373
|
+
/** A `GET` with no fields, no body, default options and no pool. */
|
|
2374
|
+
constructor() {
|
|
2375
|
+
this.names = []
|
|
2376
|
+
this.values = []
|
|
2377
|
+
this.options = new HttpOptions()
|
|
2378
|
+
}
|
|
2379
|
+
|
|
2380
|
+
/**
|
|
2381
|
+
* Appends one header field; nothing is checked until the request is written.
|
|
2382
|
+
* @param name The field name.
|
|
2383
|
+
* @param value The field value; one holding a CR or LF makes the fetch fail.
|
|
2384
|
+
* @returns This init, so calls chain.
|
|
2385
|
+
*/
|
|
2386
|
+
header(name: string, value: string): RequestInit {
|
|
2387
|
+
this.names.push(name)
|
|
2388
|
+
this.values.push(value)
|
|
2389
|
+
return this
|
|
2390
|
+
}
|
|
2391
|
+
}
|
|
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
|
+
|
|
2454
|
+
/** One connection an async fetch drives, and the state of the exchange on it. */
|
|
2455
|
+
class HttpClientConn {
|
|
2456
|
+
deadline: i64
|
|
2457
|
+
options: HttpOptions
|
|
2458
|
+
parser: Http1ResponseParser
|
|
2459
|
+
rbuf: u8[]
|
|
2460
|
+
fault: HttpClientFault
|
|
2461
|
+
route: string = ""
|
|
2462
|
+
httpProxy: string
|
|
2463
|
+
httpsProxy: string
|
|
2464
|
+
noProxy: string
|
|
2465
|
+
fd: i32 = -1
|
|
2466
|
+
gotByte: boolean = false
|
|
2467
|
+
lost: boolean = false
|
|
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
|
|
2475
|
+
|
|
2476
|
+
constructor(options: HttpOptions) {
|
|
2477
|
+
this.options = options
|
|
2478
|
+
this.deadline = httpClientDeadline(options)
|
|
2479
|
+
this.parser = httpClientParser(options)
|
|
2480
|
+
this.rbuf = new Array<u8>(HTTP_CLIENT_READ_BYTES)
|
|
2481
|
+
this.plain = []
|
|
2482
|
+
this.fault = new HttpClientFault()
|
|
2483
|
+
const proxies: string[] = httpClientEnvProxies(options)
|
|
2484
|
+
this.httpProxy = proxies[0]
|
|
2485
|
+
this.httpsProxy = proxies[1]
|
|
2486
|
+
this.noProxy = proxies[2]
|
|
2487
|
+
}
|
|
2488
|
+
|
|
2489
|
+
/** Fails with `HTTP_E_TOTAL_TIMEOUT` once the fetch's deadline has passed. */
|
|
2490
|
+
overdue(): boolean {
|
|
2491
|
+
if (this.deadline < HTTP_CLIENT_NEVER && monotonicNanos() >= this.deadline) {
|
|
2492
|
+
this.fault.fail(HTTP_E_TOTAL_TIMEOUT, httpClientWaitText(HTTP_E_TOTAL_TIMEOUT, this.options, ""))
|
|
2493
|
+
return true
|
|
2494
|
+
}
|
|
2495
|
+
return false
|
|
2496
|
+
}
|
|
2497
|
+
|
|
2498
|
+
/** Closes the connection, if one is open: an https one with its close_notify, its keys wiped. */
|
|
2499
|
+
close(): void {
|
|
2500
|
+
const conn: TlsRecordClient | null = this.tls
|
|
2501
|
+
if (conn !== null) {
|
|
2502
|
+
httpClientTlsClose(conn, this.fd)
|
|
2503
|
+
this.tls = null
|
|
2504
|
+
}
|
|
2505
|
+
if (this.fd >= 0) {
|
|
2506
|
+
netClose(this.fd)
|
|
2507
|
+
this.fd = -1
|
|
2508
|
+
}
|
|
2509
|
+
}
|
|
2510
|
+
|
|
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
|
+
*/
|
|
2516
|
+
release(pool: FetchPool | null): void {
|
|
2517
|
+
if (
|
|
2518
|
+
pool !== null &&
|
|
2519
|
+
this.fd >= 0 &&
|
|
2520
|
+
this.tls === null &&
|
|
2521
|
+
this.options.outbound === null &&
|
|
2522
|
+
this.parser.keepAlive() &&
|
|
2523
|
+
this.parser.buffered() === 0
|
|
2524
|
+
) {
|
|
2525
|
+
pool.put(this.route, this.fd)
|
|
2526
|
+
this.fd = -1
|
|
2527
|
+
return
|
|
2528
|
+
}
|
|
2529
|
+
this.close()
|
|
2530
|
+
}
|
|
2531
|
+
}
|
|
2532
|
+
|
|
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> => {
|
|
2564
|
+
if (conn.overdue()) {
|
|
2565
|
+
return -1
|
|
2566
|
+
}
|
|
2567
|
+
let n: i32 = netRead(conn.fd, conn.rbuf, HTTP_CLIENT_ZERO, want)
|
|
2568
|
+
while (n === HTTP_CLIENT_WOULD_BLOCK) {
|
|
2569
|
+
const ready = await httpClientWaitPeerAsync(conn, false)
|
|
2570
|
+
if (!ready) {
|
|
2571
|
+
return -1
|
|
2572
|
+
}
|
|
2573
|
+
if (conn.overdue()) {
|
|
2574
|
+
return -1
|
|
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) {
|
|
2596
|
+
if (conn.overdue()) {
|
|
2597
|
+
return false
|
|
2598
|
+
}
|
|
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
|
|
2723
|
+
}
|
|
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) {
|
|
2765
|
+
conn.gotByte = true
|
|
2766
|
+
conn.parser.feed(conn.plain, HTTP_CLIENT_ZERO, got)
|
|
2767
|
+
return true
|
|
2768
|
+
}
|
|
2769
|
+
if (got === 0) {
|
|
2770
|
+
// The server's close_notify: the orderly end of its stream.
|
|
2771
|
+
conn.parser.finish()
|
|
2772
|
+
return true
|
|
2773
|
+
}
|
|
2774
|
+
conn.lost = true
|
|
2775
|
+
httpClientTlsFault(tls, conn.fault)
|
|
2776
|
+
return false
|
|
2777
|
+
}
|
|
2778
|
+
|
|
2779
|
+
/** The parser's next event, reading as it needs; -1 with the fault set. */
|
|
2780
|
+
const httpClientPumpAsync = async (conn: HttpClientConn): Promise<i32> => {
|
|
2781
|
+
let event: i32 = conn.parser.next()
|
|
2782
|
+
while (event === HTTP1_NEED_MORE) {
|
|
2783
|
+
const filled = await httpClientFillAsync(conn)
|
|
2784
|
+
if (!filled) {
|
|
2785
|
+
return -1
|
|
2786
|
+
}
|
|
2787
|
+
event = conn.parser.next()
|
|
2788
|
+
}
|
|
2789
|
+
if (event === HTTP1_ERROR || event === HTTP1_CLOSED) {
|
|
2790
|
+
conn.lost = httpClientParserFault(conn.parser, event, conn.options, conn.fault)
|
|
2791
|
+
return -1
|
|
2792
|
+
}
|
|
2793
|
+
return event
|
|
2794
|
+
}
|
|
2795
|
+
|
|
2796
|
+
/** Writes `bytes`, through TLS on an https connection, parking the task while the socket is full; false with the fault set. */
|
|
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
|
+
}
|
|
2803
|
+
let at: i32 = 0
|
|
2804
|
+
const end: i32 = toI32(bytes.length)
|
|
2805
|
+
while (at < end) {
|
|
2806
|
+
const n: i32 = tls.write(bytes, at, end - at)
|
|
2807
|
+
if (n > 0) {
|
|
2808
|
+
at += n
|
|
2809
|
+
} else if (n !== TLS_RECORD_AGAIN || tls.outputEnd === tls.outputStart) {
|
|
2810
|
+
conn.lost = true
|
|
2811
|
+
httpClientTlsFault(tls, conn.fault)
|
|
2812
|
+
return false
|
|
2813
|
+
}
|
|
2814
|
+
const flushed = await httpClientFlushTlsAsync(conn, tls)
|
|
2815
|
+
if (!flushed) {
|
|
2816
|
+
return false
|
|
2817
|
+
}
|
|
2818
|
+
}
|
|
2819
|
+
const done = await httpClientFlushTlsAsync(conn, tls)
|
|
2820
|
+
return done
|
|
2821
|
+
}
|
|
2822
|
+
|
|
2823
|
+
/**
|
|
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.
|
|
2928
|
+
*/
|
|
2929
|
+
const httpClientDialAsync = async (conn: HttpClientConn, host: string, port: i32): Promise<i32> => {
|
|
2930
|
+
const start: i64 = monotonicNanos()
|
|
2931
|
+
const budget: i32 = conn.options.connectTimeoutMs
|
|
2932
|
+
let until: i64 = budget > 0 ? start + toI64(budget) * HTTP_CLIENT_NS_PER_MS : HTTP_CLIENT_NEVER
|
|
2933
|
+
let code: i32 = HTTP_E_CONNECT_TIMEOUT
|
|
2934
|
+
if (conn.deadline < HTTP_CLIENT_NEVER && conn.deadline <= until) {
|
|
2935
|
+
until = conn.deadline
|
|
2936
|
+
code = HTTP_E_TOTAL_TIMEOUT
|
|
2937
|
+
}
|
|
2938
|
+
if (until <= start) {
|
|
2939
|
+
conn.fault.fail(code, httpClientWaitText(code, conn.options, `no time was left to connect to ${host}`))
|
|
2940
|
+
return -1
|
|
2941
|
+
}
|
|
2942
|
+
const addresses: u8[] = new Array<u8>(DNS_RESOLVE_MAX_ADDRESSES * DNS_ADDRESS_BYTES)
|
|
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)
|
|
2946
|
+
if (usable < 0) {
|
|
2947
|
+
return -1
|
|
2948
|
+
}
|
|
2949
|
+
const one: u8[] = new Array<u8>(DNS_ADDRESS_BYTES)
|
|
2950
|
+
let last: i32 = 0
|
|
2951
|
+
for (let i: i32 = 0; i < usable && i < DNS_RESOLVE_MAX_ADDRESSES; i += 1) {
|
|
2952
|
+
copyBytes(one, 0, addresses, i * DNS_ADDRESS_BYTES, DNS_ADDRESS_BYTES)
|
|
2953
|
+
const fd: i32 = tcpConnect(one)
|
|
2954
|
+
if (fd < 0) {
|
|
2955
|
+
last = fd
|
|
2956
|
+
continue
|
|
2957
|
+
}
|
|
2958
|
+
const waited = await httpClientWaitAsync(fd, true, until, code)
|
|
2959
|
+
if (waited !== HTTP_E_NONE) {
|
|
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
|
+
)
|
|
2969
|
+
return -1
|
|
2970
|
+
}
|
|
2971
|
+
const result: i32 = connectResult(fd)
|
|
2972
|
+
if (result === 0) {
|
|
2973
|
+
return fd
|
|
2974
|
+
}
|
|
2975
|
+
netClose(fd)
|
|
2976
|
+
last = result
|
|
2977
|
+
}
|
|
2978
|
+
conn.fault.fail(HTTP_E_REFUSED, `could not connect to ${host} port ${port} (errno ${-last})`)
|
|
2979
|
+
return -1
|
|
2980
|
+
}
|
|
2981
|
+
|
|
2982
|
+
/**
|
|
2983
|
+
* Makes `conn` a connection to where `url` goes: one the pool kept when
|
|
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.
|
|
2987
|
+
*/
|
|
2988
|
+
const httpClientOpenAsync = async (
|
|
2989
|
+
conn: HttpClientConn,
|
|
2990
|
+
url: Url,
|
|
2991
|
+
pool: FetchPool | null,
|
|
2992
|
+
fresh: boolean
|
|
2993
|
+
): Promise<boolean> => {
|
|
2994
|
+
const secure: boolean = url.scheme === "https"
|
|
2995
|
+
const way: HttpClientRoute | null = httpClientRoute(
|
|
2996
|
+
url,
|
|
2997
|
+
conn.options,
|
|
2998
|
+
conn.httpProxy,
|
|
2999
|
+
conn.httpsProxy,
|
|
3000
|
+
conn.noProxy,
|
|
3001
|
+
conn.fault
|
|
3002
|
+
)
|
|
3003
|
+
if (way === null) {
|
|
3004
|
+
return false
|
|
3005
|
+
}
|
|
3006
|
+
conn.route = way.route
|
|
3007
|
+
conn.parser = httpClientParser(conn.options)
|
|
3008
|
+
conn.reused = false
|
|
3009
|
+
if (pool !== null && !fresh && !secure && conn.options.outbound === null) {
|
|
3010
|
+
const kept: i32 = pool.take(way.route)
|
|
3011
|
+
if (kept >= 0) {
|
|
3012
|
+
conn.fd = kept
|
|
3013
|
+
conn.reused = true
|
|
3014
|
+
return true
|
|
3015
|
+
}
|
|
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
|
+
}
|
|
3024
|
+
const fd: i32 = await httpClientDialAsync(conn, way.dialHost, way.dialPort)
|
|
3025
|
+
if (fd < 0) {
|
|
3026
|
+
return false
|
|
3027
|
+
}
|
|
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
|
+
}
|
|
3048
|
+
return true
|
|
3049
|
+
}
|
|
3050
|
+
|
|
3051
|
+
/** Writes the request on `conn` and reads up to its final response's head; false with the fault set. */
|
|
3052
|
+
const httpClientSendAsync = async (conn: HttpClientConn, url: Url, hop: HttpClientHop): Promise<boolean> => {
|
|
3053
|
+
const head: u8[] | null = httpClientRequestHead(
|
|
3054
|
+
url,
|
|
3055
|
+
hop.method,
|
|
3056
|
+
hop.names,
|
|
3057
|
+
hop.values,
|
|
3058
|
+
hop.body,
|
|
3059
|
+
conn.route.startsWith("proxy ") ? conn.httpProxy : "",
|
|
3060
|
+
conn.fault
|
|
3061
|
+
)
|
|
3062
|
+
if (head === null) {
|
|
3063
|
+
return false
|
|
3064
|
+
}
|
|
3065
|
+
conn.gotByte = false
|
|
3066
|
+
conn.lost = false
|
|
3067
|
+
conn.parser.expect(hop.method === "HEAD", false)
|
|
3068
|
+
const wrote = await httpClientWriteAsync(conn, head)
|
|
3069
|
+
if (!wrote) {
|
|
3070
|
+
return false
|
|
3071
|
+
}
|
|
3072
|
+
const body: u8[] | null = hop.body
|
|
3073
|
+
if (body !== null) {
|
|
3074
|
+
const sent = await httpClientWriteAsync(conn, body)
|
|
3075
|
+
if (!sent) {
|
|
3076
|
+
return false
|
|
3077
|
+
}
|
|
3078
|
+
}
|
|
3079
|
+
let event: i32 = await httpClientPumpAsync(conn)
|
|
3080
|
+
while (event === HTTP1_INFORMATIONAL) {
|
|
3081
|
+
event = await httpClientPumpAsync(conn)
|
|
3082
|
+
}
|
|
3083
|
+
if (event < 0) {
|
|
3084
|
+
return false
|
|
3085
|
+
}
|
|
3086
|
+
if (event !== HTTP1_HEAD) {
|
|
3087
|
+
conn.fault.fail(HTTP_E_PROTOCOL, `the response ended before its head (event ${event})`)
|
|
3088
|
+
return false
|
|
3089
|
+
}
|
|
3090
|
+
return true
|
|
3091
|
+
}
|
|
3092
|
+
|
|
3093
|
+
/**
|
|
3094
|
+
* Reads the body into `res`, at most `limit` bytes: 1 at its end, 0 when it
|
|
3095
|
+
* passed `limit` (the connection is then not reusable), -1 with the fault set.
|
|
3096
|
+
*/
|
|
3097
|
+
const httpClientBodyAsync = async (conn: HttpClientConn, res: FetchResponse, limit: i64): Promise<i32> => {
|
|
3098
|
+
let buf: u8[] = new Array<u8>(0)
|
|
3099
|
+
let len: i32 = 0
|
|
3100
|
+
let event: i32 = await httpClientPumpAsync(conn)
|
|
3101
|
+
while (event !== HTTP1_END) {
|
|
3102
|
+
if (event < 0) {
|
|
3103
|
+
return -1
|
|
3104
|
+
}
|
|
3105
|
+
if (event === HTTP1_BODY) {
|
|
3106
|
+
const take: i32 = conn.parser.bodyLen
|
|
3107
|
+
const need: i64 = toI64(len) + toI64(take)
|
|
3108
|
+
if (need > limit) {
|
|
3109
|
+
return 0
|
|
3110
|
+
}
|
|
3111
|
+
if (need > HTTP_CLIENT_ASYNC_BODY_MAX) {
|
|
3112
|
+
// A raised maxBodyBytes cannot carry a body past one array's reach.
|
|
3113
|
+
conn.fault.fail(
|
|
3114
|
+
HTTP_E_BODY_TOO_LARGE,
|
|
3115
|
+
`the body is larger than one array holds (${HTTP_CLIENT_ASYNC_BODY_MAX} bytes)`
|
|
3116
|
+
)
|
|
3117
|
+
return -1
|
|
3118
|
+
}
|
|
3119
|
+
if (need > toI64(buf.length)) {
|
|
3120
|
+
let room: i64 = toI64(buf.length) * toI64(2)
|
|
3121
|
+
if (room < need) {
|
|
3122
|
+
room = need
|
|
3123
|
+
}
|
|
3124
|
+
if (room > HTTP_CLIENT_ASYNC_BODY_MAX) {
|
|
3125
|
+
room = HTTP_CLIENT_ASYNC_BODY_MAX
|
|
3126
|
+
}
|
|
3127
|
+
const grown: u8[] = new Array<u8>(toI32(room))
|
|
3128
|
+
copyBytes(grown, 0, buf, 0, len)
|
|
3129
|
+
buf = grown
|
|
3130
|
+
}
|
|
3131
|
+
copyBytes(buf, len, conn.parser.body, conn.parser.bodyOff, take)
|
|
3132
|
+
len += take
|
|
3133
|
+
}
|
|
3134
|
+
event = await httpClientPumpAsync(conn)
|
|
3135
|
+
}
|
|
3136
|
+
if (len === toI32(buf.length)) {
|
|
3137
|
+
res.body = buf
|
|
3138
|
+
} else {
|
|
3139
|
+
const exact: u8[] = new Array<u8>(len)
|
|
3140
|
+
copyBytes(exact, 0, buf, 0, len)
|
|
3141
|
+
res.body = exact
|
|
3142
|
+
}
|
|
3143
|
+
return 1
|
|
3144
|
+
}
|
|
3145
|
+
|
|
3146
|
+
/**
|
|
3147
|
+
* One request and its whole response on `conn`, once more on a fresh
|
|
3148
|
+
* connection when a kept one turns out to be gone before any byte of an
|
|
3149
|
+
* idempotent request's answer came. Null with the fault set.
|
|
3150
|
+
*/
|
|
3151
|
+
const httpClientExchangeAsync = async (
|
|
3152
|
+
conn: HttpClientConn,
|
|
3153
|
+
url: Url,
|
|
3154
|
+
hop: HttpClientHop,
|
|
3155
|
+
pool: FetchPool | null,
|
|
3156
|
+
redirectable: boolean
|
|
3157
|
+
): Promise<FetchResponse | null> => {
|
|
3158
|
+
for (let attempt: i32 = 0; attempt < 2; attempt += 1) {
|
|
3159
|
+
const opened = await httpClientOpenAsync(conn, url, pool, attempt > 0)
|
|
3160
|
+
if (!opened) {
|
|
3161
|
+
return null
|
|
3162
|
+
}
|
|
3163
|
+
const sent = await httpClientSendAsync(conn, url, hop)
|
|
3164
|
+
if (sent) {
|
|
3165
|
+
const res: FetchResponse = new FetchResponse()
|
|
3166
|
+
res.status = conn.parser.status
|
|
3167
|
+
res.reason = conn.parser.reason
|
|
3168
|
+
res.url = httpClientUrlText(url)
|
|
3169
|
+
for (
|
|
3170
|
+
let i: i32 = 0;
|
|
3171
|
+
i < toI32(conn.parser.names.length) && i < toI32(conn.parser.values.length);
|
|
3172
|
+
i += 1
|
|
3173
|
+
) {
|
|
3174
|
+
res.names.push(conn.parser.names[i])
|
|
3175
|
+
res.values.push(conn.parser.values[i])
|
|
3176
|
+
}
|
|
3177
|
+
// A redirect's own body is read only far enough to keep its connection.
|
|
3178
|
+
const hopping: boolean =
|
|
3179
|
+
redirectable && httpClientIsRedirect(res.status) && res.header("location") !== null
|
|
3180
|
+
const limit: i64 = hopping ? toI64(HTTP_CLIENT_DRAIN_BYTES) : httpClientBodyCap(conn.options)
|
|
3181
|
+
const read: i32 = await httpClientBodyAsync(conn, res, limit)
|
|
3182
|
+
if (read < 0) {
|
|
3183
|
+
conn.close()
|
|
3184
|
+
if (!hopping) {
|
|
3185
|
+
return null
|
|
3186
|
+
}
|
|
3187
|
+
// As fetchSync's drain: a redirect's body that fails to read costs
|
|
3188
|
+
// only its connection, never the fetch.
|
|
3189
|
+
conn.fault.fail(HTTP_E_NONE, "")
|
|
3190
|
+
} else if (read === 0) {
|
|
3191
|
+
conn.close()
|
|
3192
|
+
} else {
|
|
3193
|
+
conn.release(pool)
|
|
3194
|
+
}
|
|
3195
|
+
return res
|
|
3196
|
+
}
|
|
3197
|
+
const retry: boolean = conn.reused && conn.lost && !conn.gotByte && httpClientIdempotent(hop.method)
|
|
3198
|
+
conn.close()
|
|
3199
|
+
if (!retry) {
|
|
3200
|
+
return null
|
|
3201
|
+
}
|
|
3202
|
+
}
|
|
3203
|
+
return null
|
|
3204
|
+
}
|
|
3205
|
+
|
|
3206
|
+
/** `fetch` before its answer is wrapped: the response, or null with `fault` set. */
|
|
3207
|
+
const httpClientFetchAsync = async (
|
|
3208
|
+
text: string,
|
|
3209
|
+
init: RequestInit,
|
|
3210
|
+
fault: HttpClientFault
|
|
3211
|
+
): Promise<FetchResponse | null> => {
|
|
3212
|
+
const options: HttpOptions = init.options
|
|
3213
|
+
const conn: HttpClientConn = new HttpClientConn(options)
|
|
3214
|
+
conn.fault = fault
|
|
3215
|
+
let url: Url | null = httpClientTarget(text, options, fault)
|
|
3216
|
+
if (url === null) {
|
|
3217
|
+
return null
|
|
3218
|
+
}
|
|
3219
|
+
const hop: HttpClientHop = new HttpClientHop(init.method, init.body, init.names, init.values)
|
|
3220
|
+
while (url !== null) {
|
|
3221
|
+
const res: FetchResponse | null = await httpClientExchangeAsync(
|
|
3222
|
+
conn,
|
|
3223
|
+
url,
|
|
3224
|
+
hop,
|
|
3225
|
+
init.pool,
|
|
3226
|
+
options.followRedirects
|
|
3227
|
+
)
|
|
3228
|
+
if (res === null) {
|
|
3229
|
+
return null
|
|
3230
|
+
}
|
|
3231
|
+
const location: string | null = res.header("location")
|
|
3232
|
+
if (!options.followRedirects || location === null || !httpClientIsRedirect(res.status)) {
|
|
3233
|
+
return res
|
|
3234
|
+
}
|
|
3235
|
+
url = httpClientRedirect(hop, options, url, res.status, location, fault)
|
|
3236
|
+
}
|
|
3237
|
+
return null
|
|
3238
|
+
}
|
|
3239
|
+
|
|
3240
|
+
/**
|
|
3241
|
+
* Fetches `url` without blocking the process: the task waits on the
|
|
3242
|
+
* executor while the connection is made, the request written and the
|
|
3243
|
+
* response read, so other tasks run meanwhile and `awaitAll(fetch(a),
|
|
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.
|
|
3249
|
+
*
|
|
3250
|
+
* @param url The absolute `http://` or `https://` URL to fetch.
|
|
3251
|
+
* @param init The method, fields, body, options and pool; null for a plain `GET`.
|
|
3252
|
+
* @returns The response with its body, or the failure: never a panic.
|
|
3253
|
+
*/
|
|
3254
|
+
export const fetch = async (
|
|
3255
|
+
url: string,
|
|
3256
|
+
init: RequestInit | null = null
|
|
3257
|
+
): Promise<Result<FetchResponse, FetchError>> => {
|
|
3258
|
+
const req: RequestInit = init !== null ? init : new RequestInit()
|
|
3259
|
+
const fault: HttpClientFault = new HttpClientFault()
|
|
3260
|
+
const res: FetchResponse | null = await httpClientFetchAsync(url, req, fault)
|
|
3261
|
+
if (res === null) {
|
|
3262
|
+
return Err(new FetchError(fault.code, `${httpErrorName(fault.code)}: ${fault.text}`))
|
|
3263
|
+
}
|
|
3264
|
+
return Ok(res)
|
|
3265
|
+
}
|