यह किताब अभी हिन्दी में उपलब्ध नहीं है। संस्करण: English।
University Computer Science — Year 2 · स्नातक वर्ष 2
20The Application Layer: DNS, HTTP and TLS
A program asks for the page at http://www.brenmoor.test/, the way a browser does when an address is typed:
$ python visit.py
looking up www.brenmoor.test ... 127.0.0.1
connecting to 127.0.0.1 port 44203 ... connected
GET / ... 200 OK, 58 bytes of text/html
<h1>Brenmoor</h1>
<p>Welcome to the town of Brenmoor.</p>
Three protocols took part. The name system turned the name into an address, TCP opened a connection to it, and HTTP carried the request and the page. All three servers are this chapter’s own programs, running on this machine: the name server listens on UDP port 44202 and the web server on TCP port 44203. This chapter builds them, speaking the real formats, then adds the layer that makes the exchange private, TLS, and counts what a first visit costs in round trips.
You already know
Book 1: a name such as library.brenmoor.example is looked up in the name system, which answers with an address. Book 2: an HTTP request names a method and a path, and the response carries a status, headers and a body; a secure connection uses keys and a certificate that a trusted authority has signed. Chapter 16: sockets and ports. Chapter 19: UDP datagrams, TCP’s handshake and its byte stream.
20.1 The name system
Definition 20.1 (Domain name, name system, zone)
A domain name is a sequence of labels written from the most specific to the most general, such as www.brenmoor.test; the names form a tree whose root has the empty name. The domain name system (DNS) is the distributed database that maps names to data such as addresses. It is cut into zones: a zone is a part of the tree whose data one organisation keeps, and it may delegate a subtree to another zone.
The name .test is reserved for testing, so no real server answers for it: the town’s zone, brenmoor.test, lives only in this chapter’s programs.
Definition 20.2 (Resolver, authoritative server)
An authoritative server of a zone answers for the names of that zone, and for the names of a delegated subtree it answers with a referral: the names and addresses of that subtree’s servers. A resolver finds the data for a name. In iterative resolution it asks the servers itself, following referrals from the root down; in recursive resolution it asks another resolver to do the whole job and send only the final answer.
test (query 1), which refer it to those of brenmoor.test (query 2), whose zone holds the answer (query 3).Definition 20.3 (Resource record, record lifetime)
A resource record is one fact about a name: the name, a type, a lifetime (TTL, time to live) and data. The common types are A (an IPv4 address, type 1), AAAA (an IPv6 address, 28), NS (a name server of the zone, 2), CNAME (the name is an alias of another, 5), MX (a mail server, with a preference, 15) and TXT (text, 16). A resolver may keep a record in its cache for the record’s lifetime, in seconds, and no longer.
Method 20.4 (Iterative resolution)
To find the records of type for a name: start with a root server. Ask the current server for the name and . If the reply holds answers, return them (an alias, CNAME, comes with the records of its target when the zone holds them). If it says the name does not exist, stop. If it is a referral, take one of the named servers, with its address from the reply’s additional records (the glue), and ask it in turn.
$ python resolve.py
ask 192.0.2.53 library.brenmoor.test A
referral: test is served by ns.test at 198.51.100.53
ask 198.51.100.53 library.brenmoor.test A
referral: brenmoor.test is served by ns.brenmoor.test at 203.0.113.53
ask 203.0.113.53 library.brenmoor.test A
answer: library.brenmoor.test CNAME www.brenmoor.test (lifetime 3600 s)
answer: www.brenmoor.test A 127.0.0.1 (lifetime 3600 s)
(3 queries)
ask 192.0.2.53 nowhere.brenmoor.test A
referral: test is served by ns.test at 198.51.100.53
ask 198.51.100.53 nowhere.brenmoor.test A
referral: brenmoor.test is served by ns.brenmoor.test at 203.0.113.53
ask 203.0.113.53 nowhere.brenmoor.test A
no such name
(3 queries)
The servers of zone.py answer from a list of records; the referral comes from an NS record whose name lies below the server’s own zone. Each question costs one round trip to a server, so a resolver that remembers nothing pays three round trips for every name of the town.
20.1.1 The message format
Queries and answers share one format. A 12-byte header holds an identifier, which the answer copies so that the client can match it with its question, sixteen bits of flags, and four counts; then come the question, and three lists of records: the answers, the authority (NS records of a referral), and additional records (glue). A message travels in one UDP datagram to port 53, or over TCP when it exceeds 512 bytes.
A name is written as its labels, each preceded by its length (at most 63), and ends with a zero byte, the empty label of the root. Since the names of one answer repeat the same suffixes, a name may end with a pointer: two bytes whose first two bits are 1, the other 14 giving the offset, from the start of the message, of a suffix written earlier.
def encode_name(name, out, table):
"""Append name to out, ending with a pointer to a suffix already written."""
labels = name.rstrip(".").split(".") if name.strip(".") else []
for i in range(len(labels)):
suffix = ".".join(labels[i:]).lower()
if suffix in table: # written before: point to it
out += struct.pack(">H", 0xC000 | table[suffix])
return
if len(out) < 0x4000: # a pointer holds 14 bits
table[suffix] = len(out)
label = labels[i].encode()
assert 0 < len(label) <= 63, "a label has 1 to 63 bytes"
out += bytes([len(label)]) + label
out += b"\0" # the root: an empty label
def read_name(buf, pos):
"""Return (name, position after it); pointers must point backwards."""
labels, end, start = [], None, pos
while True:
n = buf[pos]
if n >= 0xC0: # 11xxxxxx: a pointer
target = struct.unpack_from(">H", buf, pos)[0] & 0x3FFF
if target >= start:
raise ValueError(f"pointer at {pos} to {target}, not before {start}")
end = pos + 2 if end is None else end
pos = start = target
elif n == 0:
return ".".join(labels), (pos + 1 if end is None else end)
else:
labels.append(buf[pos + 1:pos + 1 + n].decode())
pos += 1 + n
A pointer could point anywhere, including to itself, and a careless reader would then loop for ever on a 14-byte message from anyone. The reader above refuses any pointer that does not go back.
Proposition 20.5 (Compression terminates)
If every pointer points to an offset strictly before the start of the stretch of labels in which it appears, reading a name from a message of bytes ends after at most steps.
Proof. Reading proceeds in stretches: a stretch starts at the name’s position or at a pointer’s target, and moves forward label by label until a zero byte or a pointer. Within a stretch every step moves forward, and a stretch ends before the end of the message. A pointer starts a new stretch at an offset strictly smaller than the start of the current one, so the starts of the stretches strictly decrease. Every byte read lies at or after the start of its stretch and before the start of the previous one (or the end of the message for the first stretch), so the stretches read disjoint ranges of bytes, and the total number of steps is at most . ∎
$ python dns_message.py
query of 35 bytes
header: 2a 17 00 00 00 01 00 00 00 00 00 00
question: 03 77 77 77 08 62 72 65 6e 6d 6f 6f 72 04 74 65 73 74 00 00 01 00 01
response: 84 bytes; without compression: 143 bytes
answer www.brenmoor.test A 3600 127.0.0.1
authority brenmoor.test NS 86400 ns.brenmoor.test
additional ns.brenmoor.test A 86400 203.0.113.53
With compression the answer takes 84 bytes instead of 143. On a real socket, the zone’s server answers queries for any of its records; a name it does not hold gets RCODE 3, “no such name”:
$ python dns_demo.py
www.brenmoor.test A 35 -> 51 bytes ok 127.0.0.1
www.brenmoor.test AAAA 35 -> 63 bytes ok 2001:db8::80
brenmoor.test MX 31 -> 52 bytes ok 10 mail.brenmoor.test
brenmoor.test TXT 31 -> 62 bytes ok Brenmoor town hall
nowhere.brenmoor.test A 39 -> 39 bytes no such name none
20.1.2 Caching
Resolvers keep answers and referrals for their lifetimes. A machine asks one nearby resolver, recursively; that resolver resolves iteratively, and its cache serves every machine behind it. The gain depends on how often a name is asked for: if queries for a name arrive at random at rate per second and its record lives seconds, the fraction answered from the cache is (Exercise 20.8).
$ python resolver_cache.py
queries/s lifetime simulated rT/(1 + rT)
0.0017 3600 s 0.8568 0.8571
0.0167 3600 s 0.9836 0.9836
1.0000 3600 s 0.9997 0.9997
0.0167 60 s 0.4997 0.5000
1.0000 60 s 0.9836 0.9836
100.0000 60 s 0.9998 0.9998
A name asked once an hour with a lifetime of an hour still saves half the queries; a busy name is almost never asked upstream. The price is staleness: a record changed at its zone may be served from caches for up to its old lifetime, which is why zones lower the lifetime of a record some time before changing it.
20.2 HTTP
An HTTP request is lines of text: a method, a path and a version, then headers, then an empty line, and a body for methods that send one. The response starts with a status line, then headers and the body. The default port is 80, and 443 for HTTP over TLS. A request by hand, then two ways of fetching twenty pages:
$ python http_demo.py
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 44
Connection: close
<h1>Library</h1>
<p>Open 9:00 to 18:00.</p>
urllib: {'connections': 20, 'requests': 20}
http.client: {'connections': 1, 'requests': 20}
Definition 20.6 (Persistent connection, head-of-line blocking)
A persistent connection carries several requests and their responses, one after the other, instead of one; it is HTTP/1.1’s default, and a Connection: close header announces that the connection will be closed after the response. Head-of-line blocking is the delay a response suffers because something before it on the same connection, or in the same ordered stream, has not finished.
On a persistent connection the client must know where each body ends, so the server sends either a Content-Length header or, when it does not know the length in advance, a chunked body: chunks, each preceded by its size in hexadecimal, and a last chunk of size 0 (Exercise 20.5). The town’s server reads requests one after the other on each connection:
def handle(conn):
stats["connections"] += 1
reader = conn.makefile("rb")
while True:
line = reader.readline().decode() # GET /library HTTP/1.1
if not line:
break # the client closed
method, path, version = line.split()
headers = {}
while (h := reader.readline().decode().strip()):
key, value = h.split(":", 1)
headers[key.lower()] = value.strip()
stats["requests"] += 1
body = PAGES.get(path)
status = "200 OK" if body else "404 Not Found"
body = body or b"<h1>Not found</h1>\n"
close = headers.get("connection") == "close" or version == "HTTP/1.0"
head = (f"HTTP/1.1 {status}\r\nContent-Type: text/html\r\n"
f"Content-Length: {len(body)}\r\n"
+ ("Connection: close\r\n" if close else "") + "\r\n").encode()
conn.sendall(head if method == "HEAD" else head + body)
if close:
break
conn.close()
urllib asked for a close each time, so it paid a TCP handshake per page; http.client kept one connection for all twenty. On a connection of HTTP/1.1, though, the second response cannot start before the first is complete. Browsers open several connections at once to fetch a page’s parts in parallel.
Definition 20.7 (Stream multiplexing)
In HTTP/2, a connection carries numbered streams, one per request and its response, whose data travel in frames: each frame starts with a 9-byte header giving its length, its type (such as DATA 0 and HEADERS 1), flags and the number of its stream. Frames of different streams may be interleaved, so responses progress together on one connection: this is stream multiplexing.
Multiplexing removes head-of-line blocking between responses, but not below them: the frames still travel in one TCP byte stream, and a lost TCP segment holds back everything after it until it is sent again. A model of four pages of 8 packets each, with a round trip of 50 ms, and the fifth packet lost:
$ python hol_blocking.py
page HTTP/1.1 HTTP/2 (TCP) HTTP/3 (QUIC) no loss (ms, page complete)
0 107 107 107 78
1 164 107 79 79
2 221 107 80 80
3 278 107 81 81
hol_blocking.py).HTTP/1.1 fetches the pages in turn, and the loss delays all of them. HTTP/2 brings them in parallel, but the loss delays all four to 107 ms, when the lost packet’s copy arrives. With HTTP/3, each stream is ordered on its own, and only the page that lost a packet waits (Exercise 20.10).
Facts as of 2026
HTTP/3, standardised in June 2022, carries HTTP over QUIC (Chapter 19): its streams are QUIC streams, each delivered in order on its own, so that a loss on one stream does not hold back the others. It is used alongside HTTP/2 and HTTP/1.1, which remain in wide use; a server announces that it speaks HTTP/3 in its HTTP/1.1 or HTTP/2 responses.
20.3 Electronic mail
Mail moves between servers by SMTP, over TCP port 25, in a dialogue of text lines. To deliver a letter to [email protected], a server looks up the MX records of example.net, tries the one with the lowest preference value first, connects to it, and the two exchange:
| client | server | meaning |
220 mail.example.net | ready | |
EHLO post.example.org | 250 | greeting |
MAIL FROM:<[email protected]> | 250 | the sender |
RCPT TO:<[email protected]> | 250 | one recipient (several allowed) |
DATA | 354 | send the letter |
the letter, then a line holding only . | 250 | accepted |
QUIT | 221 | closing |
The three-digit codes are for programs, the text after them for people; the first digit says whether the command succeeded (2), needs more (3), or failed (4 temporarily, 5 for good). The letter itself, with its From, To and Subject lines, is only data to SMTP: nothing in the protocol checks that the From line is true, which is why mail systems added signatures and checks of their own.
20.4 TLS
Everything so far crossed the network in clear: anyone on the path could read the page or change it. TLS adds a layer between TCP and the application.
Definition 20.8 (Transport Layer Security)
Transport Layer Security (TLS) is a layer that runs over a reliable byte stream such as TCP and gives the application above it a byte stream that is private (encrypted), protected against modification, and attached to a verified name. It cuts the application’s bytes into TLS records, each of at most bytes of data, sent encrypted after a 5-byte header (a content type, a version and a length).
Before any record of data, a handshake agrees on keys and proves the server’s identity. In TLS 1.3 it takes one round trip:
The certificate binds the server’s public key to its name, and is signed by an authority that the client trusts; the mathematics of keys and signatures are the Year 3 volume’s. Python’s ssl module provides TLS over a socket. The session below makes a certificate for www.brenmoor.test with openssl (a self-signed one, which the client is told to trust), then runs an echo pair and a client that asks for another name:
$ python3 tls_echo.py
version: TLSv1.3
cipher: TLS_AES_256_GCM_SHA384
server certificate for: www.brenmoor.test (verified)
echo: HELLO FROM THE LIBRARY
$ python3 tls_wrong_name.py
refused: Hostname mismatch, certificate is not valid for 'mail.brenmoor.test'.
The second client refuses the connection: the certificate is valid, but not for mail.brenmoor.test. Checking the name is as important as checking the signature; a client that skipped it would accept any server holding any certificate.
What TLS does not hide matters too. The addresses and ports are visible to every router, and so are the sizes and times of the records. The name lookup before the connection normally travels in clear, and the ClientHello usually carries the name of the site in clear, so that a server holding several sites can pick the right certificate.
20.4.1 The cost of a first visit
Every protocol of this chapter waits for an answer before the next can start, so a first visit is a chain of round trips.
Proposition 20.9 (Round trips of a visit)
Let a page be small enough to arrive in one round trip, and let RTT be the round-trip time to the server. A first visit over HTTPS, with TCP and TLS 1.3, takes the time of the name lookup plus . A visit on a new connection with the name cached on the machine takes , and a request on a connection already open takes .
Proof. The client cannot connect before it knows the address. TCP’s handshake costs one round trip: the client can send only after the SYN+ACK arrives (its last ACK travels with the ClientHello). The client can send the request only after the server’s Finished arrives, one more round trip. The response comes back one round trip after the request leaves. Each of these waits is a full round trip and none can overlap the next, which gives ; on an open connection only the last remains. ∎
$ python budget.py
first visit, resolver knows nothing 370 ms
first visit, resolver knows brenmoor.test 290 ms
first visit, resolver has the name 250 ms
revisit, name cached on the machine 240 ms
revisit, connection still open 80 ms
A cold first visit spends 130 ms of its 370 on the name, which is why resolvers cache, and the rest on handshakes, which is why browsers keep connections open and why TLS 1.3 cut the handshake to one round trip.
In practice
Opening a page usually costs more than this: a page names dozens of other resources (pictures, style sheets, scripts), often on other servers, each with its own name to look up and its own connection. Shortening the chain of round trips (persistent connections, caches near the users, fewer servers per page) often saves more time than a faster link does.
20.5 Exercises
Exercise 20.1 ★
Decode the DNS header 2a 17 85 83 00 01 00 00 00 00 00 00: is it a question or an answer, what flags are set, and what does it say about the name asked?
Solution
Solution of Exercise 20.1.
$ python exo_header.py
id 0x2a17
QR 1
opcode 0
AA 1
TC 0
RD 1
RA 1
Z 0
RCODE 3
counts: 1 question, 0 answers, 0 authority, 0 additional
QR is 1: it is an answer, to the query with identifier 2a17. The server is authoritative (AA), the query asked for recursion (RD) and the server offers it (RA). RCODE 3 says that the name asked does not exist, which is why there are no answers; the question is repeated, as in every answer.
Exercise 20.2 ★
A message contains, from offset 12, the bytes 03 77 77 77 c0 0c. What does a reader that follows every pointer do with it? Bound the number of pointers a reader must follow in a message of bytes, with or without the rule of Proposition 20.5.
Solution
Solution of Exercise 20.2.
$ python exo_loop.py
('ftp.www', 23)
rejected: pointer at 16 to 12, not before 12
The name starts at 12 with the label www, and the pointer at 16 sends the reader back to 12: a reader that follows every pointer reads www.www.www… for ever, and a 6-byte trick stops a careless server. With the rule of Proposition 20.5, each pointer lands strictly before the previous start, so a reader follows fewer than pointers (each one starts a stretch of at least two bytes). Without the rule, a reader can still stop: on a path without a loop it meets each pointer at most once, and a message of bytes holds at most pointers, so a reader that has followed more than has met a loop and may reject the message. The limit of 255 bytes on a name does not suffice alone, since c0 0c at offset 12 loops without adding a byte.
Exercise 20.3 ★
Write, byte by byte, a query with identifier 0b0e that asks for the AAAA records of www.brenmoor.test, with recursion desired.
Solution
Solution of Exercise 20.3.
$ python exo_aaaa.py
0b 0e 01 00 00 01 00 00 00 00 00 00
03 77 77 77 08 62 72 65 6e 6d 6f 6f
72 04 74 65 73 74 00 00 1c 00 01
The header: identifier 0b 0e, flags 01 00 (only RD), one question, no records. The name: 03 www, 08 brenmoor, 04 test, 00; then the type 00 1c (28, AAAA) and the class 00 01 (Internet): 35 bytes.
Exercise 20.4 ★
A machine asks its resolver for mail.brenmoor.test. How many queries does the resolver send if its cache is empty, if it holds the referral to brenmoor.test, and if it holds the answer? How many round trips does the machine wait in each case?
Solution
Solution of Exercise 20.4.
Empty cache: three queries (root, test, brenmoor.test). With the referral to brenmoor.test cached: one, to the town’s server. With the answer cached: none. The machine waits one round trip to its resolver, plus the resolver’s queries: in the three cases 1 + 3, 1 + 1 and 1 round trip, of different lengths since the resolver is usually much closer than the name servers.
Exercise 20.5 ★★
Write dechunk(data), which decodes a chunked body and returns it with the number of bytes used, and raises an error if the coding is cut short.
Solution
Solution of Exercise 20.5.
def dechunk(data):
"""Return (body, bytes used); raise ValueError if the coding is cut short."""
body, pos = b"", 0
while True:
end = data.find(b"\r\n", pos)
if end < 0:
raise ValueError("no size line")
size = int(data[pos:end].split(b";")[0], 16) # hex; extensions ignored
pos = end + 2
if size == 0: # the last chunk; then an empty line
if data[pos:pos + 2] != b"\r\n":
raise ValueError("no final empty line")
return body, pos + 2
if data[pos + size:pos + size + 2] != b"\r\n":
raise ValueError("chunk shorter than its size")
body += data[pos:pos + size]
pos += size + 2
Each chunk is a size line, the data and a line end; the size is read in hexadecimal, and anything after a ; on the size line (an extension) is ignored. The last chunk has size 0 and is followed by an empty line. Returning the number of bytes used lets the caller read the next response on the same connection. The test feeds it a body with an extension and with line ends inside the data, and three cut or lying bodies.
Exercise 20.6 ★★
This server announces 12 bytes and sends 10. What does a client do, and why?
def serve():
conn, _ = listener.accept()
conn.recv(1024)
conn.sendall(b"HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\n0123456789")
threading.Event().wait(5) # keeps the connection open
Solution
Solution of Exercise 20.6.
$ python exo_content_length.py
no answer after 1 s: the client is still waiting for 2 bytes
The client trusts Content-Length and waits for the two missing bytes. On a persistent connection the server keeps the connection open, so nothing tells the client that no more will come: without a timeout it waits for ever. Had the server closed the connection, the client would have seen a body shorter than announced and reported an error.
Exercise 20.7 ★★
A first version of the server answered one request per connection and knew only GET. Write the changes that keep the connection open unless the client asks to close it or speaks HTTP/1.0, and that answer HEAD, which sends the headers of GET without the body.
Solution
Solution of Exercise 20.7.
close = headers.get("connection") == "close" or version == "HTTP/1.0"
head = (f"HTTP/1.1 {status}\r\nContent-Type: text/html\r\n"
f"Content-Length: {len(body)}\r\n"
+ ("Connection: close\r\n" if close else "") + "\r\n").encode()
conn.sendall(head if method == "HEAD" else head + body)
if close:
break
HEAD code/bachelor-2/20-application-layer/listings/http_server.pyThe loop of Listing 20.3 reads the next request on the same connection, and leaves only on a close asked by the client (or an HTTP/1.0 request, whose default was to close) or when the client closes. For HEAD, the headers are those of GET, including the Content-Length the body would have had, and the body is not sent. The test sends GET, HEAD and GET on one connection and checks one connection, the lengths and the empty body.
Exercise 20.8 ★★
Queries for a name arrive as a Poisson process of rate , and a resolver caches the answer for seconds after each query it sends upstream. Show that the fraction of queries answered from the cache is .
Solution
Solution of Exercise 20.8.
Cut time into cycles, each starting with a query sent upstream (a miss). The answer is then cached for seconds, and every query in that interval is a hit; the first query after it is the next miss. In a Poisson process the number of queries in an interval of length has mean , whatever happened before. A cycle therefore holds one miss and on average hits, and over many cycles the fraction of hits is
Output 20.5 agrees to within 0.0005: with (one query a minute, a lifetime of a minute), half the queries are hits.
Exercise 20.9 ★★
Write a resolver that resolves iteratively, keeps answers and referrals for their lifetimes, and starts each resolution from the closest zone whose servers it knows.
Solution
Solution of Exercise 20.9.
class CachingResolver:
def __init__(self, send, clock):
self.send, self.clock, self.cache, self.queries = send, clock, {}, 0
def lookup(self, key):
hit = self.cache.get(key)
return hit[1] if hit and hit[0] > self.clock() else None
def keep(self, key, records):
ttl = min(r[2] for r in records) # the shortest lifetime decides
self.cache[key] = (self.clock() + ttl, records)
def resolve(self, name, rtype):
if (hit := self.lookup((name, rtype))) is not None:
return hit
server, labels = ROOT_ADDRESS, name.split(".")
for i in range(1, len(labels) + 1): # the closest known zone cut
known = self.lookup((".".join(labels[i:]), "glue"))
if known:
server = known[0][3]
break
while True:
self.queries += 1
reply = decode(self.send(server, query(self.queries, name, rtype)))
if reply["answer"] or not reply["authority"]:
if reply["answer"]:
self.keep((name, rtype), reply["answer"])
return reply["answer"]
ns = reply["authority"][0]
glue = [g for g in reply["additional"] if g[0] == ns[3]]
self.keep((ns[0], "glue"), glue) # whom to ask for that zone
server = glue[0][3]
The cache maps a name and a type to records and an expiry time; referrals are kept under the zone’s name, as the address of its server (the glue). A resolution first looks for the answer, then for the closest enclosing zone whose server it knows, and starts there instead of at the root. The test runs it on the toy network with a clock it moves by hand: www costs 3 queries, then 0; mail costs 1; after 4000 s www costs 1 again, and after two days 3.
Exercise 20.10 ★★★
In the model of Output 20.7, packets leave one per millisecond from 25 ms, and a lost packet’s copy arrives ms after the third packet behind it leaves. Compute when each page is complete with HTTP/2 and with HTTP/3, and explain why HTTP/1.1 is slowest.
Solution
Solution of Exercise 20.10.
Packet (from 0 to 31) belongs to page , leaves at ms and arrives at . Packet 4, page 0’s second, is lost; packet 7 leaves at 32 ms, so the copy arrives at ms. Each page’s last packet arrives at 78, 79, 80 and 81 ms. With HTTP/2, TCP delivers bytes in order: nothing after packet 4 reaches the application before 107 ms, so all four pages complete at 107. With HTTP/3, each stream waits only for its own packets: page 0 completes at 107, pages 1 to 3 at 79, 80 and 81, as without loss. HTTP/1.1 is slowest because each page waits for the previous one and for its own request to cross the network: a page takes ms after its request leaves, and page 0 takes until 107 because of the loss, so the others complete at 164, 221 and 278 ms.
Exercise 20.11 ★★★
Write a TLS echo pair on 127.0.0.1: the server uses a certificate and key from files, and the client trusts only that certificate and checks the server’s name.
Solution
Solution of Exercise 20.11.
server_ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
server_ctx.load_cert_chain("cert.pem", "key.pem") # made by openssl just before
listener = socket.create_server(("127.0.0.1", 44205))
def serve():
conn, _ = listener.accept()
with server_ctx.wrap_socket(conn, server_side=True) as tls:
tls.sendall(tls.recv(1024).upper()) # decrypted, answered, encrypted
threading.Thread(target=serve, daemon=True).start()
client_ctx = ssl.create_default_context(cafile="cert.pem") # trust only this one
with socket.create_connection(("127.0.0.1", 44205)) as raw:
with client_ctx.wrap_socket(raw, server_hostname="www.brenmoor.test") as tls:
print("version:", tls.version())
print("cipher: ", tls.cipher()[0])
subject = dict(x[0] for x in tls.getpeercert()["subject"])
print("server certificate for:", subject["commonName"], "(verified)")
tls.sendall(b"hello from the library")
print("echo:", tls.recv(1024).decode())
The client’s context trusts only the given certificate (cafile), and server_hostname makes the module check that the certificate names www.brenmoor.test; create_default_context turns both checks on. The server reads one message and sends it back in capitals: TLS gives it plain bytes, as TCP would.
Exercise 20.12 ★★★
Measure, after the handshake, how many bytes TLS sends for messages of 1 byte to 100 000 bytes, and explain the extra bytes per record. What fraction of the traffic is overhead for messages of 1, 100 and 16 384 bytes?
Solution
Solution of Exercise 20.12.
$ python3 tls_overhead.py
handshake done: TLSv1.3 TLS_AES_256_GCM_SHA384
message on the wire records extra bytes per record
1 23 1 22
100 122 1 22
1000 1022 1 22
16384 16406 1 22
16385 16429 2 22
100000 100154 7 22
Each record adds 22 bytes: the 5-byte header, the 1-byte real content type that TLS 1.3 places inside the encrypted part, and a 16-byte authentication tag that lets the receiver detect any change. A record holds at most 16 384 bytes, so 16 385 bytes take two records and 44 extra bytes. The overhead is of the traffic for a 1-byte message, for 100 bytes and for 16 384: small messages should be grouped before they are sent.
20.6 Problem: Brenmoor goes online
Problem 20.1
Weekend problem — Brenmoor goes online
The town puts its name server, its resolver and its web site online, and wants to know what a first visit costs.
Part I — The zone and its server.
- List the records of
zone.py’s town zone by type, and say what each is for. - Why must the zone
testhold the address ofns.brenmoor.test, although the name lies inbrenmoor.test? - In Output 20.4, why is the answer for the MX query longer than the query by only 21 bytes?
- A record of
libraryis a CNAME. What does the server send for its A record, and why in one answer? - What does RCODE 3 tell a resolver that an empty answer with RCODE 0 does not?
- Why does the server reject a name whose pointer does not go back, instead of following it?
Part II — A resolver with a cache.
- How many queries does an empty resolver send for
www, then formail, then forwwwagain within the hour? - After three days without queries, how many does it send for
www? - The town’s site is asked for 1000 times a day. With a lifetime of 3600 s, what fraction of the lookups reach the town’s server?
- The town moves its web server. How long may some users still reach the old address, and how can the town shorten it?
- Why does a resolver use the shortest lifetime of a set of records for the whole set?
- Why do machines ask a resolver recursively, rather than resolve iteratively themselves?
Part III — A web server with persistent connections.
- In Output 20.6, how many TCP handshakes did each client pay?
- With a round trip of 80 ms, how much time did the persistent connection save over twenty pages?
- How does the server know where a request ends, and the client where a response ends?
- Why can the server not answer the second request on a connection before the first?
- In Output 20.7, which pages does the loss delay with HTTP/2, and by how much?
- Why does HTTP/3 need a transport other than TCP to avoid that delay?
Part IV — The cost of a first page load.
- Using Proposition 20.9, how long does a cold first visit take in Output 20.9, and how much of it is the name?
- How long does a revisit on a new connection take, and one on an open connection?
- How many round trips would a TLS handshake of two round trips add to every new connection?
- A page needs 30 resources from 3 servers. With one connection per server kept open, how many handshakes does it pay?
- What does TLS hide on such a visit, and what can an observer of the network still learn?
- State the result: the round-trip budget of a first visit (name lookup, connection, handshake, request) and of a revisit.
Solution
Solution of Problem 20.1.
1. NS: the zone’s server; A: the addresses of ns, www and mail; AAAA: the IPv6 address of www; MX: the town’s mail server, preference 10; TXT: a line of text; CNAME: library is another name of www.
2. To reach ns.brenmoor.test a resolver would have to resolve a name inside the zone it is trying to reach, a circle. The glue record in the parent zone breaks it.
3. The answer repeats the question and adds one record: a pointer to the name (2 bytes), type, class, lifetime and length (10), the preference (2), the label mail (5) and a pointer to brenmoor.test (2): 21 bytes.
4. The CNAME record and the A record of www, in one answer, so that the resolver needs no second query.
5. That the name does not exist at all, for any type; RCODE 0 with no answer means that the name exists without records of that type.
6. A loop would keep the server busy for ever on a message of a few bytes; by Proposition 20.5, refusing it makes every read end.
7. 3, then 1 (the referral to brenmoor.test is cached), then 0.
8. 3: every record has expired, the longest-lived (the referral to test) after 172 800 s, two days.
9. per second and , so a fraction of one resolver’s lookups reach the town’s server; each resolver has its own cache.
10. For up to the record’s lifetime, an hour. The town lowers the lifetime (to a minute, say) at least an hour before the move, then moves, then raises it again.
11. The records of an answer belong together (an alias and its target’s address, a referral and its glue); a part kept after another has expired could point to data the zone no longer holds.
12. One resolver serves many machines, so its cache is shared; a machine waits one round trip to a nearby resolver, and needs no code to follow referrals.
13. urllib: 20; http.client: 1.
14. 19 handshakes of 80 ms: about 1.5 s.
15. A request’s headers end with an empty line, and these requests have no body (a request with one says its length). A response’s body length is given by Content-Length.
16. Responses on an HTTP/1.1 connection come in the order of the requests, and nothing in a response says which request it answers.
17. All four, which complete at 107 ms instead of 78 to 81: by 29, 28, 27 and 26 ms.
18. TCP delivers one byte stream in order, and holds back all bytes after a lost segment; it knows nothing of HTTP’s streams. QUIC orders the bytes of each stream separately.
19. 370 ms, of which 130 are the name.
20. 240 ms on a new connection, 80 ms on an open one.
21. One round trip per new connection: a cold first visit would take 450 ms.
22. Three TCP and three TLS handshakes, one per server; the 30 requests then cost round trips but no new handshakes.
23. TLS hides the pages, the paths, the headers and the data sent. An observer still sees the addresses and ports, the times and sizes of the records, the name lookups (in clear by default) and the site’s name in the ClientHello.
24. A first visit costs the name lookup (one round trip to the resolver plus one per name server it must ask) and three round trips: TCP, TLS 1.3 and the request. Here 370 ms; a revisit costs 240 ms on a new connection and 80 ms on an open one.