Scoop API

scoop:scoop.http:0.1.0

src/proxy.scoop

Selected production source · src/proxy.scoop

1package scoop.http
3import scoop.collections.emptyList
4import scoop.url.Url
6/**
7 * Builds an HTTP/1 absolute-form request from an HTTP URL, deriving Host and rejecting conflicting
8 * caller-supplied Host fields.
9 */
10public fun httpProxyRequest(url: Url, method: List<Byte> = "GET".toByteArray(),
11 fields: List<HttpField> = emptyList<HttpField>(), version: HttpVersion = HttpVersion.Http11): HttpRequestHead {
12 if (version == HttpVersion.Http2) throw IllegalArgumentException(Some("absolute-form requires HTTP/1"))
13 if (!httpToken(method)) throw IllegalArgumentException(Some("invalid HTTP method token"))
14 if (httpBytesEqual(method, "CONNECT".toByteArray()))
15 throw IllegalArgumentException(Some("CONNECT requires an authority-form target"))
16 val origin = url.httpOrigin()
17 if (origin.scheme != "http" && origin.scheme != "https")
18 throw IllegalArgumentException(Some("HTTP proxy request requires an http or https URL"))
19 val authority = origin.authority(url.authority!!.port != None)
20 return HttpRequestHead(version, method, HttpRequestTarget.Http1(url.httpAbsoluteTarget().toByteArray()),
21 proxyFields(fields, Some(authority)))
24/**
25 * Builds an authority-form CONNECT request for HTTP/1 or HTTP/2 using the URL's effective port.
26 */
27public fun httpConnectRequest(url: Url, fields: List<HttpField> = emptyList<HttpField>(),
28 version: HttpVersion = HttpVersion.Http11): HttpRequestHead {
29 val authority = url.httpOrigin().authority(true)
30 val target = if (version == HttpVersion.Http2) HttpRequestTarget.Connect(authority.toByteArray())
31 else HttpRequestTarget.Http1(authority.toByteArray())
32 return HttpRequestHead(version, "CONNECT".toByteArray(), target,
33 proxyFields(fields, if (version == HttpVersion.Http2) None else Some(authority)))
36/**
37 * Returns whether CONNECT received a 2xx status.
38 */
39public fun httpConnectAccepted(response: HttpResponseHead): Boolean = response.status >= 200U && response.status < 300U
41private fun proxyFields(fields: List<HttpField>, authority: String?): Array<HttpField> {
42 val result = ArrayList<HttpField>()
43 for (field in fields) {
44 if (!httpToken(field.name)) throw IllegalArgumentException(Some("invalid proxy request field name"))
45 if (httpAsciiEqual(field.name, "host".toByteArray()))
46 throw IllegalArgumentException(Some("proxy request Host is derived from the target URL"))
47 requireHttpValue(field.value)
48 result.add(field)
49 }
50 when (authority) {
51 case Some(val value) -> result.add(HttpField("Host".toByteArray(), value.toByteArray()))
52 case None -> {}
53 }
54 return result.toArray()