dymokomi/luce-std
Source of release 0.7.3
0.7.3 / src / net / http / encode.lucb
#==============================================================================================
#
# encode - HTTP head and body encoding
#
# DESCRIPTION:
# Serialize an HTTP head into caller storage and write bodies, framing them by their kind
# (fixed length or chunked).
#
#==============================================================================================
## Serialize an HTTP head into caller storage and validate the complete result
## before returning it. On failure the output may contain a prefix: never transmit
## it. Output must not overlap the input fields/text. Framing and Connection fields
## are generated centrally; callers must not supply them in head.fields.
## Up to 100 fields are supported. Reason phrases are intentionally empty.
pub func http_encode_head(output: u8[], head: HttpHead) -> const u8[]!:
var sink = io.SliceWriter.over(output)
var line: u8[64]
if head.version != "HTTP/1.0" and head.version != "HTTP/1.1":
error(http_unsupported, "unsupported HTTP version")
if head.status == 0:
if not http_token(head.method) or not http_request_target_valid(head.method, head.target):
error(http_invalid, "invalid HTTP request line")
try io.write_all(&sink, head.method.bytes)
try io.write_all(&sink, " ".bytes)
try io.write_all(&sink, head.target.bytes)
try io.write_all(&sink, " ".bytes)
try io.write_all(&sink, head.version.bytes)
try io.write_all(&sink, "\r\n".bytes)
else:
if head.status < 100 or head.status > 599:
error(http_invalid, "invalid HTTP status")
try io.write_all(&sink, (try strings.format(line, f"{head.version} {head.status} \r\n")).bytes)
for item in head.fields:
if not http_field_valid(item) or http_equal(item.name, "content-length") or http_equal(item.name, "transfer-encoding") or http_equal(item.name, "connection"):
error(http_invalid, "invalid or generated HTTP field")
try io.write_all(&sink, item.name.bytes)
try io.write_all(&sink, ": ".bytes)
try io.write_all(&sink, item.value.bytes)
try io.write_all(&sink, "\r\n".bytes)
let no_framing = head.status > 0 and (head.status < 200 or head.status == 204 or (head.method == "CONNECT" and head.status < 300))
if no_framing and head.body_kind != HttpBodyKind.empty and head.body_kind != HttpBodyKind.tunnel:
error(http_invalid, "framing is forbidden for this response")
if not no_framing:
if head.status == 304 and head.body_kind == HttpBodyKind.empty:
_ = 0
elif head.body_kind == HttpBodyKind.fixed or head.body_kind == HttpBodyKind.empty:
let size = head.body_length if head.body_kind == HttpBodyKind.fixed else 0
try io.write_all(&sink, (try strings.format(line, f"Content-Length: {size}\r\n")).bytes)
elif head.body_kind == HttpBodyKind.chunked:
if head.version != "HTTP/1.1":
error(http_invalid, "chunked framing requires HTTP/1.1")
try io.write_all(&sink, "Transfer-Encoding: chunked\r\n".bytes)
elif head.body_kind != HttpBodyKind.until_eof or head.status == 0:
error(http_invalid, "invalid outgoing HTTP framing")
if head.keep_alive and head.body_kind != HttpBodyKind.until_eof:
if head.connection_upgrade:
try io.write_all(&sink, "Connection: Upgrade\r\n".bytes)
else:
try io.write_all(&sink, "Connection: keep-alive\r\n".bytes)
else:
try io.write_all(&sink, "Connection: close\r\n".bytes)
try io.write_all(&sink, "\r\n".bytes)
var fields: HttpField[100]
let generous = HttpLimits(body_bytes = 18446744073709551615)
if head.status == 0:
_ = try http_parse_request(sink.written(), fields, generous)
else:
_ = try http_parse_response(sink.written(), fields, head.method, generous)
return sink.written()
# mark: Chunked writing =======================================================================
## Write a nonempty chunk. Empty writes are no-ops; only http_end_chunks ends a
## body. A sink error can follow partial output: abandon that message/connection.
pub func http_write_chunk(destination: Writer, data: const u8[]) -> !:
if data.length == 0:
return
var digits: u8[18]
let alphabet = "0123456789abcdef"
var at: usize = 16
var size = data.length
while size > 0:
at -= 1
digits[at] = alphabet.bytes[size % 16]
size //= 16
digits[16] = '\r'
digits[17] = '\n'
try io.write_all(destination, digits[at..])
try io.write_all(destination, data)
try io.write_all(destination, "\r\n".bytes)
## Terminate a chunked message, without trailers. Trailers can be decoded but the
## initial writer API deliberately emits only complete trailer-free messages.
pub func http_end_chunks(destination: Writer) -> !:
try io.write_all(destination, "0\r\n\r\n".bytes)
## Borrowed body writer with fixed-length accounting and chunked finalization.
## Construct with over; destination outlives this object. Serialize access and do
## not use independent copies. A write/finish error latches because output may
## already be partial. finish never flushes or closes the underlying destination.
pub struct HttpBodyWriter: Writer:
var destination: Writer
var kind: HttpBodyKind
var remaining: u64
var active: bool
var failed: bool
var failure: ErrorCode
## A body writer over `destination` for a body of `kind`.
pub static func over(destination: Writer, kind: HttpBodyKind, length: u64 = 0) -> HttpBodyWriter!:
if kind == HttpBodyKind.tunnel:
error(http_unsupported, "a tunnel has no HTTP body writer")
return HttpBodyWriter(destination = destination, kind = kind, remaining = length if kind == HttpBodyKind.fixed else 0, active = true)
## Write body bytes, framed by the body kind.
pub func write(data: const u8[]) -> usize!:
try self.check()
return self.append(data) catch problem:
self.failed = true
self.failure = problem.code
error(problem.code, problem.message)
func append(data: const u8[]) -> usize!:
if data.length == 0:
return 0
if self.kind == HttpBodyKind.empty or (self.kind == HttpBodyKind.fixed and (u64)data.length > self.remaining):
error(http_invalid, "HTTP body exceeds its declared length")
if self.kind == HttpBodyKind.chunked:
try http_write_chunk(self.destination, data)
else:
try io.write_all(self.destination, data)
if self.kind == HttpBodyKind.fixed:
self.remaining -= (u64)data.length
return data.length
## Finish the body, writing any terminator.
pub func finish() -> !:
try self.check()
self.end_body() catch problem:
self.failed = true
self.failure = problem.code
error(problem.code, problem.message)
self.active = false
func end_body() -> !:
if self.kind == HttpBodyKind.fixed and self.remaining != 0:
error(io.unexpected_eof, "HTTP body is shorter than its declared length")
if self.kind == HttpBodyKind.chunked:
try http_end_chunks(self.destination)
func check() -> !:
if self.failed:
error(self.failure, "HTTP body writer has failed")
if not self.active:
error(io.closed, "HTTP body writer is not active")