tobogganSe connecter

louise

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

80 lignes · 2544 octetsBrut · Historique
1import std/bytes
2import std/http.{type Request, Request}
3import std/io
4import std/net.{type SocketAddress, SocketAddress}
5
6// The client's address (issue #308), on requests built by hand: the
7// server puts the peer first, as the `:peer` pseudo-header; `peer`
8// finds it anywhere in the list (issue #313).
9fn request :: peer: SocketAddress headers: List<(String, String)> -> Request
10{
11 http.with_peer Request("GET", "/", headers, bytes.empty ()) peer
12}
13
14fn shown :: o: Option<String> -> String
15{
16 match o { Some(s) -> s, None -> "none" }
17}
18
19pub fn main :: -> () / <io>
20{
21 // No peer: a request built by hand.
22 let plain = Request("GET", "/", [("Host", "x")], bytes.empty ())
23 io.println (shown (http.client_address plain []))
24 //> none
25 match http.peer (request SocketAddress("::1", 4242) [])
26 { Some(SocketAddress(host, port)) -> io.println (host <> " " <> show port)
27 , None -> io.println "no peer"
28 }
29 //> ::1 4242
30 // `:peer` not first (issue #313): still found, anywhere in the list.
31 let buried =
32 Request( "GET"
33 , "/"
34 , [("Host", "x"), (":peer", "10.0.0.2:1")]
35 , bytes.empty ()
36 )
37 match http.peer buried
38 { Some(SocketAddress(host, port)) -> io.println (host <> " " <> show port)
39 , None -> io.println "no peer"
40 }
41 //> 10.0.0.2 1
42 io.println (shown (http.client_address buried []))
43 //> 10.0.0.2
44 // A direct client: its X-Forwarded-For, which anyone can send, is
45 // ignored.
46 let spoofed =
47 request SocketAddress("198.51.100.4", 5000) [("X-Forwarded-For", "1.2.3.4")]
48 io.println (shown (http.client_address spoofed ["10.0.0.2"]))
49 //> 198.51.100.4
50 // Behind a trusted proxy: the right-most untrusted entry.
51 let proxied =
52 request
53 SocketAddress("10.0.0.2", 5000)
54 [ ("X-Forwarded-For", "1.2.3.4, 203.0.113.7")
55 , ("X-Forwarded-For", "10.0.0.3")
56 ]
57 io.println (shown (http.client_address proxied ["10.0.0.2", "10.0.0.3"]))
58 //> 203.0.113.7
59 // Every entry trusted: the left-most one.
60 io.println
61 ( shown
62 ( http.client_address
63 proxied
64 ["10.0.0.2", "10.0.0.3", "203.0.113.7", "1.2.3.4"]
65 )
66 )
67 //> 1.2.3.4
68 // A trusted proxy without X-Forwarded-For: the proxy itself.
69 io.println
70 ( shown
71 ( http.client_address
72 (request SocketAddress("10.0.0.2", 1) [])
73 ["10.0.0.2"]
74 )
75 )
76 //> 10.0.0.2
77 // Wire headers leave the pseudo-header out.
78 io.println (show (http.wire_headers proxied))
79 //> [(X-Forwarded-For, 1.2.3.4, 203.0.113.7), (X-Forwarded-For, 10.0.0.3)]
80}