nish 0.36.0 → 0.37.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/docs/AI.md +43 -4
- package/docs/INSTALL.md +67 -58
- package/package.json +9 -5
- package/runtime/async.d.mts +2 -0
- package/runtime/async.mjs +7 -0
- package/runtime/nish.d.ts +736 -499
- package/runtime/nish.h +25 -0
- package/runtime/page.d.ts +53 -0
- package/runtime/page.mjs +146 -0
- package/runtime/runtime-async.c +557 -0
- package/runtime/runtime-wasm.c +63 -7
- package/scripts/build.sh +147 -5
- package/scripts/fuzz.sh +1 -0
- package/scripts/undocumented.txt +14 -0
- package/std/README.md +107 -82
- 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/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/net/fetch.ts +1117 -230
- package/std/net/handler.ts +18 -0
- package/std/net/hpack.ts +29 -26
- package/std/net/http-compress.ts +27 -21
- package/std/net/http1-client-codec.ts +29 -25
- package/std/net/http1-codec.ts +44 -87
- package/std/net/http1-server.ts +66 -54
- 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.ts +178 -160
- 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/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 +11 -10
- 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,27 @@
|
|
|
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 connect, every write and every read wait on the executor; the name
|
|
20
|
+
* lookup still blocks, and only `http://` is driven (an `https://` URL answers
|
|
21
|
+
* `HTTP_E_TLS` naming `fetchSync`, never a silent block). A `FetchPool` handed
|
|
22
|
+
* in through `RequestInit.pool` keeps idle connections per route, capped.
|
|
23
|
+
* Policy, proxies, redirects and error codes are the shared code below, so
|
|
24
|
+
* both clients behave alike. It does not run under `--emit-ts`.
|
|
6
25
|
*
|
|
7
26
|
* import { HttpOptions, HttpRequest, HttpResponse, fetchSync } from "nish/net/fetch";
|
|
8
27
|
*
|
|
@@ -96,6 +115,7 @@ import {
|
|
|
96
115
|
pollWait,
|
|
97
116
|
tcpConnect,
|
|
98
117
|
} from "nish:net"
|
|
118
|
+
import { readable, writable } from "nish:async"
|
|
99
119
|
import { getenv, monotonicNanos, wallClockNanos } from "nish:process"
|
|
100
120
|
import { PkiRoots, pkiLoadRoots, pkiLoadSystemRoots } from "nish/crypto/pki-roots"
|
|
101
121
|
import { TlsClient, TlsClientConfig, tlsClientIsIpLiteral } from "nish/net/tls/client"
|
|
@@ -157,6 +177,8 @@ const HTTP_CLIENT_PROXY_PORT: i32 = 1080
|
|
|
157
177
|
const HTTP_CLIENT_MAX_WAIT_MS: i64 = 3600000
|
|
158
178
|
/** Nanoseconds in a millisecond. */
|
|
159
179
|
const HTTP_CLIENT_NS_PER_MS: i64 = 1000000
|
|
180
|
+
/** The largest body the async fetch can hold in one array, whatever `maxBodyBytes` says. */
|
|
181
|
+
const HTTP_CLIENT_ASYNC_BODY_MAX: i64 = 2147483647
|
|
160
182
|
/** A deadline that never comes: 146 years of monotonic nanoseconds, far below the overflow of a sum with a timeout. */
|
|
161
183
|
const HTTP_CLIENT_NEVER: i64 = 4611686018 * 1000000000
|
|
162
184
|
/** netRead's and netWrite's answer when the socket has nothing ready. */
|
|
@@ -312,13 +334,7 @@ export class HttpResponse {
|
|
|
312
334
|
* @returns The value, or null when the response has no such field.
|
|
313
335
|
*/
|
|
314
336
|
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
|
|
337
|
+
return httpClientField(this.names, this.values, name)
|
|
322
338
|
}
|
|
323
339
|
}
|
|
324
340
|
|
|
@@ -480,12 +496,10 @@ export class FetchSyncClient {
|
|
|
480
496
|
this.ready = new Array<i32>(8)
|
|
481
497
|
this.rbuf = new Array<u8>(HTTP_CLIENT_READ_BYTES)
|
|
482
498
|
this.plain = []
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
this.noProxy = httpChooseProxy(getenv("no_proxy"), getenv("NO_PROXY"), true)
|
|
488
|
-
}
|
|
499
|
+
const proxies: string[] = httpClientEnvProxies(options)
|
|
500
|
+
this.httpProxy = proxies[0]
|
|
501
|
+
this.httpsProxy = proxies[1]
|
|
502
|
+
this.noProxy = proxies[2]
|
|
489
503
|
}
|
|
490
504
|
|
|
491
505
|
/**
|
|
@@ -516,29 +530,16 @@ export class FetchSyncClient {
|
|
|
516
530
|
this.drop()
|
|
517
531
|
}
|
|
518
532
|
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)
|
|
533
|
+
this.deadline = httpClientDeadline(this.options)
|
|
534
|
+
const fault: HttpClientFault = new HttpClientFault()
|
|
535
|
+
let url: Url | null = httpClientTarget(req.url, this.options, fault)
|
|
536
|
+
if (url === null) {
|
|
537
|
+
this.fail(fault.code, fault.text)
|
|
529
538
|
return null
|
|
530
539
|
}
|
|
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
|
|
540
|
+
const hop: HttpClientHop = new HttpClientHop(req.method, req.body, req.names, req.values)
|
|
540
541
|
while (url !== null) {
|
|
541
|
-
const res: HttpResponse | null = this.exchange(url, method, names, values, body)
|
|
542
|
+
const res: HttpResponse | null = this.exchange(url, hop.method, hop.names, hop.values, hop.body)
|
|
542
543
|
if (res === null) {
|
|
543
544
|
return null
|
|
544
545
|
}
|
|
@@ -546,70 +547,16 @@ export class FetchSyncClient {
|
|
|
546
547
|
if (!this.options.followRedirects || location === null || !httpClientIsRedirect(res.status)) {
|
|
547
548
|
return res
|
|
548
549
|
}
|
|
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")
|
|
550
|
+
const next: Url | null = httpClientRedirect(hop, this.options, url, res.status, location, fault)
|
|
551
|
+
if (next === null) {
|
|
552
|
+
return this.refuse(fault.code, fault.text)
|
|
596
553
|
}
|
|
597
554
|
this.drain()
|
|
598
|
-
hops += 1
|
|
599
555
|
url = next
|
|
600
556
|
}
|
|
601
557
|
return null
|
|
602
558
|
}
|
|
603
559
|
|
|
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
560
|
/** Closes the connection; the client can still fetch, on a new one. */
|
|
614
561
|
close(): void {
|
|
615
562
|
this.drop()
|
|
@@ -656,32 +603,22 @@ export class FetchSyncClient {
|
|
|
656
603
|
* a failure, with the error set.
|
|
657
604
|
*/
|
|
658
605
|
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}`
|
|
606
|
+
const fault: HttpClientFault = new HttpClientFault()
|
|
607
|
+
const way: HttpClientRoute | null = httpClientRoute(
|
|
608
|
+
url,
|
|
609
|
+
this.options,
|
|
610
|
+
this.httpProxy,
|
|
611
|
+
this.httpsProxy,
|
|
612
|
+
this.noProxy,
|
|
613
|
+
fault
|
|
614
|
+
)
|
|
615
|
+
if (way === null) {
|
|
616
|
+
this.fail(fault.code, fault.text)
|
|
617
|
+
return false
|
|
684
618
|
}
|
|
619
|
+
const proxy: Url | null = way.proxy
|
|
620
|
+
const port: i32 = way.port
|
|
621
|
+
const route: string = way.route
|
|
685
622
|
if (
|
|
686
623
|
this.fd >= 0 &&
|
|
687
624
|
this.route === route &&
|
|
@@ -697,9 +634,7 @@ export class FetchSyncClient {
|
|
|
697
634
|
if (url.scheme === "https" && !this.loadTrust()) {
|
|
698
635
|
return false
|
|
699
636
|
}
|
|
700
|
-
const
|
|
701
|
-
const dialPort: i32 = proxy !== null ? proxy.port : port
|
|
702
|
-
const fd: i32 = this.dial(dialHost, dialPort)
|
|
637
|
+
const fd: i32 = this.dial(way.dialHost, way.dialPort)
|
|
703
638
|
if (fd < 0) {
|
|
704
639
|
return false
|
|
705
640
|
}
|
|
@@ -854,57 +789,18 @@ export class FetchSyncClient {
|
|
|
854
789
|
values: string[],
|
|
855
790
|
body: u8[] | null
|
|
856
791
|
): 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)
|
|
792
|
+
const fault: HttpClientFault = new HttpClientFault()
|
|
793
|
+
const head: u8[] | null = httpClientRequestHead(
|
|
794
|
+
url,
|
|
795
|
+
method,
|
|
796
|
+
names,
|
|
797
|
+
values,
|
|
798
|
+
body,
|
|
799
|
+
this.route.startsWith("proxy ") ? this.httpProxy : "",
|
|
800
|
+
fault
|
|
801
|
+
)
|
|
903
802
|
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
|
-
)
|
|
803
|
+
this.fail(fault.code, fault.text)
|
|
908
804
|
return null
|
|
909
805
|
}
|
|
910
806
|
this.gotByte = false
|
|
@@ -960,28 +856,10 @@ export class FetchSyncClient {
|
|
|
960
856
|
}
|
|
961
857
|
event = this.parser.next()
|
|
962
858
|
}
|
|
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")
|
|
859
|
+
if (event === HTTP1_ERROR || event === HTTP1_CLOSED) {
|
|
860
|
+
const fault: HttpClientFault = new HttpClientFault()
|
|
861
|
+
this.lost = httpClientParserFault(this.parser, event, this.options, fault)
|
|
862
|
+
this.fail(fault.code, fault.text)
|
|
985
863
|
return -1
|
|
986
864
|
}
|
|
987
865
|
return event
|
|
@@ -1162,39 +1040,13 @@ export class FetchSyncClient {
|
|
|
1162
1040
|
this.fail(code, `no time was left to connect to ${host}`)
|
|
1163
1041
|
return -1
|
|
1164
1042
|
}
|
|
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
1043
|
const addresses: u8[] = new Array<u8>(DNS_RESOLVE_MAX_ADDRESSES * DNS_ADDRESS_BYTES)
|
|
1172
|
-
const
|
|
1173
|
-
const
|
|
1174
|
-
if (
|
|
1175
|
-
this.
|
|
1044
|
+
const fault: HttpClientFault = new HttpClientFault()
|
|
1045
|
+
const usable: i32 = httpClientResolve(host, port, this.options, start, until, code, addresses, fault)
|
|
1046
|
+
if (usable < 0) {
|
|
1047
|
+
this.fail(fault.code, fault.text)
|
|
1176
1048
|
return -1
|
|
1177
1049
|
}
|
|
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
|
-
)
|
|
1183
|
-
return -1
|
|
1184
|
-
}
|
|
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
1050
|
const one: u8[] = new Array<u8>(DNS_ADDRESS_BYTES)
|
|
1199
1051
|
let last: i32 = 0
|
|
1200
1052
|
for (let i: i32 = 0; i < usable && i < DNS_RESOLVE_MAX_ADDRESSES; i += 1) {
|
|
@@ -1434,13 +1286,7 @@ export class FetchSyncClient {
|
|
|
1434
1286
|
|
|
1435
1287
|
/** Sets the error for a wait that ended with `code`, `text` saying what timed out. */
|
|
1436
1288
|
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
|
-
}
|
|
1289
|
+
this.fail(code, httpClientWaitText(code, this.options, text))
|
|
1444
1290
|
}
|
|
1445
1291
|
|
|
1446
1292
|
/** Refuses a redirect: closes the connection, whose response is left unread, and fails. */
|
|
@@ -1814,3 +1660,1044 @@ const httpClientProxyAuth = (proxy: Url): string | null => {
|
|
|
1814
1660
|
}
|
|
1815
1661
|
return "Basic " + base64Encode(httpFieldBytes(user + ":" + password))
|
|
1816
1662
|
}
|
|
1663
|
+
|
|
1664
|
+
/** The first value of the field `name`, in any case, from parallel name and value lists; null when there is none. */
|
|
1665
|
+
const httpClientField = (names: string[], values: string[], name: string): string | null => {
|
|
1666
|
+
const lower: string = httpClientLower(name)
|
|
1667
|
+
for (let i: i32 = 0; i < toI32(names.length) && i < toI32(values.length); i += 1) {
|
|
1668
|
+
if (names[i] === lower) {
|
|
1669
|
+
return values[i]
|
|
1670
|
+
}
|
|
1671
|
+
}
|
|
1672
|
+
return null
|
|
1673
|
+
}
|
|
1674
|
+
|
|
1675
|
+
/**
|
|
1676
|
+
* The proxy settings the environment gives, as [http, https, no-proxy]; ""
|
|
1677
|
+
* for each when `useEnvProxy` is off. A CGI program (`REQUEST_METHOD` set)
|
|
1678
|
+
* ignores `HTTP_PROXY`, which a request's `Proxy:` header could have set.
|
|
1679
|
+
*/
|
|
1680
|
+
const httpClientEnvProxies = (options: HttpOptions): string[] => {
|
|
1681
|
+
if (!options.useEnvProxy) {
|
|
1682
|
+
return ["", "", ""]
|
|
1683
|
+
}
|
|
1684
|
+
const cgi: boolean = getenv("REQUEST_METHOD") !== null
|
|
1685
|
+
return [
|
|
1686
|
+
httpChooseProxy(getenv("http_proxy"), getenv("HTTP_PROXY"), !cgi),
|
|
1687
|
+
httpChooseProxy(getenv("https_proxy"), getenv("HTTPS_PROXY"), true),
|
|
1688
|
+
httpChooseProxy(getenv("no_proxy"), getenv("NO_PROXY"), true),
|
|
1689
|
+
]
|
|
1690
|
+
}
|
|
1691
|
+
|
|
1692
|
+
/** When a fetch starting now must be done by, on the monotonic clock; `HTTP_CLIENT_NEVER` with no total timeout. */
|
|
1693
|
+
const httpClientDeadline = (options: HttpOptions): i64 => {
|
|
1694
|
+
const total: i32 = httpClientTotalMs(options)
|
|
1695
|
+
return total > 0 ? monotonicNanos() + toI64(total) * HTTP_CLIENT_NS_PER_MS : HTTP_CLIENT_NEVER
|
|
1696
|
+
}
|
|
1697
|
+
|
|
1698
|
+
/** A failure a shared step found: an `HTTP_E_*` code and its sentence, before the code's name is put in front. */
|
|
1699
|
+
class HttpClientFault {
|
|
1700
|
+
code: i32 = 0
|
|
1701
|
+
text: string = ""
|
|
1702
|
+
|
|
1703
|
+
fail(code: i32, text: string): void {
|
|
1704
|
+
this.code = code
|
|
1705
|
+
this.text = text
|
|
1706
|
+
}
|
|
1707
|
+
}
|
|
1708
|
+
|
|
1709
|
+
/** Why the outbound policy refuses to let a URL name `url`'s host; "" when there is no policy or it allows the host. */
|
|
1710
|
+
const httpClientHostRefusal = (options: HttpOptions, url: Url): string => {
|
|
1711
|
+
const policy: OutboundPolicy | null = options.outbound
|
|
1712
|
+
if (policy === null || outboundHostAllowed(policy, url.host)) {
|
|
1713
|
+
return ""
|
|
1714
|
+
}
|
|
1715
|
+
return `${httpClientRedact(url)} names a host the outbound policy does not allow`
|
|
1716
|
+
}
|
|
1717
|
+
|
|
1718
|
+
/** The request's URL, parsed and checked against the scheme and the policy; null with `fault` set. */
|
|
1719
|
+
const httpClientTarget = (text: string, options: HttpOptions, fault: HttpClientFault): Url | null => {
|
|
1720
|
+
const url: Url | null = urlParse(text)
|
|
1721
|
+
if (url === null || (url.scheme !== "http" && url.scheme !== "https")) {
|
|
1722
|
+
fault.fail(HTTP_E_URL, `not an absolute http or https URL: ${httpClientRedact(url)}`)
|
|
1723
|
+
return null
|
|
1724
|
+
}
|
|
1725
|
+
const refusal: string = httpClientHostRefusal(options, url)
|
|
1726
|
+
if (refusal !== "") {
|
|
1727
|
+
fault.fail(HTTP_E_BLOCKED, refusal)
|
|
1728
|
+
return null
|
|
1729
|
+
}
|
|
1730
|
+
return url
|
|
1731
|
+
}
|
|
1732
|
+
|
|
1733
|
+
/** What the next hop of a fetch sends: the method, body and fields a redirect may rewrite, and the hops taken. */
|
|
1734
|
+
class HttpClientHop {
|
|
1735
|
+
method: string
|
|
1736
|
+
body: u8[] | null
|
|
1737
|
+
names: string[]
|
|
1738
|
+
values: string[]
|
|
1739
|
+
hops: i32 = 0
|
|
1740
|
+
|
|
1741
|
+
constructor(method: string, body: u8[] | null, names: string[], values: string[]) {
|
|
1742
|
+
this.method = method
|
|
1743
|
+
this.body = body
|
|
1744
|
+
this.names = []
|
|
1745
|
+
this.values = []
|
|
1746
|
+
for (let i: i32 = 0; i < toI32(names.length) && i < toI32(values.length); i += 1) {
|
|
1747
|
+
// Read before any call, which is where the bounds proof forgets a length.
|
|
1748
|
+
const name: string = names[i]
|
|
1749
|
+
const value: string = values[i]
|
|
1750
|
+
this.names.push(name)
|
|
1751
|
+
this.values.push(value)
|
|
1752
|
+
}
|
|
1753
|
+
}
|
|
1754
|
+
}
|
|
1755
|
+
|
|
1756
|
+
/**
|
|
1757
|
+
* Where a redirect from `url` to `location` goes, with `hop` rewritten for
|
|
1758
|
+
* it: credentials dropped across origins, a 303 (or a 301/302 after POST)
|
|
1759
|
+
* turned into GET. Null with `fault` set when the redirect is refused.
|
|
1760
|
+
*/
|
|
1761
|
+
const httpClientRedirect = (
|
|
1762
|
+
hop: HttpClientHop,
|
|
1763
|
+
options: HttpOptions,
|
|
1764
|
+
url: Url,
|
|
1765
|
+
status: i32,
|
|
1766
|
+
location: string,
|
|
1767
|
+
fault: HttpClientFault
|
|
1768
|
+
): Url | null => {
|
|
1769
|
+
const next: Url | null = urlResolve(url, location)
|
|
1770
|
+
const maxRedirects: i32 = httpClientMaxRedirects(options)
|
|
1771
|
+
if (hop.hops >= maxRedirects) {
|
|
1772
|
+
fault.fail(
|
|
1773
|
+
HTTP_E_TOO_MANY_REDIRECTS,
|
|
1774
|
+
`more than ${maxRedirects} redirects, the last to ${httpClientRedact(next)}`
|
|
1775
|
+
)
|
|
1776
|
+
return null
|
|
1777
|
+
}
|
|
1778
|
+
if (next === null || (next.scheme !== "http" && next.scheme !== "https")) {
|
|
1779
|
+
fault.fail(
|
|
1780
|
+
HTTP_E_REDIRECT_REFUSED,
|
|
1781
|
+
`a redirect to ${httpClientRedact(next)}, which is not an http or https URL`
|
|
1782
|
+
)
|
|
1783
|
+
return null
|
|
1784
|
+
}
|
|
1785
|
+
if (url.scheme === "https" && next.scheme === "http") {
|
|
1786
|
+
fault.fail(HTTP_E_REDIRECT_REFUSED, `a redirect from https to http (${httpClientRedact(next)})`)
|
|
1787
|
+
return null
|
|
1788
|
+
}
|
|
1789
|
+
const refusal: string = httpClientHostRefusal(options, next)
|
|
1790
|
+
if (refusal !== "") {
|
|
1791
|
+
fault.fail(HTTP_E_BLOCKED, refusal)
|
|
1792
|
+
return null
|
|
1793
|
+
}
|
|
1794
|
+
const from: string | null = urlOrigin(url)
|
|
1795
|
+
const to: string | null = urlOrigin(next)
|
|
1796
|
+
if (from === null || to === null || from !== to) {
|
|
1797
|
+
if (!options.crossOriginRedirects) {
|
|
1798
|
+
fault.fail(HTTP_E_REDIRECT_REFUSED, `a redirect to another origin (${httpClientRedact(next)})`)
|
|
1799
|
+
return null
|
|
1800
|
+
}
|
|
1801
|
+
// Credentials were meant for the first origin, not for wherever it points.
|
|
1802
|
+
httpClientDropField(hop.names, hop.values, "authorization")
|
|
1803
|
+
httpClientDropField(hop.names, hop.values, "proxy-authorization")
|
|
1804
|
+
httpClientDropField(hop.names, hop.values, "cookie")
|
|
1805
|
+
httpClientDropField(hop.names, hop.values, "host")
|
|
1806
|
+
}
|
|
1807
|
+
if (
|
|
1808
|
+
(status === 303 && hop.method !== "HEAD") ||
|
|
1809
|
+
((status === 301 || status === 302) && hop.method === "POST")
|
|
1810
|
+
) {
|
|
1811
|
+
hop.method = "GET"
|
|
1812
|
+
hop.body = null
|
|
1813
|
+
httpClientDropField(hop.names, hop.values, "content-type")
|
|
1814
|
+
}
|
|
1815
|
+
hop.hops += 1
|
|
1816
|
+
return next
|
|
1817
|
+
}
|
|
1818
|
+
|
|
1819
|
+
/** Where a connection for one URL goes: the address to dial, the proxy if any, and the route a kept connection must match. */
|
|
1820
|
+
class HttpClientRoute {
|
|
1821
|
+
proxy: Url | null = null
|
|
1822
|
+
dialHost: string = ""
|
|
1823
|
+
route: string = ""
|
|
1824
|
+
port: i32 = 0
|
|
1825
|
+
dialPort: i32 = 0
|
|
1826
|
+
}
|
|
1827
|
+
|
|
1828
|
+
/**
|
|
1829
|
+
* The route to `url` under the proxy settings: none under an outbound
|
|
1830
|
+
* policy, since a proxy would look the name up past the policy's address
|
|
1831
|
+
* check. Null with `fault` set when the proxy setting is malformed.
|
|
1832
|
+
*/
|
|
1833
|
+
const httpClientRoute = (
|
|
1834
|
+
url: Url,
|
|
1835
|
+
options: HttpOptions,
|
|
1836
|
+
httpProxy: string,
|
|
1837
|
+
httpsProxy: string,
|
|
1838
|
+
noProxy: string,
|
|
1839
|
+
fault: HttpClientFault
|
|
1840
|
+
): HttpClientRoute | null => {
|
|
1841
|
+
const way: HttpClientRoute = new HttpClientRoute()
|
|
1842
|
+
const port: i32 = url.port >= 0 ? url.port : urlDefaultPort(url.scheme)
|
|
1843
|
+
way.port = port
|
|
1844
|
+
const proxyText: string =
|
|
1845
|
+
options.outbound !== null ? "" : httpProxyFor(url.scheme, url.host, port, httpProxy, httpsProxy, noProxy)
|
|
1846
|
+
let proxy: Url | null = null
|
|
1847
|
+
if (proxyText !== "") {
|
|
1848
|
+
proxy = httpClientProxyUrl(proxyText)
|
|
1849
|
+
if (proxy === null) {
|
|
1850
|
+
fault.fail(
|
|
1851
|
+
HTTP_E_PROXY,
|
|
1852
|
+
`the proxy setting is not an http:// URL with a host: ${httpClientRedact(
|
|
1853
|
+
urlParse(proxyText.indexOf("://") >= 0 ? proxyText : "http://" + proxyText)
|
|
1854
|
+
)}`
|
|
1855
|
+
)
|
|
1856
|
+
return null
|
|
1857
|
+
}
|
|
1858
|
+
}
|
|
1859
|
+
const origin: string = `${url.scheme}://${httpClientHostText(url.host)}:${port}`
|
|
1860
|
+
way.route = origin
|
|
1861
|
+
way.dialHost = url.host
|
|
1862
|
+
way.dialPort = port
|
|
1863
|
+
if (proxy !== null) {
|
|
1864
|
+
way.proxy = proxy
|
|
1865
|
+
way.dialHost = proxy.host
|
|
1866
|
+
way.dialPort = proxy.port
|
|
1867
|
+
way.route =
|
|
1868
|
+
url.scheme === "http"
|
|
1869
|
+
? `proxy ${httpClientHostText(proxy.host)}:${proxy.port}`
|
|
1870
|
+
: `${origin} via ${httpClientHostText(proxy.host)}:${proxy.port}`
|
|
1871
|
+
}
|
|
1872
|
+
return way
|
|
1873
|
+
}
|
|
1874
|
+
|
|
1875
|
+
/**
|
|
1876
|
+
* The bytes of a request's head: `Host` added when the fields lack it, the
|
|
1877
|
+
* absolute-form target and the proxy's credentials when `httpProxy` is the
|
|
1878
|
+
* http proxy the request goes through ("" for none), and a
|
|
1879
|
+
* `Proxy-Authorization` field dropped when it is not. Null with `fault` set.
|
|
1880
|
+
*/
|
|
1881
|
+
const httpClientRequestHead = (
|
|
1882
|
+
url: Url,
|
|
1883
|
+
method: string,
|
|
1884
|
+
names: string[],
|
|
1885
|
+
values: string[],
|
|
1886
|
+
body: u8[] | null,
|
|
1887
|
+
httpProxy: string,
|
|
1888
|
+
fault: HttpClientFault
|
|
1889
|
+
): u8[] | null => {
|
|
1890
|
+
const viaProxy: boolean = httpProxy !== ""
|
|
1891
|
+
const sendNames: string[] = []
|
|
1892
|
+
const sendValues: string[] = []
|
|
1893
|
+
let hasHost: boolean = false
|
|
1894
|
+
let hasProxyAuth: boolean = false
|
|
1895
|
+
for (let i: i32 = 0; i < toI32(names.length) && i < toI32(values.length); i += 1) {
|
|
1896
|
+
// Read before any call, which is where the bounds proof forgets a length.
|
|
1897
|
+
const name: string = names[i]
|
|
1898
|
+
const value: string = values[i]
|
|
1899
|
+
hasHost = hasHost || httpClientNameIs(name, "host")
|
|
1900
|
+
const proxyAuth: boolean = httpClientNameIs(name, "proxy-authorization")
|
|
1901
|
+
if (proxyAuth && !viaProxy) {
|
|
1902
|
+
// Only an http proxy reads it: sent direct or through a tunnel, it
|
|
1903
|
+
// would hand the proxy's credentials to the origin.
|
|
1904
|
+
continue
|
|
1905
|
+
}
|
|
1906
|
+
hasProxyAuth = hasProxyAuth || proxyAuth
|
|
1907
|
+
sendNames.push(name)
|
|
1908
|
+
sendValues.push(value)
|
|
1909
|
+
}
|
|
1910
|
+
const hostText: string = httpClientHostText(url.host)
|
|
1911
|
+
const authority: string = url.port >= 0 ? `${hostText}:${url.port}` : hostText
|
|
1912
|
+
if (!hasHost) {
|
|
1913
|
+
sendNames.push("Host")
|
|
1914
|
+
sendValues.push(authority)
|
|
1915
|
+
}
|
|
1916
|
+
let target: string = url.path === "" ? "/" : url.path
|
|
1917
|
+
const query: string | null = url.query
|
|
1918
|
+
if (query !== null) {
|
|
1919
|
+
target = target + "?" + query
|
|
1920
|
+
}
|
|
1921
|
+
if (viaProxy) {
|
|
1922
|
+
target = `${url.scheme}://${authority}${target}`
|
|
1923
|
+
const proxy: Url | null = httpClientProxyUrl(httpProxy)
|
|
1924
|
+
const auth: string | null = proxy !== null ? httpClientProxyAuth(proxy) : ""
|
|
1925
|
+
if (auth === null) {
|
|
1926
|
+
fault.fail(HTTP_E_PROXY, "the proxy's user name or password is not valid percent-encoding")
|
|
1927
|
+
return null
|
|
1928
|
+
}
|
|
1929
|
+
if (auth !== "" && !hasProxyAuth) {
|
|
1930
|
+
sendNames.push("Proxy-Authorization")
|
|
1931
|
+
sendValues.push(auth)
|
|
1932
|
+
}
|
|
1933
|
+
}
|
|
1934
|
+
const bodyLength: i64 = body !== null ? toI64(body.length) : toI64(-2)
|
|
1935
|
+
const head: u8[] | null = http1RequestHead(method, target, sendNames, sendValues, bodyLength)
|
|
1936
|
+
if (head === null) {
|
|
1937
|
+
fault.fail(
|
|
1938
|
+
HTTP_E_REQUEST,
|
|
1939
|
+
`the request ${method} ${httpClientRedact(url)} was refused: a bad method, target or header field`
|
|
1940
|
+
)
|
|
1941
|
+
}
|
|
1942
|
+
return head
|
|
1943
|
+
}
|
|
1944
|
+
|
|
1945
|
+
/**
|
|
1946
|
+
* The failure behind a parser's `HTTP1_ERROR` or `HTTP1_CLOSED` `event`, in
|
|
1947
|
+
* `fault`: true when the connection was lost (closed before or part way
|
|
1948
|
+
* through the response), which is what lets a kept connection be retried.
|
|
1949
|
+
*/
|
|
1950
|
+
const httpClientParserFault = (
|
|
1951
|
+
parser: Http1ResponseParser,
|
|
1952
|
+
event: i32,
|
|
1953
|
+
options: HttpOptions,
|
|
1954
|
+
fault: HttpClientFault
|
|
1955
|
+
): boolean => {
|
|
1956
|
+
if (event === HTTP1_CLOSED) {
|
|
1957
|
+
fault.fail(HTTP_E_IO, "the server closed the connection before it answered")
|
|
1958
|
+
return true
|
|
1959
|
+
}
|
|
1960
|
+
const code: i32 = parser.error
|
|
1961
|
+
if (code === HTTP1_E_BODY_LIMIT) {
|
|
1962
|
+
fault.fail(HTTP_E_BODY_TOO_LARGE, `the body is larger than maxBodyBytes (${httpClientBodyCap(options)})`)
|
|
1963
|
+
return false
|
|
1964
|
+
}
|
|
1965
|
+
fault.fail(HTTP_E_PROTOCOL, `the response broke HTTP/1.1: ${parser.errorText} (http1 error ${code})`)
|
|
1966
|
+
// A response the server closed part way through is a connection lost, as
|
|
1967
|
+
// one closed before any byte is; it is never sent again, because a byte of
|
|
1968
|
+
// it came.
|
|
1969
|
+
return code === HTTP1_E_TRUNCATED
|
|
1970
|
+
}
|
|
1971
|
+
|
|
1972
|
+
/** The sentence for a failed wait: the total timeout and a broken poll loop have fixed ones, anything else `text`. */
|
|
1973
|
+
const httpClientWaitText = (code: i32, options: HttpOptions, text: string): string => {
|
|
1974
|
+
if (code === HTTP_E_TOTAL_TIMEOUT) {
|
|
1975
|
+
return `the fetch ran past ${httpClientTotalMs(options)} ms`
|
|
1976
|
+
}
|
|
1977
|
+
if (code === HTTP_E_IO) {
|
|
1978
|
+
return "the poll loop failed"
|
|
1979
|
+
}
|
|
1980
|
+
return text
|
|
1981
|
+
}
|
|
1982
|
+
|
|
1983
|
+
/**
|
|
1984
|
+
* Looks `host` up within `start`..`until` into `addresses` and keeps those
|
|
1985
|
+
* the outbound policy allows: how many to try, or -1 with `fault` set (`code`
|
|
1986
|
+
* names the deadline a lookup that timed out ran past). The lookup blocks.
|
|
1987
|
+
*/
|
|
1988
|
+
const httpClientResolve = (
|
|
1989
|
+
host: string,
|
|
1990
|
+
port: i32,
|
|
1991
|
+
options: HttpOptions,
|
|
1992
|
+
start: i64,
|
|
1993
|
+
until: i64,
|
|
1994
|
+
code: i32,
|
|
1995
|
+
addresses: u8[],
|
|
1996
|
+
fault: HttpClientFault
|
|
1997
|
+
): i32 => {
|
|
1998
|
+
let lookupMs: i64 = (until - start) / HTTP_CLIENT_NS_PER_MS
|
|
1999
|
+
if (lookupMs < toI64(1)) {
|
|
2000
|
+
lookupMs = toI64(1)
|
|
2001
|
+
} else if (lookupMs > toI64(2147483647)) {
|
|
2002
|
+
lookupMs = toI64(2147483647)
|
|
2003
|
+
}
|
|
2004
|
+
const ttls: i32[] = new Array<i32>(DNS_RESOLVE_MAX_ADDRESSES)
|
|
2005
|
+
const count: i32 = resolveHost(host, toI32(lookupMs), port, addresses, ttls)
|
|
2006
|
+
if (count === DNS_RESOLVE_TIMEOUT && until < HTTP_CLIENT_NEVER) {
|
|
2007
|
+
fault.fail(
|
|
2008
|
+
code,
|
|
2009
|
+
httpClientWaitText(code, options, `${host} was not looked up within ${options.connectTimeoutMs} ms`)
|
|
2010
|
+
)
|
|
2011
|
+
return -1
|
|
2012
|
+
}
|
|
2013
|
+
if (count <= 0) {
|
|
2014
|
+
fault.fail(
|
|
2015
|
+
HTTP_E_DNS,
|
|
2016
|
+
`${host} could not be looked up (${count === 0 ? "no address" : `resolver code ${count}`})`
|
|
2017
|
+
)
|
|
2018
|
+
return -1
|
|
2019
|
+
}
|
|
2020
|
+
let usable: i32 = count < DNS_RESOLVE_MAX_ADDRESSES ? count : DNS_RESOLVE_MAX_ADDRESSES
|
|
2021
|
+
const policy: OutboundPolicy | null = options.outbound
|
|
2022
|
+
if (policy !== null) {
|
|
2023
|
+
// Only the bytes checked here are connected to: no second lookup a rebinding answer could change.
|
|
2024
|
+
usable = outboundFilter(policy, addresses, usable)
|
|
2025
|
+
if (usable === 0) {
|
|
2026
|
+
fault.fail(
|
|
2027
|
+
HTTP_E_BLOCKED,
|
|
2028
|
+
`${host} resolves to ${outboundAddressText(addresses, 0)}, which the outbound policy does not allow`
|
|
2029
|
+
)
|
|
2030
|
+
return -1
|
|
2031
|
+
}
|
|
2032
|
+
}
|
|
2033
|
+
return usable
|
|
2034
|
+
}
|
|
2035
|
+
|
|
2036
|
+
// ---- The async fetch ---------------------------------------------------------
|
|
2037
|
+
|
|
2038
|
+
/** How many idle connections a `FetchPool` holds at most, over every route. */
|
|
2039
|
+
const FETCH_POOL_SLOTS: i32 = 64
|
|
2040
|
+
|
|
2041
|
+
/**
|
|
2042
|
+
* Why an async `fetch` failed: an `HTTP_E_*` code and its sentence, the
|
|
2043
|
+
* code's name first, as `FetchSyncClient.errorText` reads. The text never
|
|
2044
|
+
* holds a URL's credentials or query.
|
|
2045
|
+
*/
|
|
2046
|
+
export class FetchError {
|
|
2047
|
+
/** The `HTTP_E_*` code. */
|
|
2048
|
+
code: i32
|
|
2049
|
+
/** The code's name, a colon and what went wrong, such as `dns: example.invalid could not be looked up`. */
|
|
2050
|
+
text: string
|
|
2051
|
+
|
|
2052
|
+
/**
|
|
2053
|
+
* A failure with its code and text.
|
|
2054
|
+
* @param code The `HTTP_E_*` code.
|
|
2055
|
+
* @param text The code's name, a colon and the sentence.
|
|
2056
|
+
*/
|
|
2057
|
+
constructor(code: i32, text: string) {
|
|
2058
|
+
this.code = code
|
|
2059
|
+
this.text = text
|
|
2060
|
+
}
|
|
2061
|
+
}
|
|
2062
|
+
|
|
2063
|
+
/**
|
|
2064
|
+
* A response `fetch` answered, its body already read whole: the body is
|
|
2065
|
+
* read before `fetch` answers, up to `maxBodyBytes`, so `text()` and
|
|
2066
|
+
* `bytes()` are plain calls. `names` are lower-cased and in the order they
|
|
2067
|
+
* arrived, beside `values`; `url` is the URL that answered.
|
|
2068
|
+
*/
|
|
2069
|
+
export class FetchResponse {
|
|
2070
|
+
/** The status code, such as 200. */
|
|
2071
|
+
status: i32 = 0
|
|
2072
|
+
/** The reason phrase the server sent beside the status. */
|
|
2073
|
+
reason: string = ""
|
|
2074
|
+
/** The URL that answered, which differs from the request's after a redirect. */
|
|
2075
|
+
url: string = ""
|
|
2076
|
+
/** The header field names, lower-cased, in the order they arrived. */
|
|
2077
|
+
names: string[]
|
|
2078
|
+
/** The header field values, each beside its name in `names`. */
|
|
2079
|
+
values: string[]
|
|
2080
|
+
/** The body, de-chunked; empty for a `HEAD` or a status that has none. */
|
|
2081
|
+
body: u8[]
|
|
2082
|
+
|
|
2083
|
+
/** A response with no status, fields or body yet; `fetch` fills them in. */
|
|
2084
|
+
constructor() {
|
|
2085
|
+
this.names = []
|
|
2086
|
+
this.values = []
|
|
2087
|
+
this.body = []
|
|
2088
|
+
}
|
|
2089
|
+
|
|
2090
|
+
/**
|
|
2091
|
+
* The first value of the field `name`, in any case.
|
|
2092
|
+
* @param name The field name to look for.
|
|
2093
|
+
* @returns The value, or null when the response has no such field.
|
|
2094
|
+
*/
|
|
2095
|
+
header(name: string): string | null {
|
|
2096
|
+
return httpClientField(this.names, this.values, name)
|
|
2097
|
+
}
|
|
2098
|
+
|
|
2099
|
+
/**
|
|
2100
|
+
* The body as a string, its bytes unchanged: nothing checks that they are UTF-8.
|
|
2101
|
+
* @returns The body's text.
|
|
2102
|
+
*/
|
|
2103
|
+
text(): string {
|
|
2104
|
+
return String.fromBytes(this.body, HTTP_CLIENT_ZERO, toI32(this.body.length))
|
|
2105
|
+
}
|
|
2106
|
+
|
|
2107
|
+
/**
|
|
2108
|
+
* The body's bytes.
|
|
2109
|
+
* @returns The body, the same array as `body`.
|
|
2110
|
+
*/
|
|
2111
|
+
bytes(): u8[] {
|
|
2112
|
+
return this.body
|
|
2113
|
+
}
|
|
2114
|
+
}
|
|
2115
|
+
|
|
2116
|
+
/**
|
|
2117
|
+
* Connections an async `fetch` leaves open for the next one to the same
|
|
2118
|
+
* place, held by the caller and handed in through `RequestInit.pool`. At
|
|
2119
|
+
* most `maxIdlePerOrigin` wait per route and 64 in all; a kept connection
|
|
2120
|
+
* the server closed, or sent a byte on unasked, is closed when it is next
|
|
2121
|
+
* looked at. A fetch under an outbound policy never keeps or takes one.
|
|
2122
|
+
*/
|
|
2123
|
+
export class FetchPool {
|
|
2124
|
+
/** The most idle connections kept for one route (origin, or proxy). */
|
|
2125
|
+
maxIdlePerOrigin: i32
|
|
2126
|
+
private fds: i32[]
|
|
2127
|
+
private routes: string[]
|
|
2128
|
+
private probe: u8[]
|
|
2129
|
+
|
|
2130
|
+
/**
|
|
2131
|
+
* An empty pool.
|
|
2132
|
+
* @param maxIdlePerOrigin The most idle connections kept for one route; 0 keeps none.
|
|
2133
|
+
*/
|
|
2134
|
+
constructor(maxIdlePerOrigin: i32 = 4) {
|
|
2135
|
+
this.maxIdlePerOrigin = maxIdlePerOrigin
|
|
2136
|
+
this.fds = []
|
|
2137
|
+
this.routes = []
|
|
2138
|
+
this.probe = new Array<u8>(1)
|
|
2139
|
+
for (let i: i32 = 0; i < FETCH_POOL_SLOTS; i += 1) {
|
|
2140
|
+
this.fds.push(toI32(-1))
|
|
2141
|
+
this.routes.push("")
|
|
2142
|
+
}
|
|
2143
|
+
}
|
|
2144
|
+
|
|
2145
|
+
/**
|
|
2146
|
+
* How many idle connections the pool holds.
|
|
2147
|
+
* @returns The count, over every route.
|
|
2148
|
+
*/
|
|
2149
|
+
idle(): i32 {
|
|
2150
|
+
let count: i32 = 0
|
|
2151
|
+
for (let i: i32 = 0; i < FETCH_POOL_SLOTS; i += 1) {
|
|
2152
|
+
if (this.fds[i] >= 0) {
|
|
2153
|
+
count += 1
|
|
2154
|
+
}
|
|
2155
|
+
}
|
|
2156
|
+
return count
|
|
2157
|
+
}
|
|
2158
|
+
|
|
2159
|
+
/** Closes every idle connection; the pool can still keep new ones. */
|
|
2160
|
+
close(): void {
|
|
2161
|
+
for (let i: i32 = 0; i < FETCH_POOL_SLOTS; i += 1) {
|
|
2162
|
+
this.drop(i)
|
|
2163
|
+
}
|
|
2164
|
+
}
|
|
2165
|
+
|
|
2166
|
+
/**
|
|
2167
|
+
* A quiet idle connection for `route`, taken out of the pool; -1 for none.
|
|
2168
|
+
* A connection that reads anything, its end included, is closed instead.
|
|
2169
|
+
* @internal
|
|
2170
|
+
*/
|
|
2171
|
+
take(route: string): i32 {
|
|
2172
|
+
for (let i: i32 = 0; i < FETCH_POOL_SLOTS; i += 1) {
|
|
2173
|
+
if (this.fds[i] < 0 || this.routes[i] !== route) {
|
|
2174
|
+
continue
|
|
2175
|
+
}
|
|
2176
|
+
const fd: i32 = this.fds[i]
|
|
2177
|
+
if (netRead(fd, this.probe, HTTP_CLIENT_ZERO, 1) === HTTP_CLIENT_WOULD_BLOCK) {
|
|
2178
|
+
this.fds[i] = -1
|
|
2179
|
+
this.routes[i] = ""
|
|
2180
|
+
return fd
|
|
2181
|
+
}
|
|
2182
|
+
this.drop(i)
|
|
2183
|
+
}
|
|
2184
|
+
return -1
|
|
2185
|
+
}
|
|
2186
|
+
|
|
2187
|
+
/** Keeps `fd` for `route` when there is room, else closes it. @internal */
|
|
2188
|
+
put(route: string, fd: i32): void {
|
|
2189
|
+
let same: i32 = 0
|
|
2190
|
+
let free: i32 = -1
|
|
2191
|
+
for (let i: i32 = 0; i < FETCH_POOL_SLOTS; i += 1) {
|
|
2192
|
+
if (this.fds[i] < 0) {
|
|
2193
|
+
free = free < 0 ? i : free
|
|
2194
|
+
} else if (this.routes[i] === route) {
|
|
2195
|
+
same += 1
|
|
2196
|
+
}
|
|
2197
|
+
}
|
|
2198
|
+
if (same >= this.maxIdlePerOrigin || free < 0) {
|
|
2199
|
+
netClose(fd)
|
|
2200
|
+
return
|
|
2201
|
+
}
|
|
2202
|
+
this.fds[free] = fd
|
|
2203
|
+
this.routes[free] = route
|
|
2204
|
+
}
|
|
2205
|
+
|
|
2206
|
+
private drop(i: i32): void {
|
|
2207
|
+
if (this.fds[i] >= 0) {
|
|
2208
|
+
netClose(this.fds[i])
|
|
2209
|
+
}
|
|
2210
|
+
this.fds[i] = -1
|
|
2211
|
+
this.routes[i] = ""
|
|
2212
|
+
}
|
|
2213
|
+
}
|
|
2214
|
+
|
|
2215
|
+
/**
|
|
2216
|
+
* What an async `fetch` sends and how it behaves. `options` are
|
|
2217
|
+
* `HttpOptions` as `fetchSync` reads them, except that `readTimeoutMs`
|
|
2218
|
+
* bounds no wait (a wait has no deadline yet), `connectTimeoutMs` bounds
|
|
2219
|
+
* only the name lookup, and `totalTimeoutMs` is checked each time a wait
|
|
2220
|
+
* ends. `pool` keeps connections for later fetches; null closes each one
|
|
2221
|
+
* when its fetch is done.
|
|
2222
|
+
*/
|
|
2223
|
+
export class RequestInit {
|
|
2224
|
+
/** The request method, sent as given; `GET` by default. */
|
|
2225
|
+
method: string = "GET"
|
|
2226
|
+
/** The header field names, in the order they are sent. */
|
|
2227
|
+
names: string[]
|
|
2228
|
+
/** The header field values, each beside its name in `names`. */
|
|
2229
|
+
values: string[]
|
|
2230
|
+
/** Null for no body at all; an empty array sends `Content-Length: 0`. */
|
|
2231
|
+
body: u8[] | null = null
|
|
2232
|
+
/** The limits, policy and redirect and proxy settings (see above for the timeouts). */
|
|
2233
|
+
options: HttpOptions
|
|
2234
|
+
/** Where idle connections are kept between fetches; null for none. */
|
|
2235
|
+
pool: FetchPool | null = null
|
|
2236
|
+
|
|
2237
|
+
/** A `GET` with no fields, no body, default options and no pool. */
|
|
2238
|
+
constructor() {
|
|
2239
|
+
this.names = []
|
|
2240
|
+
this.values = []
|
|
2241
|
+
this.options = new HttpOptions()
|
|
2242
|
+
}
|
|
2243
|
+
|
|
2244
|
+
/**
|
|
2245
|
+
* Appends one header field; nothing is checked until the request is written.
|
|
2246
|
+
* @param name The field name.
|
|
2247
|
+
* @param value The field value; one holding a CR or LF makes the fetch fail.
|
|
2248
|
+
* @returns This init, so calls chain.
|
|
2249
|
+
*/
|
|
2250
|
+
header(name: string, value: string): RequestInit {
|
|
2251
|
+
this.names.push(name)
|
|
2252
|
+
this.values.push(value)
|
|
2253
|
+
return this
|
|
2254
|
+
}
|
|
2255
|
+
}
|
|
2256
|
+
|
|
2257
|
+
/** One connection an async fetch drives, and the state of the exchange on it. */
|
|
2258
|
+
class HttpClientConn {
|
|
2259
|
+
deadline: i64
|
|
2260
|
+
options: HttpOptions
|
|
2261
|
+
parser: Http1ResponseParser
|
|
2262
|
+
rbuf: u8[]
|
|
2263
|
+
fault: HttpClientFault
|
|
2264
|
+
route: string = ""
|
|
2265
|
+
httpProxy: string
|
|
2266
|
+
httpsProxy: string
|
|
2267
|
+
noProxy: string
|
|
2268
|
+
fd: i32 = -1
|
|
2269
|
+
gotByte: boolean = false
|
|
2270
|
+
lost: boolean = false
|
|
2271
|
+
reused: boolean = false
|
|
2272
|
+
|
|
2273
|
+
constructor(options: HttpOptions) {
|
|
2274
|
+
this.options = options
|
|
2275
|
+
this.deadline = httpClientDeadline(options)
|
|
2276
|
+
this.parser = httpClientParser(options)
|
|
2277
|
+
this.rbuf = new Array<u8>(HTTP_CLIENT_READ_BYTES)
|
|
2278
|
+
this.fault = new HttpClientFault()
|
|
2279
|
+
const proxies: string[] = httpClientEnvProxies(options)
|
|
2280
|
+
this.httpProxy = proxies[0]
|
|
2281
|
+
this.httpsProxy = proxies[1]
|
|
2282
|
+
this.noProxy = proxies[2]
|
|
2283
|
+
}
|
|
2284
|
+
|
|
2285
|
+
/** Fails with `HTTP_E_TOTAL_TIMEOUT` once the fetch's deadline has passed. */
|
|
2286
|
+
overdue(): boolean {
|
|
2287
|
+
if (this.deadline < HTTP_CLIENT_NEVER && monotonicNanos() >= this.deadline) {
|
|
2288
|
+
this.fault.fail(HTTP_E_TOTAL_TIMEOUT, httpClientWaitText(HTTP_E_TOTAL_TIMEOUT, this.options, ""))
|
|
2289
|
+
return true
|
|
2290
|
+
}
|
|
2291
|
+
return false
|
|
2292
|
+
}
|
|
2293
|
+
|
|
2294
|
+
/** Closes the connection, if one is open. */
|
|
2295
|
+
close(): void {
|
|
2296
|
+
if (this.fd >= 0) {
|
|
2297
|
+
netClose(this.fd)
|
|
2298
|
+
this.fd = -1
|
|
2299
|
+
}
|
|
2300
|
+
}
|
|
2301
|
+
|
|
2302
|
+
/** Hands the connection back to `pool` when the response left it clean to reuse, else closes it. */
|
|
2303
|
+
release(pool: FetchPool | null): void {
|
|
2304
|
+
if (
|
|
2305
|
+
pool !== null &&
|
|
2306
|
+
this.fd >= 0 &&
|
|
2307
|
+
this.options.outbound === null &&
|
|
2308
|
+
this.parser.keepAlive() &&
|
|
2309
|
+
this.parser.buffered() === 0
|
|
2310
|
+
) {
|
|
2311
|
+
pool.put(this.route, this.fd)
|
|
2312
|
+
this.fd = -1
|
|
2313
|
+
return
|
|
2314
|
+
}
|
|
2315
|
+
this.close()
|
|
2316
|
+
}
|
|
2317
|
+
}
|
|
2318
|
+
|
|
2319
|
+
/** One read of the response into the parser, parking the task until the socket has bytes; false with the fault set. */
|
|
2320
|
+
const httpClientFillAsync = async (conn: HttpClientConn): Promise<boolean> => {
|
|
2321
|
+
if (conn.overdue()) {
|
|
2322
|
+
return false
|
|
2323
|
+
}
|
|
2324
|
+
let n: i32 = netRead(conn.fd, conn.rbuf, HTTP_CLIENT_ZERO, HTTP_CLIENT_READ_BYTES)
|
|
2325
|
+
while (n === HTTP_CLIENT_WOULD_BLOCK) {
|
|
2326
|
+
const ready = await readable(conn.fd)
|
|
2327
|
+
if (!ready) {
|
|
2328
|
+
conn.fault.fail(HTTP_E_IO, "the wait for the server failed")
|
|
2329
|
+
return false
|
|
2330
|
+
}
|
|
2331
|
+
if (conn.overdue()) {
|
|
2332
|
+
return false
|
|
2333
|
+
}
|
|
2334
|
+
n = netRead(conn.fd, conn.rbuf, HTTP_CLIENT_ZERO, HTTP_CLIENT_READ_BYTES)
|
|
2335
|
+
}
|
|
2336
|
+
if (n > 0) {
|
|
2337
|
+
conn.gotByte = true
|
|
2338
|
+
conn.parser.feed(conn.rbuf, HTTP_CLIENT_ZERO, n)
|
|
2339
|
+
return true
|
|
2340
|
+
}
|
|
2341
|
+
if (n === 0) {
|
|
2342
|
+
conn.parser.finish()
|
|
2343
|
+
return true
|
|
2344
|
+
}
|
|
2345
|
+
conn.lost = true
|
|
2346
|
+
conn.fault.fail(HTTP_E_IO, `reading from the server failed (errno ${-n})`)
|
|
2347
|
+
return false
|
|
2348
|
+
}
|
|
2349
|
+
|
|
2350
|
+
/** The parser's next event, reading as it needs; -1 with the fault set. */
|
|
2351
|
+
const httpClientPumpAsync = async (conn: HttpClientConn): Promise<i32> => {
|
|
2352
|
+
let event: i32 = conn.parser.next()
|
|
2353
|
+
while (event === HTTP1_NEED_MORE) {
|
|
2354
|
+
const filled = await httpClientFillAsync(conn)
|
|
2355
|
+
if (!filled) {
|
|
2356
|
+
return -1
|
|
2357
|
+
}
|
|
2358
|
+
event = conn.parser.next()
|
|
2359
|
+
}
|
|
2360
|
+
if (event === HTTP1_ERROR || event === HTTP1_CLOSED) {
|
|
2361
|
+
conn.lost = httpClientParserFault(conn.parser, event, conn.options, conn.fault)
|
|
2362
|
+
return -1
|
|
2363
|
+
}
|
|
2364
|
+
return event
|
|
2365
|
+
}
|
|
2366
|
+
|
|
2367
|
+
/** Writes `bytes`, parking the task while the socket is full; false with the fault set. */
|
|
2368
|
+
const httpClientWriteAsync = async (conn: HttpClientConn, bytes: u8[]): Promise<boolean> => {
|
|
2369
|
+
let at: i32 = 0
|
|
2370
|
+
const end: i32 = toI32(bytes.length)
|
|
2371
|
+
while (at < end) {
|
|
2372
|
+
if (conn.overdue()) {
|
|
2373
|
+
return false
|
|
2374
|
+
}
|
|
2375
|
+
const n: i32 = netWrite(conn.fd, bytes, at, end - at)
|
|
2376
|
+
if (n > 0) {
|
|
2377
|
+
at += n
|
|
2378
|
+
} else if (n === HTTP_CLIENT_WOULD_BLOCK || n === 0) {
|
|
2379
|
+
const ready = await writable(conn.fd)
|
|
2380
|
+
if (!ready) {
|
|
2381
|
+
conn.fault.fail(HTTP_E_IO, "the wait for the server failed")
|
|
2382
|
+
return false
|
|
2383
|
+
}
|
|
2384
|
+
} else {
|
|
2385
|
+
conn.lost = true
|
|
2386
|
+
conn.fault.fail(HTTP_E_IO, `writing to the server failed (errno ${-n})`)
|
|
2387
|
+
return false
|
|
2388
|
+
}
|
|
2389
|
+
}
|
|
2390
|
+
return true
|
|
2391
|
+
}
|
|
2392
|
+
|
|
2393
|
+
/**
|
|
2394
|
+
* Looks `host` up (blocking, within `connectTimeoutMs`) and connects to its
|
|
2395
|
+
* addresses in turn, parking the task while each connect is in flight: the
|
|
2396
|
+
* connected fd, or -1 with the fault set.
|
|
2397
|
+
*/
|
|
2398
|
+
const httpClientDialAsync = async (conn: HttpClientConn, host: string, port: i32): Promise<i32> => {
|
|
2399
|
+
const start: i64 = monotonicNanos()
|
|
2400
|
+
const budget: i32 = conn.options.connectTimeoutMs
|
|
2401
|
+
let until: i64 = budget > 0 ? start + toI64(budget) * HTTP_CLIENT_NS_PER_MS : HTTP_CLIENT_NEVER
|
|
2402
|
+
let code: i32 = HTTP_E_CONNECT_TIMEOUT
|
|
2403
|
+
if (conn.deadline < HTTP_CLIENT_NEVER && conn.deadline <= until) {
|
|
2404
|
+
until = conn.deadline
|
|
2405
|
+
code = HTTP_E_TOTAL_TIMEOUT
|
|
2406
|
+
}
|
|
2407
|
+
if (until <= start) {
|
|
2408
|
+
conn.fault.fail(code, httpClientWaitText(code, conn.options, `no time was left to connect to ${host}`))
|
|
2409
|
+
return -1
|
|
2410
|
+
}
|
|
2411
|
+
const addresses: u8[] = new Array<u8>(DNS_RESOLVE_MAX_ADDRESSES * DNS_ADDRESS_BYTES)
|
|
2412
|
+
const usable: i32 = httpClientResolve(host, port, conn.options, start, until, code, addresses, conn.fault)
|
|
2413
|
+
if (usable < 0) {
|
|
2414
|
+
return -1
|
|
2415
|
+
}
|
|
2416
|
+
const one: u8[] = new Array<u8>(DNS_ADDRESS_BYTES)
|
|
2417
|
+
let last: i32 = 0
|
|
2418
|
+
for (let i: i32 = 0; i < usable && i < DNS_RESOLVE_MAX_ADDRESSES; i += 1) {
|
|
2419
|
+
copyBytes(one, 0, addresses, i * DNS_ADDRESS_BYTES, DNS_ADDRESS_BYTES)
|
|
2420
|
+
const fd: i32 = tcpConnect(one)
|
|
2421
|
+
if (fd < 0) {
|
|
2422
|
+
last = fd
|
|
2423
|
+
continue
|
|
2424
|
+
}
|
|
2425
|
+
const ready = await writable(fd)
|
|
2426
|
+
if (conn.overdue()) {
|
|
2427
|
+
netClose(fd)
|
|
2428
|
+
return -1
|
|
2429
|
+
}
|
|
2430
|
+
const result: i32 = ready ? connectResult(fd) : -5
|
|
2431
|
+
if (result === 0) {
|
|
2432
|
+
return fd
|
|
2433
|
+
}
|
|
2434
|
+
netClose(fd)
|
|
2435
|
+
last = result
|
|
2436
|
+
}
|
|
2437
|
+
conn.fault.fail(HTTP_E_REFUSED, `could not connect to ${host} port ${port} (errno ${-last})`)
|
|
2438
|
+
return -1
|
|
2439
|
+
}
|
|
2440
|
+
|
|
2441
|
+
/**
|
|
2442
|
+
* Makes `conn` a connection to where `url` goes: one the pool kept when
|
|
2443
|
+
* there is one, else a new one, through an http proxy when the settings say
|
|
2444
|
+
* so. False with the fault set; an https URL is refused before anything is
|
|
2445
|
+
* dialled, since its TLS handshake would block the process.
|
|
2446
|
+
*/
|
|
2447
|
+
const httpClientOpenAsync = async (
|
|
2448
|
+
conn: HttpClientConn,
|
|
2449
|
+
url: Url,
|
|
2450
|
+
pool: FetchPool | null,
|
|
2451
|
+
fresh: boolean
|
|
2452
|
+
): Promise<boolean> => {
|
|
2453
|
+
if (url.scheme === "https") {
|
|
2454
|
+
conn.fault.fail(
|
|
2455
|
+
HTTP_E_TLS,
|
|
2456
|
+
`${httpClientRedact(url)} is https, which the async fetch does not drive yet; use fetchSync`
|
|
2457
|
+
)
|
|
2458
|
+
return false
|
|
2459
|
+
}
|
|
2460
|
+
const way: HttpClientRoute | null = httpClientRoute(
|
|
2461
|
+
url,
|
|
2462
|
+
conn.options,
|
|
2463
|
+
conn.httpProxy,
|
|
2464
|
+
conn.httpsProxy,
|
|
2465
|
+
conn.noProxy,
|
|
2466
|
+
conn.fault
|
|
2467
|
+
)
|
|
2468
|
+
if (way === null) {
|
|
2469
|
+
return false
|
|
2470
|
+
}
|
|
2471
|
+
conn.route = way.route
|
|
2472
|
+
conn.parser = httpClientParser(conn.options)
|
|
2473
|
+
conn.reused = false
|
|
2474
|
+
if (pool !== null && !fresh && conn.options.outbound === null) {
|
|
2475
|
+
const kept: i32 = pool.take(way.route)
|
|
2476
|
+
if (kept >= 0) {
|
|
2477
|
+
conn.fd = kept
|
|
2478
|
+
conn.reused = true
|
|
2479
|
+
return true
|
|
2480
|
+
}
|
|
2481
|
+
}
|
|
2482
|
+
const fd: i32 = await httpClientDialAsync(conn, way.dialHost, way.dialPort)
|
|
2483
|
+
if (fd < 0) {
|
|
2484
|
+
return false
|
|
2485
|
+
}
|
|
2486
|
+
conn.fd = fd
|
|
2487
|
+
return true
|
|
2488
|
+
}
|
|
2489
|
+
|
|
2490
|
+
/** Writes the request on `conn` and reads up to its final response's head; false with the fault set. */
|
|
2491
|
+
const httpClientSendAsync = async (conn: HttpClientConn, url: Url, hop: HttpClientHop): Promise<boolean> => {
|
|
2492
|
+
const head: u8[] | null = httpClientRequestHead(
|
|
2493
|
+
url,
|
|
2494
|
+
hop.method,
|
|
2495
|
+
hop.names,
|
|
2496
|
+
hop.values,
|
|
2497
|
+
hop.body,
|
|
2498
|
+
conn.route.startsWith("proxy ") ? conn.httpProxy : "",
|
|
2499
|
+
conn.fault
|
|
2500
|
+
)
|
|
2501
|
+
if (head === null) {
|
|
2502
|
+
return false
|
|
2503
|
+
}
|
|
2504
|
+
conn.gotByte = false
|
|
2505
|
+
conn.lost = false
|
|
2506
|
+
conn.parser.expect(hop.method === "HEAD", false)
|
|
2507
|
+
const wrote = await httpClientWriteAsync(conn, head)
|
|
2508
|
+
if (!wrote) {
|
|
2509
|
+
return false
|
|
2510
|
+
}
|
|
2511
|
+
const body: u8[] | null = hop.body
|
|
2512
|
+
if (body !== null) {
|
|
2513
|
+
const sent = await httpClientWriteAsync(conn, body)
|
|
2514
|
+
if (!sent) {
|
|
2515
|
+
return false
|
|
2516
|
+
}
|
|
2517
|
+
}
|
|
2518
|
+
let event: i32 = await httpClientPumpAsync(conn)
|
|
2519
|
+
while (event === HTTP1_INFORMATIONAL) {
|
|
2520
|
+
event = await httpClientPumpAsync(conn)
|
|
2521
|
+
}
|
|
2522
|
+
if (event < 0) {
|
|
2523
|
+
return false
|
|
2524
|
+
}
|
|
2525
|
+
if (event !== HTTP1_HEAD) {
|
|
2526
|
+
conn.fault.fail(HTTP_E_PROTOCOL, `the response ended before its head (event ${event})`)
|
|
2527
|
+
return false
|
|
2528
|
+
}
|
|
2529
|
+
return true
|
|
2530
|
+
}
|
|
2531
|
+
|
|
2532
|
+
/**
|
|
2533
|
+
* Reads the body into `res`, at most `limit` bytes: 1 at its end, 0 when it
|
|
2534
|
+
* passed `limit` (the connection is then not reusable), -1 with the fault set.
|
|
2535
|
+
*/
|
|
2536
|
+
const httpClientBodyAsync = async (conn: HttpClientConn, res: FetchResponse, limit: i64): Promise<i32> => {
|
|
2537
|
+
let buf: u8[] = new Array<u8>(0)
|
|
2538
|
+
let len: i32 = 0
|
|
2539
|
+
let event: i32 = await httpClientPumpAsync(conn)
|
|
2540
|
+
while (event !== HTTP1_END) {
|
|
2541
|
+
if (event < 0) {
|
|
2542
|
+
return -1
|
|
2543
|
+
}
|
|
2544
|
+
if (event === HTTP1_BODY) {
|
|
2545
|
+
const take: i32 = conn.parser.bodyLen
|
|
2546
|
+
const need: i64 = toI64(len) + toI64(take)
|
|
2547
|
+
if (need > limit) {
|
|
2548
|
+
return 0
|
|
2549
|
+
}
|
|
2550
|
+
if (need > HTTP_CLIENT_ASYNC_BODY_MAX) {
|
|
2551
|
+
// A raised maxBodyBytes cannot carry a body past one array's reach.
|
|
2552
|
+
conn.fault.fail(
|
|
2553
|
+
HTTP_E_BODY_TOO_LARGE,
|
|
2554
|
+
`the body is larger than one array holds (${HTTP_CLIENT_ASYNC_BODY_MAX} bytes)`
|
|
2555
|
+
)
|
|
2556
|
+
return -1
|
|
2557
|
+
}
|
|
2558
|
+
if (need > toI64(buf.length)) {
|
|
2559
|
+
let room: i64 = toI64(buf.length) * toI64(2)
|
|
2560
|
+
if (room < need) {
|
|
2561
|
+
room = need
|
|
2562
|
+
}
|
|
2563
|
+
if (room > HTTP_CLIENT_ASYNC_BODY_MAX) {
|
|
2564
|
+
room = HTTP_CLIENT_ASYNC_BODY_MAX
|
|
2565
|
+
}
|
|
2566
|
+
const grown: u8[] = new Array<u8>(toI32(room))
|
|
2567
|
+
copyBytes(grown, 0, buf, 0, len)
|
|
2568
|
+
buf = grown
|
|
2569
|
+
}
|
|
2570
|
+
copyBytes(buf, len, conn.parser.body, conn.parser.bodyOff, take)
|
|
2571
|
+
len += take
|
|
2572
|
+
}
|
|
2573
|
+
event = await httpClientPumpAsync(conn)
|
|
2574
|
+
}
|
|
2575
|
+
if (len === toI32(buf.length)) {
|
|
2576
|
+
res.body = buf
|
|
2577
|
+
} else {
|
|
2578
|
+
const exact: u8[] = new Array<u8>(len)
|
|
2579
|
+
copyBytes(exact, 0, buf, 0, len)
|
|
2580
|
+
res.body = exact
|
|
2581
|
+
}
|
|
2582
|
+
return 1
|
|
2583
|
+
}
|
|
2584
|
+
|
|
2585
|
+
/**
|
|
2586
|
+
* One request and its whole response on `conn`, once more on a fresh
|
|
2587
|
+
* connection when a kept one turns out to be gone before any byte of an
|
|
2588
|
+
* idempotent request's answer came. Null with the fault set.
|
|
2589
|
+
*/
|
|
2590
|
+
const httpClientExchangeAsync = async (
|
|
2591
|
+
conn: HttpClientConn,
|
|
2592
|
+
url: Url,
|
|
2593
|
+
hop: HttpClientHop,
|
|
2594
|
+
pool: FetchPool | null,
|
|
2595
|
+
redirectable: boolean
|
|
2596
|
+
): Promise<FetchResponse | null> => {
|
|
2597
|
+
for (let attempt: i32 = 0; attempt < 2; attempt += 1) {
|
|
2598
|
+
const opened = await httpClientOpenAsync(conn, url, pool, attempt > 0)
|
|
2599
|
+
if (!opened) {
|
|
2600
|
+
return null
|
|
2601
|
+
}
|
|
2602
|
+
const sent = await httpClientSendAsync(conn, url, hop)
|
|
2603
|
+
if (sent) {
|
|
2604
|
+
const res: FetchResponse = new FetchResponse()
|
|
2605
|
+
res.status = conn.parser.status
|
|
2606
|
+
res.reason = conn.parser.reason
|
|
2607
|
+
res.url = httpClientUrlText(url)
|
|
2608
|
+
for (
|
|
2609
|
+
let i: i32 = 0;
|
|
2610
|
+
i < toI32(conn.parser.names.length) && i < toI32(conn.parser.values.length);
|
|
2611
|
+
i += 1
|
|
2612
|
+
) {
|
|
2613
|
+
res.names.push(conn.parser.names[i])
|
|
2614
|
+
res.values.push(conn.parser.values[i])
|
|
2615
|
+
}
|
|
2616
|
+
// A redirect's own body is read only far enough to keep its connection.
|
|
2617
|
+
const hopping: boolean =
|
|
2618
|
+
redirectable && httpClientIsRedirect(res.status) && res.header("location") !== null
|
|
2619
|
+
const limit: i64 = hopping ? toI64(HTTP_CLIENT_DRAIN_BYTES) : httpClientBodyCap(conn.options)
|
|
2620
|
+
const read: i32 = await httpClientBodyAsync(conn, res, limit)
|
|
2621
|
+
if (read < 0) {
|
|
2622
|
+
conn.close()
|
|
2623
|
+
if (!hopping) {
|
|
2624
|
+
return null
|
|
2625
|
+
}
|
|
2626
|
+
// As fetchSync's drain: a redirect's body that fails to read costs
|
|
2627
|
+
// only its connection, never the fetch.
|
|
2628
|
+
conn.fault.fail(HTTP_E_NONE, "")
|
|
2629
|
+
} else if (read === 0) {
|
|
2630
|
+
conn.close()
|
|
2631
|
+
} else {
|
|
2632
|
+
conn.release(pool)
|
|
2633
|
+
}
|
|
2634
|
+
return res
|
|
2635
|
+
}
|
|
2636
|
+
const retry: boolean = conn.reused && conn.lost && !conn.gotByte && httpClientIdempotent(hop.method)
|
|
2637
|
+
conn.close()
|
|
2638
|
+
if (!retry) {
|
|
2639
|
+
return null
|
|
2640
|
+
}
|
|
2641
|
+
}
|
|
2642
|
+
return null
|
|
2643
|
+
}
|
|
2644
|
+
|
|
2645
|
+
/** `fetch` before its answer is wrapped: the response, or null with `fault` set. */
|
|
2646
|
+
const httpClientFetchAsync = async (
|
|
2647
|
+
text: string,
|
|
2648
|
+
init: RequestInit,
|
|
2649
|
+
fault: HttpClientFault
|
|
2650
|
+
): Promise<FetchResponse | null> => {
|
|
2651
|
+
const options: HttpOptions = init.options
|
|
2652
|
+
const conn: HttpClientConn = new HttpClientConn(options)
|
|
2653
|
+
conn.fault = fault
|
|
2654
|
+
let url: Url | null = httpClientTarget(text, options, fault)
|
|
2655
|
+
if (url === null) {
|
|
2656
|
+
return null
|
|
2657
|
+
}
|
|
2658
|
+
const hop: HttpClientHop = new HttpClientHop(init.method, init.body, init.names, init.values)
|
|
2659
|
+
while (url !== null) {
|
|
2660
|
+
const res: FetchResponse | null = await httpClientExchangeAsync(
|
|
2661
|
+
conn,
|
|
2662
|
+
url,
|
|
2663
|
+
hop,
|
|
2664
|
+
init.pool,
|
|
2665
|
+
options.followRedirects
|
|
2666
|
+
)
|
|
2667
|
+
if (res === null) {
|
|
2668
|
+
return null
|
|
2669
|
+
}
|
|
2670
|
+
const location: string | null = res.header("location")
|
|
2671
|
+
if (!options.followRedirects || location === null || !httpClientIsRedirect(res.status)) {
|
|
2672
|
+
return res
|
|
2673
|
+
}
|
|
2674
|
+
url = httpClientRedirect(hop, options, url, res.status, location, fault)
|
|
2675
|
+
}
|
|
2676
|
+
return null
|
|
2677
|
+
}
|
|
2678
|
+
|
|
2679
|
+
/**
|
|
2680
|
+
* Fetches `url` without blocking the process: the task waits on the
|
|
2681
|
+
* executor while the connection is made, the request written and the
|
|
2682
|
+
* response read, so other tasks run meanwhile and `awaitAll(fetch(a),
|
|
2683
|
+
* fetch(b))` overlaps the two. The body is read whole, up to
|
|
2684
|
+
* `maxBodyBytes`, before the answer comes. Only http is driven this way: an
|
|
2685
|
+
* https URL answers `HTTP_E_TLS` (use `fetchSync`). The name lookup still
|
|
2686
|
+
* blocks. Policy, proxy, redirect and error rules are `fetchSync`'s.
|
|
2687
|
+
*
|
|
2688
|
+
* @param url The absolute `http://` URL to fetch.
|
|
2689
|
+
* @param init The method, fields, body, options and pool; null for a plain `GET`.
|
|
2690
|
+
* @returns The response with its body, or the failure: never a panic.
|
|
2691
|
+
*/
|
|
2692
|
+
export const fetch = async (
|
|
2693
|
+
url: string,
|
|
2694
|
+
init: RequestInit | null = null
|
|
2695
|
+
): Promise<Result<FetchResponse, FetchError>> => {
|
|
2696
|
+
const req: RequestInit = init !== null ? init : new RequestInit()
|
|
2697
|
+
const fault: HttpClientFault = new HttpClientFault()
|
|
2698
|
+
const res: FetchResponse | null = await httpClientFetchAsync(url, req, fault)
|
|
2699
|
+
if (res === null) {
|
|
2700
|
+
return Err(new FetchError(fault.code, `${httpErrorName(fault.code)}: ${fault.text}`))
|
|
2701
|
+
}
|
|
2702
|
+
return Ok(res)
|
|
2703
|
+
}
|