std

source of std::http

1// HTTP/1.1 requests (alloy-ui's decisions/F12.md, "Network in std"): a2// client in Alloy over std::net and, for `https://`, std::tls. `send`3// waits for the whole response on whichever task calls it, and another4// task may follow or cancel an exchange through its `Control`.5//6// It writes the request with `Host`, `Content-Length`, `Accept-Encoding:7// gzip` and `User-Agent: alloy` unless the request has its own; reads the8// status line, headers and a body sized by its length, chunked or ending9// with the connection; inflates a gzip body (std::deflate); and follows10// redirections as browsers do: 303, and 301 or 302 after a POST, become11// a GET without a body, and `Authorization`, `Proxy-Authorization` and12// `Cookie` are dropped when the origin changes. A `Client` keeps the13// connections servers leave open, at most 6 an origin, each for a minute14// after its last response, for the requests sent through it after; `send`15// makes a client for one request, whose redirections still reuse its16// connection on its origin. A status of 404 or 500 is a response, not an17// error; past `redirects` redirections the last is the response.18//19// The timeout covers the whole exchange, connecting included, through20// the socket's own timeouts against its deadline. Natively only: under21// WASI and in the interpreter `send` gives Unsupported, and on the web's22// page, which may not wait, it is a fault.23//24// ```alloy25// import std::result;26// import std::string;27//28// var request = Request::get(&"ftp://tickets.example/shows.json");29// request.add_header(&"Accept", &"application/json");30// request.timeout = Duration::from_seconds(10.0);31// match (send(&request)) {32//     ::Ok |&response| {33//         expect(response.ok());34//     }35//     ::Err |&error| {36//         expect_equal(&f"{error}", &String::from(&"not an http:// or https:// URL"));37//     }38// }39// ```4041import std::option;42import std::result;43import std::string;44import std::vector;45import std::text;46import std::format;47import std::time;48import std::sync;49import std::process;50import std::dispose;51import std::ffi;52import std::json;53import std::net;54import std::tls;55import std::url;56import std::deflate;5758exp type Method = enum {59    Get,60    Head,61    Post,62    Put,63    Patch,64    Delete65};6667exp fn name(self method: &Method) -> &[u8] => match (method) {68    ::Get &"GET";69    ::Head &"HEAD";70    ::Post &"POST";71    ::Put &"PUT";72    ::Patch &"PATCH";73    ::Delete &"DELETE";74};7576exp type Header = struct {77    exp name: String,78    exp value: String79};8081exp type Request = struct {82    exp method: Method = Method::Get,83    exp url: String,84    exp headers: Vector<Header> = Vector<Header>::empty(),85    exp body: Vector<u8> = Vector<u8>::empty(),86    exp timeout: Duration = Duration::from_seconds(30.0), // the whole exchange, connecting included87    exp limit: u64 = 64 << 20, // the most bytes of body taken; more is TooLarge88    exp redirects: u8 = 5 // the most followed89};9091exp fn Request::get(url: &[u8]) -> Request {92    return Request { .url = String::from(&url) };93}9495// A POST of the JSON, with `Content-Type: application/json`.96exp fn Request::post_json(url: &[u8], body: &Json) -> Request {97    var request = Request {98        .method = Method::Post,99        .url = String::from(&url),100        .body = Vector<u8>::from(&body.to_json().view())101    };102    request.add_header(&"Content-Type", &"application/json");103    return move request;104}105106// The name and value are written as they are: `send` gives107// `HttpError::Header` when the name is empty or holds ':', or either holds108// a CR, LF or NUL.109exp fn add_header(self request: &var Request, name: &[u8], value: &[u8]) {110    request.headers.push(Header { .name = String::from(&name), .value = String::from(&value) });111}112113exp type Response = struct {114    exp status: u16,115    exp headers: Vector<Header>,116    exp body: Vector<u8>, // decoded: chunks joined, gzip inflated117    exp url: String // where it came from, after redirections118};119120// The first header of the name, compared without case.121exp fn header(self response: &Response, name: &[u8]) -> Option<&[u8]> {122    return header_in(&response.headers, &name);123}124125// A status from 200 to 299.126exp fn ok(self response: &Response) -> bool => response.status >= 200 && response.status < 300;127128// The body as JSON, None when it is not.129exp fn json(self response: &Response) -> Option<Json> => parse_json(&response.body.view());130131exp type HttpError : Format = enum {132    Address, // not an http:// or https:// URL133    Header, // a header's name or value cannot be written (`add_header`)134    Unsupported, // no network here: WASI, the interpreter135    Resolve, // the host has no address136    Connect, // no address took the connection137    Certificate: String, // the server's certificate is not trusted for the host: why138    Tls, // the handshake failed otherwise139    Timeout,140    Cancelled,141    Closed, // the connection ended before the response did142    Malformed, // what came back is not HTTP/1.1143    TooLarge144};145146exp fn format(self error: &HttpError, out: &var String) {147    out.append(match (error) {148        ::Address &"not an http:// or https:// URL";149        ::Header &"a header of the request is not valid HTTP/1.1";150        ::Unsupported &"no network here";151        ::Resolve &"the host has no address";152        ::Connect &"no address took the connection";153        ::Certificate &"the server's certificate is not trusted: ";154        ::Tls &"the TLS handshake failed";155        ::Timeout &"the time ran out";156        ::Cancelled &"cancelled";157        ::Closed &"the connection ended before the response did";158        ::Malformed &"the response is not HTTP/1.1";159        ::TooLarge &"the response is larger than its limit";160    });161    if (error is ::Certificate |&why|) {162        out.append(&why.view());163    }164}165166// How far an exchange has gone.167exp type Progress = struct {168    exp sent: u64,169    exp to_send: u64,170    exp received: u64,171    exp total: Option<u64> // the response's Content-Length, when it gave one172};173174// What another task sees of an exchange, and how it stops one. A control175// follows one exchange at a time, its progress the latest one's; once176// cancelled it stays cancelled, as a browser's AbortSignal does, so a177// cancel that comes before or between exchanges is not lost and every178// later `send_with` through it gives Cancelled at once: the next179// exchange takes a new control.180exp type Control : Shared = struct {181    socket: Mutex<i64>, // the connection under way, -1 for none182    cancelled: Atomic<bool>,183    sent: Atomic<u64>,184    to_send: Atomic<u64>,185    received: Atomic<u64>,186    total: Atomic<u64> // NO_TOTAL for none187};188189const NO_TOTAL: u64 = 0xFFFFFFFFFFFFFFFF;190191exp fn Control::create() -> Control {192    return Control {193        .socket = Mutex<i64>::from(-1),194        .cancelled = Atomic<bool>::from(false),195        .sent = Atomic<u64>::from(0),196        .to_send = Atomic<u64>::from(0),197        .received = Atomic<u64>::from(0),198        .total = Atomic<u64>::from(NO_TOTAL)199    };200}201202// Stops the exchange: its connection is shut down, and `send_with`203// returns Cancelled, now and through this control from now on.204exp fn cancel(self control: &Control) {205    control.cancelled.store(true);206    var guard = control.socket.lock();207    const socket = guard.value();208    if (socket >= 0) {209        shutdown_handle(socket);210    }211    guard.dispose();212}213214exp fn progress(self control: &Control) -> Progress {215    const total = control.total.load();216    return Progress {217        .sent = control.sent.load(),218        .to_send = control.to_send.load(),219        .received = control.received.load(),220        .total = if (total == NO_TOTAL) ::None else ::Some(total)221    };222}223224// The connection another task may shut down, -1 for none.225fn attach(self control: &Control, socket: i64) {226    var guard = control.socket.lock();227    guard.value() = socket;228    if (socket >= 0 && control.cancelled.load()) {229        shutdown_handle(socket);230    }231    guard.dispose();232}233234// Sends the request and waits for the whole response, on connections of235// its own.236exp fn send(request: &Request) -> Result<Response, HttpError> {237    const control = Control::create();238    return send_with(&request, &control);239}240241// Sends the request as `send` does, another task following it or242// cancelling it through the control.243exp fn send_with(request: &Request, control: &Control) -> Result<Response, HttpError> {244    var client = Client {};245    var result = client.send_with(&request, &control);246    client.dispose();247    return move result;248}249250/* --- Kept connections --- */251252// Connections kept open between requests, by origin: a request takes one253// to its origin the client keeps, else connects, and gives it back once254// its response ended where it said and the server keeps it open, the255// client keeping at most 6 an origin, each closed once idle for256// `idle_for`. Tasks share a client: each request takes its own257// connection. Disposing the client closes those it keeps.258//259// ```alloy260// import std::result;261// import std::string;262//263// var client = Client {};264// const result = client.send(&Request::get(&"ftp://tickets.example/shows.json"));265// expect(result.is_err());266// client.dispose();267// ```268exp type Client : Shared + Disposable = struct {269    exp idle_for: Duration = Duration::from_seconds(60.0),270    idle: Mutex<Vector<Link>> = Mutex<Vector<Link>>::from(Vector<Link>::empty())271};272273// The most connections a client keeps to one origin.274const KEPT_PER_ORIGIN: u64 = 6;275276exp fn dispose(self client: &var Client) {277    client.idle.dispose();278}279280// Sends the request as `http::send` does, on a connection the client281// keeps when it has one to the origin.282exp fn send(self client: &Client, request: &Request) -> Result<Response, HttpError> {283    const control = Control::create();284    return client.send_with(&request, &control);285}286287// Sends the request as `send_with` does, on a connection the client keeps288// when it has one to the origin.289exp fn send_with(290    self client: &Client,291    request: &Request,292    control: &Control293) -> Result<Response, HttpError> {294    if (target() == "wasi-wasm32") {295        return ::Err(::Unsupported);296    } else if (target() == "web-wasm32") {297        panic "std::http::send cannot wait on the web's page: ui.send and ui.load send requests there";298    } else {299        const transfer = Transfer {300            .client = &client,301            .control = &control,302            .started = Instant::now(),303            .timeout = request.timeout,304            .limit = request.limit305        };306        return transfer.run(&request);307    }308}309310/* --- On the web --- */311312// An exchange `start` handed to the browser, which another part of the313// program follows or cancels by it.314exp type Exchange = struct {315    id: u32316};317318// web-wasm32 only: hands the request to the browser's `fetch` and returns319// at once; `done` runs from the browser's loop once the exchange ends,320// cancelled too. The browser follows redirections and inflates the body321// itself, and a URL relative to the page is taken. Elsewhere a program322// waits with `send` on a task of its own, and this panics.323exp fn start(request: Request, done: |=| (Result<Response, HttpError>)) -> Exchange {324    if (target() == "web-wasm32") {325        return page_start(move request, move done);326    } else {327        panic "std::http::start hands requests to a browser: elsewhere send waits on a task";328    }329}330331fn page_start(request: Request, done: |=| (Result<Response, HttpError>)) -> Exchange {332    var refused = PageOutcome::Done;333    if (Url::parse(&request.url.view()) is ::Some |&url| && !web_scheme(&url.scheme.view())) {334        refused = PageOutcome::Address;335    }336    var headers = String::empty();337    for (request.headers.view()) |&h| {338        if (!header_name(&h.name.view()) || !header_text(&h.value.view())) {339            refused = PageOutcome::Header;340        }341        headers.append(&f"{h.name}: {h.value}\r\n".view());342    }343    const method = &request.method.name();344    var kept: *var Waiting = new Waiting { .done = move done };345    const waiting = c_pointer::keep(move kept);346    const id = al_http_start(347        c_pointer::of(&method),348        method.length() to u32,349        c_pointer::of(&request.url.view()),350        request.url.length() to u32,351        c_pointer::of(&headers.view()),352        headers.length() to u32,353        c_pointer::of(&request.body.view()),354        request.body.length() to u32,355        request.timeout.milliseconds(),356        request.limit to f64,357        refused to u32,358        on_page_done,359        waiting360    );361    return Exchange { .id = id };362}363364// Stops the exchange: `done` gets Cancelled, unless it ended first.365exp fn cancel(self exchange: &Exchange) {366    if (target() == "web-wasm32") {367        al_http_cancel(exchange.id);368    }369}370371// How far the exchange has gone; nothing once it ended. Bytes sent jump372// from none to all, as `fetch` tells no more of an upload.373exp fn progress(self exchange: &Exchange) -> Progress {374    var counts: [f64 : 4] = [0.0 : 4];375    if (target() == "web-wasm32") {376        al_http_progress(exchange.id, c_pointer::of(&counts[..]));377    }378    return Progress {379        .sent = counts[0] to u64,380        .to_send = counts[1] to u64,381        .received = counts[2] to u64,382        .total = if (counts[3] < 0.0) ::None else ::Some(counts[3] to u64)383    };384}385386type PageDone = extern (c_pointer, u32, u32, u32);387388// http.web.js's functions.389extern al_http_start(390    method: c_pointer,391    method_length: u32,392    url: c_pointer,393    url_length: u32,394    headers: c_pointer,395    headers_length: u32,396    body: c_pointer,397    body_length: u32,398    milliseconds: f64,399    limit: f64,400    refused: u32,401    done: PageDone,402    data: c_pointer403) -> u32;404extern al_http_take(id: u32, at: c_pointer, capacity: u32);405extern al_http_cancel(id: u32);406extern al_http_progress(id: u32, counts: c_pointer);407408// What `start` keeps for the page to call back.409type Waiting = struct {410    done: |=| (Result<Response, HttpError>)411};412413// How an exchange on the page ended, as http.web.js numbers it.414type PageOutcome = enum : u32 {415    Done = 0,416    Address = 1,417    Header = 2,418    Unsupported = 3,419    Connect = 4,420    Timeout = 5,421    Cancelled = 6,422    TooLarge = 7423};424425fn on_page_done(data: c_pointer, id: u32, outcome: u32, length: u32) {426    var waiting = data.take<Waiting>();427    const ended = if (PageOutcome::from(outcome) is ::Some |o|) o else PageOutcome::Connect;428    var result: Result<Response, HttpError> = ::Err(::Malformed);429    match (ended) {430        ::Done {431            var bytes: *var [u8] = new [0 to u8 : length to u64];432            al_http_take(id, c_pointer::of(&bytes[..]), length);433            if (unpack_response(&bytes[..]) is ::Some |move r|) {434                result = ::Ok(move r);435            }436        }437        ::Address {438            result = ::Err(::Address);439        }440        ::Header {441            result = ::Err(::Header);442        }443        ::Unsupported {444            result = ::Err(::Unsupported);445        }446        ::Connect {447            result = ::Err(::Connect);448        }449        ::Timeout {450            result = ::Err(::Timeout);451        }452        ::Cancelled {453            result = ::Err(::Cancelled);454        }455        ::TooLarge {456            result = ::Err(::TooLarge);457        }458    }459    waiting.done(move result);460}461462// A response as http.web.js packs it: the status, the URL, the headers'463// count and each name and value, then the body, each text and the body464// after its length, as little-endian u32s.465fn unpack_response(bytes: &[u8]) -> Option<Response> {466    var r = Unpacking { .bytes = &bytes, .at = 0, .short = false };467    var response = Response {468        .status = r.number() to u16,469        .headers = Vector<Header>::empty(),470        .body = Vector<u8>::empty(),471        .url = String::from(&r.chunk())472    };473    const count = r.number();474    for ([..count to u64]) {475        var name = String::from(&r.chunk());476        response.headers.push(Header { .name = move name, .value = String::from(&r.chunk()) });477        if (r.short) {478            return ::None;479        }480    }481    response.body = Vector<u8>::from(&r.chunk());482    return if (r.short) ::None else ::Some(move response);483}484485type Unpacking = struct {486    bytes: &[u8],487    at: u64,488    short: bool // whether the bytes ended early489};490491fn number(self r: &var Unpacking) -> u32 {492    if (r.at + 4 > r.bytes.length()) {493        r.at = r.bytes.length();494        r.short = true;495        return 0;496    }497    var n: u32 = 0;498    for ([..4 to u64]) |k| {499        n |= r.bytes[r.at + k] to u32 << (8 * k to u32);500    }501    r.at += 4;502    return n;503}504505fn chunk(self r: &var Unpacking) -> &[u8] {506    const length = r.number() to u64;507    if (r.at + length > r.bytes.length()) {508        r.short = true;509        return &r.bytes[r.at..];510    }511    r.at += length;512    return &r.bytes[r.at - length..r.at];513}514515/* --- The exchange --- */516517type Transfer = struct {518    client: &Client,519    control: &Control,520    started: Instant,521    timeout: Duration,522    limit: u64523};524525// What is left of the exchange's time.526fn left(self x: &Transfer) -> Duration {527    const spent = x.started.elapsed().nanoseconds;528    return Duration::from_nanoseconds(529        if (spent < x.timeout.nanoseconds) x.timeout.nanoseconds - spent else 0530    );531}532533// Why reading or writing stopped: cancelled, out of time, or the534// connection ended.535fn failure(self x: &Transfer) -> HttpError {536    if (x.control.cancelled.load()) {537        return ::Cancelled;538    }539    // the socket's timeout may end a little before the deadline540    if (x.left().nanoseconds < 20000000) {541        return ::Timeout;542    }543    return ::Closed;544}545546fn run(self x: &Transfer, request: &Request) -> Result<Response, HttpError> {547    var url = if (Url::parse(&request.url.view()) is ::Some |move u|) move u else {548        return ::Err(::Address);549    };550    if (!web_scheme(&url.scheme.view())) {551        return ::Err(::Address);552    }553    for (request.headers.view()) |&h| {554        if (!header_name(&h.name.view()) || !header_text(&h.value.view())) {555            return ::Err(::Header);556        }557    }558    var method = request.method;559    var headers = copy request.headers;560    var body = copy request.body;561    var link = match (x.connect(&url)) {562        ::Ok |move l| move l;563        ::Err |&e| {564            return ::Err(copy e);565        }566    };567    var redirections: u8 = 0;568    var retried = false;569    while (true) {570        if (!link.reusable || link.origin != url.origin()) {571            x.control.attach(-1);572            x.client.keep(move link);573            // a retry on a connection of its own, not another kept one574            link = match (if (retried) x.open(&url) else x.connect(&url)) {575                ::Ok |move l| move l;576                ::Err |&e| {577                    return ::Err(copy e);578                }579            };580        }581        var response = match (x.hop(&var link, &url, method, &headers, &body.view())) {582            ::Ok |move r| move r;583            ::Err |&e| {584                // a kept connection the server closed before answering:585                // once more on a new one586                if (e is ::Closed && !retried && link.requests > 1 && link.answered == 0) {587                    retried = true;588                    link.reusable = false;589                    continue;590                }591                x.control.attach(-1);592                link.dispose();593                return ::Err(copy e);594            }595        };596        retried = false;597        if (redirections < request.redirects && redirected(response.status)) {598            if (599                response.header(&"Location") is ::Some |&location|600                && url.resolve(&location) is ::Some |move next|601                && web_scheme(&next.scheme.view())602            ) {603                if (604                    (response.status == 303 && !(method is ::Head))605                    || ((response.status == 301 || response.status == 302) && method is ::Post)606                ) {607                    method = Method::Get;608                    body.clear();609                    remove_header(&var headers, &"Content-Type");610                }611                if (next.origin() != url.origin()) {612                    remove_header(&var headers, &"Authorization");613                    remove_header(&var headers, &"Proxy-Authorization");614                    remove_header(&var headers, &"Cookie");615                }616                url = move next;617                redirections += 1;618                continue;619            }620        }621        x.control.attach(-1);622        x.client.keep(move link);623        // a HEAD's, a 204's or a 304's empty body says how a body would come624        if (response.body.length() > 0 && gzipped(&response)) {625            match (gunzip(&response.body.view(), x.limit)) {626                ::Ok |move inflated| {627                    response.body = move inflated;628                }629                ::Err |e| {630                    return ::Err(631                        if (e is ::TooLarge) HttpError::TooLarge else HttpError::Malformed632                    );633                }634            }635        }636        response.url = f"{url}";637        return ::Ok(move response);638    }639}640641fn gzipped(response: &Response) -> bool {642    if (response.header(&"Content-Encoding") is ::Some |&coding|) {643        return same_name(&coding, &"gzip") || same_name(&coding, &"x-gzip");644    }645    return false;646}647648// Whether the response says its connection closes after it.649fn closing(response: &Response) -> bool {650    if (response.header(&"Connection") is ::Some |&value|) {651        return same_name(&value, &"close");652    }653    return false;654}655656// A header's name may not be empty nor hold ':', which would end it.657fn header_name(name: &[u8]) -> bool => name.length() > 0658    && name.find_byte(':', 0) is ::None659    && header_text(&name);660661// Header text may not hold CR or LF, which would end the header, nor NUL.662fn header_text(text: &[u8]) -> bool {663    for (text) |c| {664        if (c == '\r' || c == '\n' || c == 0) {665            return false;666        }667    }668    return true;669}670671fn web_scheme(scheme: &[u8]) -> bool => scheme == "http" || scheme == "https";672673fn redirected(status: u16) -> bool => status == 301674    || status == 302675    || status == 303676    || status == 307677    || status == 308;678679// A connection to the URL's origin the client keeps, else a new one.680fn connect(self x: &Transfer, url: &Url) -> Result<Link, HttpError> {681    if (x.control.cancelled.load()) {682        return ::Err(::Cancelled);683    }684    if (x.client.take(&url.origin().view()) is ::Some |move link|) {685        x.control.attach(link.stream.handle());686        return ::Ok(move link);687    }688    return x.open(&url);689}690691// A connection to the origin the client keeps, those idle too long closed692// on the way.693fn take(self client: &Client, origin: &[u8]) -> Option<Link> {694    var guard = client.idle.lock();695    const idle = &var guard.value();696    var k: u64 = 0;697    while (k < idle.length()) {698        if (idle.get(k).since.elapsed().nanoseconds >= client.idle_for.nanoseconds) {699            var old = idle.remove(k);700            old.dispose();701        } else {702            k += 1;703        }704    }705    var at: Option<u64> = ::None;706    for (idle.view(), [..idle.length()]) |&l, j| {707        if (l.origin.view() == origin) {708            at = ::Some(j);709            break;710        }711    }712    var found: Option<Link> = if (at is ::Some |j|) ::Some(idle.remove(j)) else ::None;713    guard.dispose();714    return move found;715}716717// Keeps the connection for the next request to its origin when the718// server keeps it open and the client has room, else closes it.719fn keep(self client: &Client, link: Link) {720    var kept = move link;721    if (!kept.reusable) {722        kept.dispose();723        return;724    }725    var guard = client.idle.lock();726    const idle = &var guard.value();727    var count: u64 = 0;728    for (idle.view()) |&l| {729        if (l.origin == kept.origin) {730            count += 1;731        }732    }733    if (count < KEPT_PER_ORIGIN) {734        kept.since = Instant::now();735        idle.push(move kept);736    } else {737        kept.dispose();738    }739    guard.dispose();740}741742// A connection to the URL's origin, through TLS for `https://`.743fn open(self x: &Transfer, url: &Url) -> Result<Link, HttpError> {744    if (x.control.cancelled.load()) {745        return ::Err(::Cancelled);746    }747    const connected = Connection::connect(&url.host.view(), url.port, x.left());748    var connection = match (connected) {749        ::Ok |move c| move c;750        ::Err |e| {751            return ::Err(match (e) {752                ::Resolve HttpError::Resolve;753                ::Connect HttpError::Connect;754                ::Timeout HttpError::Timeout;755                ::Unsupported HttpError::Unsupported;756            });757        }758    };759    x.control.attach(connection.handle());760    if (url.scheme.view() != "https") {761        return ::Ok(Link::over(Stream::Plain(move connection), &url));762    }763    connection.set_timeout(x.left());764    var tls = Tls::client(move connection, &url.host.view());765    if (tls.handshake() is ::Some |&problem|) {766        var error = if (767            problem is ::Certificate |&why|768        ) HttpError::Certificate(copy why) else if (769            x.failure() is ::Closed770        ) HttpError::Tls else x.failure();771        x.control.attach(-1);772        tls.dispose();773        return ::Err(move error);774    }775    return ::Ok(Link::over(Stream::Secure(move tls), &url));776}777778// One request on the link and its response, the body still encoded.779fn hop(780    self x: &Transfer,781    link: &var Link,782    url: &Url,783    method: Method,784    headers: &Vector<Header>,785    body: &[u8]786) -> Result<Response, HttpError> {787    link.requests += 1;788    link.answered = 0;789    link.reusable = false;790    var out = String::with_capacity(256 + body.length());791    out.append(&method.name());792    out.push(' ');793    out.append(&url.target().view());794    out.append(&" HTTP/1.1\r\nHost: ");795    out.append(&url.authority().view());796    out.append(&"\r\n");797    if (header_in(&headers, &"User-Agent") is ::None) {798        out.append(&"User-Agent: alloy\r\n");799    }800    if (header_in(&headers, &"Accept-Encoding") is ::None) {801        out.append(&"Accept-Encoding: gzip\r\n");802    }803    if (body.length() > 0 || method is ::Post || method is ::Put || method is ::Patch) {804        out.append(&f"Content-Length: {body.length()}\r\n".view());805    }806    for (headers.view()) |&h| {807        const name = &h.name.view();808        if (809            !same_name(&name, &"Host")810            && !same_name(&name, &"Content-Length")811            && !same_name(&name, &"Transfer-Encoding")812        ) {813            out.append(&name);814            out.append(&": ");815            out.append(&h.value.view());816            out.append(&"\r\n");817        }818    }819    out.append(&"\r\n");820    out.append(&body);821    const bytes = &out.view();822    x.control.to_send.store(bytes.length());823    x.control.sent.store(0);824    x.control.received.store(0);825    x.control.total.store(NO_TOTAL);826    var at: u64 = 0;827    while (at < bytes.length()) {828        const piece = if (bytes.length() - at < 65536) bytes.length() - at else 65536;829        const left = x.left();830        if (left.nanoseconds == 0) {831            return ::Err(::Timeout);832        }833        link.stream.set_timeout(left);834        if (!link.stream.write(&bytes[at..at + piece])) {835            return ::Err(x.failure());836        }837        at += piece;838        x.control.sent.store(at);839    }840    // informational answers (100 Continue) come before the response841    var head = match (link.head(&x)) {842        ::Ok |move h| move h;843        ::Err |&e| {844            return ::Err(copy e);845        }846    };847    while (head.status >= 100 && head.status < 200 && head.status != 101) {848        head = match (link.head(&x)) {849            ::Ok |move h| move h;850            ::Err |&e| {851                return ::Err(copy e);852            }853        };854    }855    var response = Response {856        .status = head.status,857        .headers = move head.headers,858        .body = Vector<u8>::empty(),859        .url = String::empty()860    };861    const keep = head.minor >= 1 && !closing(&response);862    if (863        method is ::Head864        || response.status == 204865        || response.status == 304866        || (response.status >= 100 && response.status < 200)867    ) {868        link.reusable = keep;869        return ::Ok(move response);870    }871    const coded = response.header(&"Transfer-Encoding") is ::Some;872    if (response.header(&"Transfer-Encoding") is ::Some |&coding| && ends_with_chunked(&coding)) {873        if (link.chunks(&x, &var response.body) is ::Some |&e|) {874            return ::Err(copy e);875        }876    } else if (!coded && response.header(&"Content-Length") is ::Some |&text|) {877        const length = if (878            all_digits(&text)879            && text.length() < 19880            && text.parse_integer() is ::Some |n|881        ) n to u64 else {882            return ::Err(::Malformed);883        };884        if (length > x.limit) {885            return ::Err(::TooLarge);886        }887        x.control.total.store(length);888        // what the server claims, up to 1 MB, the rest as it comes889        response.body = Vector<u8>::with_capacity(if (length < 1 << 20) length else 1 << 20);890        if (link.take(&x, length, &var response.body) is ::Some |&e|) {891            return ::Err(copy e);892        }893    } else {894        // to the connection's end895        if (link.rest(&x, &var response.body) is ::Some |&e|) {896            return ::Err(copy e);897        }898        return ::Ok(move response);899    }900    link.reusable = keep;901    return ::Ok(move response);902}903904// Whether a Transfer-Encoding's last coding is chunked.905fn ends_with_chunked(coding: &[u8]) -> bool {906    var start = coding.length();907    while (start > 0 && coding[start - 1] != ',') {908        start -= 1;909    }910    return same_name(&coding[start..].trim(), &"chunked");911}912913/* --- The connection under an exchange --- */914915type Stream : Disposable = enum {916    Plain: Connection,917    Secure: Tls918};919920fn dispose(self stream: &var Stream) {921    match (stream) {922        ::Plain |&var c| {923            c.dispose();924        }925        ::Secure |&var t| {926            t.dispose();927        }928    }929}930931// How many bytes came, 0 at the connection's end, -1 after a failure.932fn read(self stream: &var Stream, buffer: &var [u8]) -> i64 => match (stream) {933    ::Plain |&var c| c.read_or_fail(&var buffer);934    ::Secure |&var t| t.read_or_fail(&var buffer);935};936937fn write(self stream: &var Stream, bytes: &[u8]) -> bool => match (stream) {938    ::Plain |&var c| c.write(&bytes);939    ::Secure |&var t| t.write(&bytes);940};941942// The socket under the stream, which a control shuts down.943fn handle(self stream: &Stream) -> i64 => match (stream) {944    ::Plain |&c| c.handle();945    ::Secure |&t| t.connection().handle();946};947948fn set_timeout(self stream: &var Stream, limit: Duration) {949    match (stream) {950        ::Plain |&var c| {951            c.set_timeout(limit);952        }953        ::Secure |&var t| {954            t.set_timeout(limit);955        }956    }957}958959// A connection and what was read from it but not yet taken.960type Link : Disposable = struct {961    stream: Stream,962    origin: String, // the URLs it serves: scheme://host[:port]963    buffer: Vector<u8>,964    start: u64, // the first byte not taken965    end: u64, // past the last byte read966    reusable: bool, // the last response ended where it said, and the server keeps it open967    requests: u32, // how many requests it carried968    answered: u64, // how many bytes of the current response came969    ended: bool, // the last read found the connection's end, not a failure970    since: Instant // when a client last kept it971};972973fn Link::over(stream: Stream, url: &Url) -> Link {974    return Link {975        .stream = move stream,976        .origin = url.origin(),977        .buffer = Vector<u8>::filled(0, 16384),978        .start = 0,979        .end = 0,980        .reusable = true,981        .requests = 0,982        .answered = 0,983        .ended = false,984        .since = Instant::now()985    };986}987988fn dispose(self link: &var Link) {989    link.stream.dispose();990}991992// More bytes into the buffer, waiting at most what is left of the993// exchange's time; false when none came.994fn more(self link: &var Link, x: &Transfer) -> bool {995    if (link.start > 0) {996        const kept = link.end - link.start;997        const bytes = &var link.buffer.items();998        for ([..kept]) |k| {999            bytes[k] = bytes[link.start + k];1000        }1001        link.start = 0;1002        link.end = kept;1003    }1004    if (link.end == link.buffer.length()) {1005        link.buffer.append(&Vector<u8>::filled(0, link.buffer.length()).view());1006    }1007    const left = x.left();1008    if (left.nanoseconds == 0) {1009        return false;1010    }1011    link.stream.set_timeout(left);1012    const count = link.stream.read(&var link.buffer.items()[link.end..]);1013    if (count <= 0) {1014        link.ended = count == 0;1015        return false;1016    }1017    link.end += count to u64;1018    link.answered += count to u64;1019    return true;1020}10211022// What a response starts with.1023type Head = struct {1024    minor: u8, // HTTP/1.minor1025    status: u16,1026    headers: Vector<Header>1027};10281029const HEAD_LIMIT: u64 = 65536; // the most bytes of a status line and headers10301031fn head(self link: &var Link, x: &Transfer) -> Result<Head, HttpError> {1032    var end: u64 = 0;1033    while (true) {1034        if (blank_line(&link.buffer.view()[link.start..link.end]) is ::Some |at|) {1035            end = link.start + at;1036            break;1037        }1038        if (link.end - link.start > HEAD_LIMIT) {1039            return ::Err(::Malformed);1040        }1041        if (!link.more(&x)) {1042            return ::Err(x.failure());1043        }1044    }1045    const text = &link.buffer.view()[link.start..end];1046    var head = Head { .minor = 0, .status = 0, .headers = Vector<Header>::empty() };1047    var first = true;1048    for (lines(&text).view()) |&line| {1049        if (first) {1050            first = false;1051            // HTTP/1.x SSS reason1052            if (1053                line.length() < 121054                || !line.starts_with(&"HTTP/1.")1055                || !(line[7] == '0' || line[7] == '1')1056                || line[8] != ' '1057                || !all_digits(&line[9..12])1058                || (line.length() > 12 && line[12] != ' ')1059            ) {1060                return ::Err(::Malformed);1061            }1062            head.minor = line[7] - '0';1063            head.status = (1064                (line[9] - '0') to u161065            ) * 100 + ((line[10] - '0') to u16) * 10 + (line[11] - '0') to u16;1066            continue;1067        }1068        const colon = if (line.find_byte(':', 0) is ::Some |c| && c > 0) c else {1069            return ::Err(::Malformed);1070        };1071        if (line[0] == ' ' || line[0] == '\t') {1072            return ::Err(::Malformed);1073        }1074        head.headers.push(Header {1075            .name = String::from(&line[..colon]),1076            .value = String::from(&line[colon + 1..].trim())1077        });1078    }1079    if (first) {1080        return ::Err(::Malformed);1081    }1082    link.start = end;1083    return ::Ok(move head);1084}10851086// Where the text's first empty line ends (CRLF CRLF, or LF LF), None1087// before one.1088fn blank_line(text: &[u8]) -> Option<u64> {1089    var at: u64 = 0;1090    while (text.find_byte('\n', at) is ::Some |n|) {1091        if (n + 1 < text.length() && text[n + 1] == '\n') {1092            return ::Some(n + 2);1093        }1094        if (n + 2 < text.length() && text[n + 1] == '\r' && text[n + 2] == '\n') {1095            return ::Some(n + 3);1096        }1097        at = n + 1;1098    }1099    return ::None;1100}11011102// The text's lines, without their CR LF or LF, the empty ones left out.1103fn lines(text: &[u8]) -> Vector<&[u8]> {1104    var out = Vector<&[u8]>::empty();1105    var start: u64 = 0;1106    while (start < text.length()) {1107        var end = if (text.find_byte('\n', start) is ::Some |n|) n else text.length();1108        const next = end + 1;1109        if (end > start && text[end - 1] == '\r') {1110            end -= 1;1111        }1112        if (end > start) {1113            out.push(&text[start..end]);1114        }1115        start = next;1116    }1117    return move out;1118}11191120// The next `count` bytes into the body; the error that stopped it.1121fn take(1122    self link: &var Link,1123    x: &Transfer,1124    count: u64,1125    body: &var Vector<u8>1126) -> Option<HttpError> {1127    var wanted = count;1128    while (wanted > 0) {1129        if (link.start == link.end && !link.more(&x)) {1130            return ::Some(x.failure());1131        }1132        const ready = link.end - link.start;1133        const piece = if (ready < wanted) ready else wanted;1134        body.append(&link.buffer.view()[link.start..link.start + piece]);1135        link.start += piece;1136        wanted -= piece;1137        x.control.received.add(piece);1138    }1139    return ::None;1140}11411142// The next line, without its CR LF; the error that stopped it.1143fn line(self link: &var Link, x: &Transfer) -> Result<String, HttpError> {1144    while (true) {1145        if (link.buffer.view()[link.start..link.end].find_byte('\n', 0) is ::Some |n|) {1146            var end = link.start + n;1147            const next = end + 1;1148            if (end > link.start && link.buffer.get(end - 1) == '\r') {1149                end -= 1;1150            }1151            var text = String::from(&link.buffer.view()[link.start..end]);1152            link.start = next;1153            return ::Ok(move text);1154        }1155        if (link.end - link.start > 4096) {1156            return ::Err(::Malformed);1157        }1158        if (!link.more(&x)) {1159            return ::Err(x.failure());1160        }1161    }1162}11631164// A chunked body (RFC 9112, 7.1), its trailers read and left out.1165fn chunks(self link: &var Link, x: &Transfer, body: &var Vector<u8>) -> Option<HttpError> {1166    while (true) {1167        const size_line = match (link.line(&x)) {1168            ::Ok |move l| move l;1169            ::Err |&e| {1170                return ::Some(copy e);1171            }1172        };1173        const digits = if (1174            size_line.view().find_byte(';', 0) is ::Some |s|1175        ) &size_line.view()[..s].trim() else &size_line.view().trim();1176        const size = if (hex_number(&digits) is ::Some |n|) n else {1177            return ::Some(::Malformed);1178        };1179        if (size == 0) {1180            while (true) {1181                const trailer = match (link.line(&x)) {1182                    ::Ok |move l| move l;1183                    ::Err |&e| {1184                        return ::Some(copy e);1185                    }1186                };1187                if (trailer.length() == 0) {1188                    return ::None;1189                }1190            }1191        }1192        if (body.length() + size > x.limit) {1193            return ::Some(::TooLarge);1194        }1195        if (link.take(&x, size, &var body) is ::Some |&e|) {1196            return ::Some(copy e);1197        }1198        const ending = match (link.line(&x)) {1199            ::Ok |move l| move l;1200            ::Err |&e| {1201                return ::Some(copy e);1202            }1203        };1204        if (ending.length() != 0) {1205            return ::Some(::Malformed);1206        }1207    }1208}12091210// A body ending with the connection.1211fn rest(self link: &var Link, x: &Transfer, body: &var Vector<u8>) -> Option<HttpError> {1212    while (true) {1213        const ready = link.end - link.start;1214        if (body.length() + ready > x.limit) {1215            return ::Some(::TooLarge);1216        }1217        body.append(&link.buffer.view()[link.start..link.end]);1218        link.start = link.end;1219        x.control.received.add(ready);1220        if (!link.more(&x)) {1221            // only the connection's end ends the body, not a reset or a timeout1222            return if (link.ended) ::None else ::Some(x.failure());1223        }1224    }1225}12261227fn hex_number(text: &[u8]) -> Option<u64> {1228    if (text.length() == 0 || text.length() > 15) {1229        return ::None;1230    }1231    var n: u64 = 0;1232    for (text) |c| {1233        const digit: u64 = if (1234            c >= '0'1235            && c <= '9'1236        ) (c - '0') to u64 else if (1237            c >= 'a'1238            && c <= 'f'1239        ) (c - 'a' + 10) to u64 else if (c >= 'A' && c <= 'F') (c - 'A' + 10) to u64 else {1240            return ::None;1241        };1242        n = n * 16 + digit;1243    }1244    return ::Some(n);1245}12461247/* --- Headers --- */12481249fn header_in(headers: &Vector<Header>, name: &[u8]) -> Option<&[u8]> {1250    for (headers.view()) |&h| {1251        if (same_name(&h.name.view(), &name)) {1252            return ::Some(&h.value.view());1253        }1254    }1255    return ::None;1256}12571258fn remove_header(headers: &var Vector<Header>, name: &[u8]) {1259    var at: u64 = 0;1260    while (at < headers.length()) {1261        if (same_name(&headers.get(at).name.view(), &name)) {1262            headers.remove(at);1263        } else {1264            at += 1;1265        }1266    }1267}12681269// Whether two names are the same, ASCII letters compared without case.1270fn same_name(a: &[u8], b: &[u8]) -> bool {1271    if (a.length() != b.length()) {1272        return false;1273    }1274    for (a, b) |x, y| {1275        if (lower(x) != lower(y)) {1276            return false;1277        }1278    }1279    return true;1280}12811282fn lower(c: u8) -> u8 => if (c >= 'A' && c <= 'Z') c + 32 else c;12831284fn all_digits(text: &[u8]) -> bool {1285    if (text.length() == 0) {1286        return false;1287    }1288    for (text) |c| {1289        if (c < '0' || c > '9') {1290            return false;1291        }1292    }1293    return true;1294}12951296/* --- F12b as built --- */12971298// **F12b as built** (2026-10-16; alloy-ui's decisions/F12.md, "Network in1299// std", questions 4A, 5A and 6A):1300// - std::net: `Connection::connect(host, port, timeout)` through1301//   `al_sys_tcp_connect` (getaddrinfo, then each address connected1302//   without blocking and polled for at most 3 seconds, the last for what1303//   is left of the timeout, TCP_NODELAY set; GetAddrInfoW and WSAPoll on1304//   Windows; WASI and the interpreter give Unsupported), `shutdown`, and1305//   timeouts as a `Duration` to the millisecond.1306// - std::tls: `alloyc/src/support/tls.c` over Mbed TLS 3.6.5 as1307//   `tls_config.h` configures it (PSA's random bytes from the system,1308//   threads: pthreads, slim reader/writer locks on Windows), built by1309//   `scripts/tls.sh` a section a function into `lib/<target>/tls.a`1310//   (Linux x86-64 and ARM64 against musl and glibc, Windows, macOS1311//   against `src/support/darwin/include`, which gained Mbed TLS's1312//   headers), linked into a program reaching std::tls's externs1313//   (`src/lir/tls_checks.alloy`). Trust: `ALLOY_CA_FILE`, else Linux's1314//   bundle (`SSL_CERT_FILE` first), Windows' CertGetCertificateChain and1315//   SSL policy (revocation an unreachable server cannot answer is1316//   ignored), macOS's SecTrustEvaluateWithError reached by dlopen in1317//   tls.c, built but not yet run on a Mac. `Tls::client` and `handshake`1318//   are the library's, so this module keeps the connection's handle in1319//   the `Control` until the session is disposed.1320// - std::http as above, `Control` a mutex over the connection's handle1321//   and atomic counts. A connection was kept only across one `send`'s1322//   redirections on its origin (question 18); one the server closed1323//   before answering is tried once more on a new one. Since question 18A1324//   (2026-10-16) a `Client` keeps them: `Client {}` (Shared, a `Mutex`1325//   over its idle links, each with when it was kept), `client.send` and1326//   `send_with` taking a link to the origin when it has one, those idle1327//   past `idle_for` (60 seconds) closed as it looks, and giving it back1328//   once its response ended where it said and the server keeps it open,1329//   at most 6 an origin; a retry after a kept link failed opens a new1330//   one. `http::send` and `send_with` make a client for the request and1331//   dispose of it. pkg::alloy::ui keeps one in each app's `Network`.1332//   `tests/driver/http.sh` counts the server's requests on a connection:1333//   ten through one client on one, over TLS too, one the server closed1334//   while kept tried again, and one idle past a short `idle_for` not1335//   taken. On the web `send`1336//   is a fault; `start` over `fetch` comes with F12c.1337// - std::url, std::deflate (the inflate pkg::alloy::text had, with gzip,1338//   gunzip, deflate and crc32), and std::json's floats correctly rounded1339//   (`read_decimal` in std::float_digits).1340// - Compiler: the disposal check takes a match's temporary subject whole1341//   when its moving arms take every disposable variant (`match1342//   (Tls::connect(...)) { ::Ok |move t| ...; ::Err |&e| ... }`), and1343//   knows `while (true)` is left only by a jump.1344// - Tests: `tests/driver/http.sh` (the client and server of1345//   `tests/driver/http`, test certificates trusted through ALLOY_CA_FILE,1346//   macOS builds inspected, WASI and the interpreter Unsupported, a public1347//   site with ALLOY_NETWORK_TESTS=1), `http_aarch64.sh` under qemu, run1348//   tests `url`, `deflate`, `json_floats`; `scripts/windows-tests.sh1349//   build` adds the pair for the desktop, which did not answer this time.1350// - Sizes, release builds: hello world 145,288 bytes natively and 12,2381351//   of wasm, unchanged to the byte; the counter 1,869,152 and 1,331,6791352//   of wasm, unchanged; pkg::alloy::window's hello 1,640,416 and1353//   1,095,127, unchanged. A static Linux program connecting is 41.6 KB1354//   larger than hello world (musl's resolver with it), one adding a TLS1355//   client 256 KB more, and std::http, std::url and std::deflate 89 KB1356//   more (532,336 bytes in all; the estimate was 40 to 60 KB). Checked1357//   builds keep every runtime function, so a checked hello world grows by1358//   the resolver, 309,336 bytes to 336,408.1359// - Sample `language/samples/get.alloy`: a URL's status, headers, time1360//   and body.1361// - Fixed after the review: `send` refuses a header `add_header` said may1362//   not be written, a name empty or holding ':' or a name or value holding1363//   CR, LF or NUL, with `HttpError::Header`, a variant added for it and1364//   named, as `Address` is, after the part of the request at fault. A1365//   `Control` stays cancelled once cancelled, now said on the type: one1366//   reset by each `send_with` would lose a cancel coming before the1367//   exchange starts, so the next exchange takes a new control.1368//   std::deflate checks a stored block's length against its complement,1369//   and `gunzip` reads members one after another as one stream, as RFC1370//   1952 has them. std::json takes an exponent of any length, as1371//   `read_decimal` does, past the range of an f64 giving infinity or zero,1372//   where it refused one of more than 4 digits. The disposal check no1373//   longer takes a subject whole, nor a local as consumed, when a moving1374//   capture leaves something undisposed: an enum disposable itself whose1375//   payloads hold nothing to dispose, or a variant holding something no1376//   moving capture takes (spec section 5.2).