The HTTP/2 protocol from the ground up: frames, HPACK header compression and streams.
import net.http2
This package implements HTTP/2 at the protocol level: it builds and reads frames, compresses the headers with HPACK and carries several requests at once over one connection as "streams". It is not a web server or a ready client. For an ordinary web server or one-off requests use net.http, which speaks HTTP/1.1; reach for this package when you need the protocol itself, for example to talk to a service that only offers HTTP/2, to test a server, or to send many requests over one connection.
How it goes: build a Transport over a TCP or TLS socket, take a connection with NewConn and do the handshake. Then the client sends a request with SendHeaders and reads the answer in StreamAt after AwaitStreamEnd. Over TLS, the client and the server must have agreed on h2 through ALPN.
What the package does for you, and what it leaves to you:
•
It answers pings, sends window updates for flow control, waits for window space in SendData, and refuses server push.
•
You write the pseudo-headers yourself: :method, :scheme, :authority and :path on a request, :status on an answer, before any normal header.
•
A stream's body is collected in memory in s.data until the stream ends, and finished streams stay in the connection, so open a new connection now and then rather than keeping one for millions of requests.
•
A Conn belongs to one thread; nothing in it is locked.
Many requests on one connection
The point of HTTP/2 is that one connection carries many requests at the same time. Each request is a stream with an odd id chosen by the client (1, 3, 5 and so on), and the frames of different streams can be interleaved in both directions. The client below sends three requests before reading anything; the server, in the same program, answers them in reverse order, and each answer still lands on the right stream.
net-http2-multiplex.salam
import net.http2
import net.tcp
import compress
mut server := tcp.Server {}
funcserve():
conn := tcp.Accept(server)
mut c := http2.NewConn(http2.PlainTransport(conn.fd), true)
ifnot http2.ServerHandshake(c):
retendmut ids := Vector {} asVector<int>
until ids.Len() < 3:
ids.Push(http2.AwaitAnyHeaders(c, 20))
endmut i := ids.Len() - 1until i >= 0:
id := ids.Get(i)
path := http2.HeadersGet(http2.StreamAt(c, id).headers, ":path")
mut h := http2.HeaderList {}
http2.HeadersAdd(h, ":status", "200")
_ := http2.SendHeaders(c, id, h, false)
_ := http2.SendData(c, id, compress.BufFromStr("page " + path), true)
i--
end
_ := http2.AwaitStreamEnd(c, 0, 5)
http2.CloseConn(c)
endfuncrequest(c &: http2.Conn, path: str): int:
id := http2.NextStreamId(c)
mut h := http2.HeaderList {}
http2.HeadersAdd(h, ":method", "GET")
http2.HeadersAdd(h, ":scheme", "http")
http2.HeadersAdd(h, ":path", path)
http2.HeadersAdd(h, ":authority", "127.0.0.1")
_ := http2.SendHeaders(c, id, h, true)
ret id
endfuncmain:
server = tcp.Bind(0)
t := spawn(serve)
conn := tcp.Dial("127.0.0.1", tcp.Port(server))
mut c := http2.NewConn(http2.PlainTransport(conn.fd), false)
ifnot http2.ClientHandshake(c):
println"handshake failed"ret1endmut ids := Vector {} asVector<int>
each p in ["/a", "/b", "/c"]:
ids.Push(request(c, p))
endprintln"three requests sent on streams", ids.Get(0), ids.Get(1), ids.Get(2)
each id in ids:
_ := http2.AwaitStreamEnd(c, id, 50)
s := http2.StreamAt(c, id)
println"stream",
id,
http2.HeadersGet(s.headers, ":status"),
compress.BufToStrUnsafe(s.data)
endprintln"connections used: 1, streams:", http2.StreamCount(c)
_ := http2.SendGoAway(c, http2.H2_NO_ERROR, "")
http2.CloseConn(c)
join(t)
tcp.CloseServer(server)
ret0end
Output
three requests sent on streams 1 3 5
stream 1 200 page /a
stream 3 200 page /b
stream 5 200 page /c
connections used: 1, streams: 3
AwaitAnyHeaders on the server reads frames until one arrives for a stream whose headers are complete and returns that stream's id, or H2_POLL_ERROR when the connection fails. A request that also has a body sends more frames on the same stream, so a server that accepts bodies should remember which ids it has already seen. AwaitStreamEnd on the client reads frames, for any stream, until the one you asked about has ended; the frames of the others are kept in their streams for later. Its last argument is a limit on how many frames to read, so a broken peer cannot keep you waiting forever.
How much HPACK saves
Requests to one site repeat nearly the same headers every time. HPACK sends a header once, stores it in a table that both sides keep in step, and afterwards sends only its index. The first request below is already smaller than its HTTP/1.1 text because of the static table and the Huffman code; the second and third are about a quarter of the size, because almost everything is now in the dynamic table.
net-http2-hpack-savings.salam
import net.http2
funcrequest_headers(path: str): http2.HeaderList:
mut h := http2.HeaderList {}
http2.HeadersAdd(h, ":method", "GET")
http2.HeadersAdd(h, ":scheme", "https")
http2.HeadersAdd(h, ":authority", "shop.example.com")
http2.HeadersAdd(h, ":path", path)
http2.HeadersAdd(h, "user-agent", "salam-client/1.0")
http2.HeadersAdd(h, "accept", "application/json")
http2.HeadersAddSensitive(h, "authorization", "Bearer eyJhbGciOiJIUzI1NiJ9.e30.x")
ret h
endfuncplain_size(h: http2.HeaderList): int:
mut n := 0each item in h.items:
n += item.name.Len() + item.value.Len() + 4endret n
endfuncmain:
mut table := http2.NewDynTable(4096)
each path in ["/cart", "/cart/items", "/checkout"]:
h := request_headers(path)
block := http2.EncodeHeaderList(table, h, true)
println path,
"as HTTP/1.1 text:",
plain_size(h),
"bytes, HPACK:",
block.len,
"bytes, table entries:",
http2.DynCount(table)
endprintln"huffman alone, user-agent value:",
"salam-client/1.0".Len(),
"->",
http2.HuffmanEncodedLenStr("salam-client/1.0")
end
The authorization header is added with HeadersAddSensitive, so it is never put in the table and is sent in full every time. That costs a few bytes but stops an attacker who can influence other headers on the same connection from guessing the token by watching the compressed size, the attack known as CRIME.
HTTP/2 over TLS to a real server
Servers on the internet offer HTTP/2 only over TLS, and only to clients that ask for it during the TLS handshake. Set alpn to h2 in the tls config, connect with tls.Dial, and wrap the connection with TLSTransport. If the server did not pick h2, ClientHandshake fails and you should fall back to HTTP/1.1.
net-http2-tls-get.salam
import net.http2
import tls
funcmain:
host := "www.cloudflare.com"mut cfg := tls.NewConfig(host)
cfg.alpn = "h2"
secure := tls.Dial(host, 443, cfg)
ifnot tls.ConnOk(secure):
println"TLS failed:", tls.ConnError(secure)
ret1endmut c := http2.NewConn(http2.TLSTransport(secure), false)
ifnot http2.ClientHandshake(c):
println"the server did not agree to HTTP/2"ret1end
id := http2.NextStreamId(c)
mut h := http2.HeaderList {}
http2.HeadersAdd(h, ":method", "HEAD")
http2.HeadersAdd(h, ":scheme", "https")
http2.HeadersAdd(h, ":path", "/")
http2.HeadersAdd(h, ":authority", host)
_ := http2.SendHeaders(c, id, h, true)
if http2.AwaitStreamEnd(c, id, 100):
s := http2.StreamAt(c, id)
println"status:", http2.HeadersGet(s.headers, ":status")
println"server:", http2.HeadersGet(s.headers, "server")
println"body bytes:", s.data.len
end
http2.CloseConn(c)
ret0end
It needs network access, so it is only checked here. Run against Cloudflare, it printed:
status: 200
server: cloudflare
body bytes: 0
The body is empty because the request used HEAD. With GET, the page arrives in s.data as one buffer, after the package has already sent the window updates that flow control needs.
The HPACK dynamic table, which keeps the headers sent or received so that next time only their number is sent. Each side has its own table and the two must stay in step.
The flags in the fifth byte of a frame. What each flag means depends on the frame type; that is why H2_FLAG_END_STREAM and H2_FLAG_ACK are both 1, one for a data or headers frame and the other for settings and ping. Check them with FrameHasFlag.