tobogganSe connecter

packages

The Louise packages, each released on its own

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

240 lignes · 6311 octetsBrut · Historique
1/// Whether an IP address is on the public internet: what `fetch` checks
2/// every address of a host against before it connects (ADR 0079), so a
3/// URL cannot reach the machine itself, its network or its cloud's
4/// metadata service (server-side request forgery).
5///
6/// address.classify "8.8.8.8" // Ok(Public)
7/// address.classify "169.254.169.254" // Ok(Private("link-local"))
8/// address.classify "::ffff:10.0.0.1" // Ok(Private("IPv4-mapped: private"))
9/// address.classify "example.com" // Error("not an IP address")
10///
11/// Refused in IPv4: `0.0.0.0/8`, `10.0.0.0/8`, `127.0.0.0/8`,
12/// `100.64.0.0/10`, `169.254.0.0/16`, `172.16.0.0/12`, `192.168.0.0/16`
13/// and everything from `224.0.0.0` up (multicast, reserved, broadcast).
14/// In IPv6: `::`, `::1`, `fe80::/10`, `fec0::/10`, `fc00::/7`,
15/// `ff00::/8` and the rest of `::/96` (IPv4-compatible). An IPv4-mapped
16/// address (`::ffff:a.b.c.d`) and a NAT64 one (`64:ff9b::/96`) are judged
17/// by the IPv4 address they hold.
18///
19/// Only the text `net.resolve` gives is read: dotted decimal without
20/// leading zeros, and IPv6 without a zone (`%eth0`). Anything else is an
21/// `Error`, which `fetch` refuses too.
22
23import std/int
24import std/list
25import std/result
26import std/string
27
28/// Where an address is.
29@derive Eq Show Debug
30pub type Reach
31{ Public
32 /// Not on the public internet; `reason` names the range.
33, Private(reason: String)
34}
35
36/// Where `ip` is, or why it is not an IP address.
37pub fn classify :: ip: String -> Result<Reach, String>
38{
39 if string.contains ip ":"
40 {
41 ipv6 ip |> result.map v6_reach
42 }
43 else
44 {
45 ipv4 ip |> result.map v4_reach
46 }
47}
48
49/// Whether `ip` is an IP address on the public internet.
50pub fn is_public :: ip: String -> Bool
51{
52 classify ip == Ok(Public)
53}
54
55// ---- IPv4 ----------------------------------------------------------------------
56
57/// The four bytes of a dotted-decimal address.
58fn ipv4 :: text: String -> Result<List<Int>, String>
59{
60 match string.split text "."
61 { [a, b, c, d] -> result.all (list.map [a, b, c, d] octet)
62 , _ -> Error("not an IP address: {text}")
63 }
64}
65
66fn octet :: text: String -> Result<Int, String>
67{
68 let digits = string.byte_length text
69 let leading_zero = digits > 1 && string.starts_with text "0"
70 match string.to_int text
71 { Ok
72 ( n
73 ) if digits <= 3 && !leading_zero && n >= 0 && n <= 255
74 && all_digits text -> Ok(n)
75 , _ -> Error("not an IPv4 byte: {text}")
76 }
77}
78
79fn all_digits :: text: String -> Bool
80{
81 list.all (string.chars text) fn c { string.contains "0123456789" c }
82}
83
84fn v4_reach :: bytes: List<Int> -> Reach
85{
86 match bytes
87 { [0, _, _, _] -> Private("this network")
88 , [10, _, _, _] -> Private("private")
89 , [127, _, _, _] -> Private("loopback")
90 , [169, 254, _, _] -> Private("link-local")
91 , [192, 168, _, _] -> Private("private")
92 , [100, b, _, _] if b >= 64 && b <= 127 ->
93 Private("shared (carrier-grade NAT)")
94 , [172, b, _, _] if b >= 16 && b <= 31 -> Private("private")
95 , [a, _, _, _] if a >= 224 -> Private("multicast or reserved")
96 , _ -> Public
97 }
98}
99
100// ---- IPv6 ----------------------------------------------------------------------
101
102/// The eight 16-bit groups of an IPv6 address.
103fn ipv6 :: text: String -> Result<List<Int>, String>
104{
105 match string.split text "::"
106 { [whole] -> groups whole True |> result.try fn g { exactly 8 g text }
107 , [left, right] ->
108 {
109 use l <- result.try (groups left False)
110 use r <- result.try (groups right True)
111 let missing = 8 - list.length l - list.length r
112 if missing < 1
113 {
114 Error("not an IPv6 address: {text}")
115 }
116 else
117 {
118 Ok( list.append
119 l
120 (list.append (list.map (list.range 1 missing) fn _ { 0 }) r)
121 )
122 }
123 }
124 , _ -> Error("not an IPv6 address: {text}")
125 }
126}
127
128fn exactly :: n: Int g: List<Int> text: String -> Result<List<Int>, String>
129{
130 if list.length g == n
131 {
132 Ok(g)
133 }
134 else
135 {
136 Error("not an IPv6 address: {text}")
137 }
138}
139
140/// The groups of one side of `::`. At the end of the address (`at_end`),
141/// the last may be an IPv4 address: two groups.
142fn groups :: text: String at_end: Bool -> Result<List<Int>, String>
143{
144 if text == ""
145 {
146 Ok([])
147 }
148 else
149 {
150 groups_of (string.split text ":") at_end
151 }
152}
153
154fn groups_of :: parts: List<String> at_end: Bool -> Result<List<Int>, String>
155{
156 match parts
157 { [] -> Ok([])
158 , [last] if at_end && string.contains last "." ->
159 {
160 use b <- result.try (ipv4 last)
161 match b
162 { [a, b2, c, d] -> Ok([a * 256 + b2, c * 256 + d])
163 , _ -> Error("not an IPv4 address: {last}")
164 }
165 }
166 , [part, ..rest] ->
167 {
168 use g <- result.try (hex_group part)
169 use more <- result.try (groups_of rest at_end)
170 Ok([g, ..more])
171 }
172 }
173}
174
175fn hex_group :: text: String -> Result<Int, String>
176{
177 let digits = string.chars (string.to_lower text)
178 if digits == [] || list.length digits > 4
179 {
180 Error("not an IPv6 group: {text}")
181 }
182 else
183 {
184 list.fold
185 digits
186 Ok(0)
187 fn acc d
188 {
189 use n <- result.try acc
190 match string.find "0123456789abcdef" d
191 { Some(v) -> Ok(n * 16 + v)
192 , None -> Error("not an IPv6 group: {text}")
193 }
194 }
195 }
196}
197
198fn v6_reach :: g: List<Int> -> Reach
199{
200 match g
201 { [0, 0, 0, 0, 0, 0, 0, 0] -> Private("unspecified")
202 , [0, 0, 0, 0, 0, 0, 0, 1] -> Private("loopback")
203 , [0, 0, 0, 0, 0, 0xffff, hi, lo] -> embedded "IPv4-mapped" hi lo
204 , [0, 0, 0, 0, 0, 0, _, _] -> Private("IPv4-compatible")
205 , [0x64, 0xff9b, 0, 0, 0, 0, hi, lo] -> embedded "NAT64" hi lo
206 , [first, ..] -> v6_prefix first
207 , [] -> Private("unspecified")
208 }
209}
210
211fn v6_prefix :: first: Int -> Reach
212{
213 if int.and first 0xffc0 == 0xfe80
214 {
215 Private("link-local")
216 }
217 else if int.and first 0xffc0 == 0xfec0
218 {
219 Private("site-local")
220 }
221 else if int.and first 0xfe00 == 0xfc00
222 {
223 Private("unique local")
224 }
225 else if int.and first 0xff00 == 0xff00
226 {
227 Private("multicast")
228 }
229 else
230 {
231 Public
232 }
233}
234
235/// The reach of the IPv4 address in the last two groups.
236fn embedded :: kind: String hi: Int lo: Int -> Reach
237{
238 match v4_reach [hi / 256, hi % 256, lo / 256, lo % 256]
239 { Public -> Public, Private(reason) -> Private("{kind}: {reason}") }
240}