-
Notifications
You must be signed in to change notification settings - Fork 1
/
http.carp
381 lines (348 loc) · 14.4 KB
/
http.carp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
(load "[email protected]:carpentry-org/[email protected]")
(load "[email protected]:carpentry-org/[email protected]")
(deftype SameSite
(Lax [])
(Strict [])
(None [])
)
(defmodule SameSite
(defn zero [] (Lax))
(implements zero SameSite.zero)
)
(doc Cookie "is a simple cookie data type. You usually shouldn’t need to build
the type yourself, instead you can [parse](#parse) it.")
(deftype Cookie [name String,
value String,
path String,
expires (Maybe Datetime),
domain (Maybe String),
secure Bool,
httponly Bool,
samesite SameSite])
(defmodule Cookie
(doc expired? "checks if a cookie is expired now.")
(defn expired? [c]
(match @(expires c)
(Maybe.Just d) (> &(Datetime.now) &d)
(Maybe.Nothing) false))
(doc parse "parses a cookie.")
(defn parse [s]
(let [splt (split-by s &[\=])]
(if (= (Array.length &splt) 2)
(Result.Success
(init
(trim (Array.unsafe-first &splt))
(trim (Array.unsafe-nth &splt 1)) @"/"
(Maybe.Nothing) (Maybe.Nothing) false false (zero)))
(Result.Error @"cookie malformed: expected key=value pair"))))
(doc parse-many "parses multiple cookies.")
(defn parse-many [s]
(Array.reduce
&(fn [a s]
(match a
(Result.Error err) (Result.Error err)
(Result.Success arr)
(match (parse s)
(Result.Error err) (Result.Error err)
(Result.Success c) (Result.Success (Array.push-back arr c)))))
(Result.Success []) &(split-by s &[\;])))
(doc kv "makes a `name=value` pair from a cookie.")
(defn kv [c] (fmt "%s=%s" (name c) (value c)))
(doc set "makes a proper set cookie string from a cookie.")
(defn set [c]
(let-do [s (fmt "%s; Path=%s" &(kv c) (path c))]
(match @(expires c)
(Maybe.Nothing) ()
(Maybe.Just xp)
(set! s (fmt "%s; Expires=%s" &s &(Datetime.strftime &xp "%a, %d %b %Y %H:%M:%S GMT"))))
(match @(domain c)
(Maybe.Nothing) ()
(Maybe.Just d) (set! s (fmt "%s; Domain=%s" &s &d)))
(when @(secure c) (set! s (fmt "%s; Secure" &s)))
(when @(httponly c) (set! s (fmt "%s; HttpOnly" &s)))
(match @(samesite c)
(SameSite.Lax) (set! s (fmt "%s; SameSite=Lax" &s))
(SameSite.Strict) (set! s (fmt "%s; SameSite=Strict" &s))
(SameSite.None) (set! s (fmt "%s; SameSite=None" &s)))
s))
(private parse-set-prop)
(hidden parse-set-prop)
(defn parse-set-prop [a p]
(match a
(Result.Error err) (Result.Error err)
(Result.Success c)
(let [prop &(trim p)
splt &(split-by prop &[\=])
l<2 (< (Array.length splt) 2)]
(cond
(= prop "Secure") (Result.Success (set-secure c true))
(= prop "HttpOnly") (Result.Success (set-httponly c true))
(starts-with? prop "Path")
(if l<2
(Result.Error @"malformed path property in set-cookie, no value")
(Result.Success (set-path c (join "=" &(Array.suffix splt 1)))))
(starts-with? prop "Domain")
(if l<2
(Result.Error @"malformed domain property in set-cookie, no value")
(Result.Success
(set-domain c (Maybe.Just (join "=" &(Array.suffix splt 1))))))
(starts-with? prop "Expires")
(if l<2
(Result.Error @"malformed expires property in set-cookie, no value")
(Result.Error @"TODO: parse date"))
(starts-with? prop "Max-Age")
(if l<2
(Result.Error @"malformed max-age property in set-cookie, no value")
(let [mi (Int.from-string &(join "=" &(Array.suffix splt 1)))]
(match mi
(Maybe.Nothing)
(Result.Error @"malformed max-age value in set-cookie")
(Maybe.Just i)
(Result.Success
(set-expires c
(Maybe.Just (Datetime.add-seconds &(Datetime.now) i)))))))
(starts-with? prop "SameSite")
(if l<2
(Result.Error @"malformed samesite property in set-cookie, no value")
(let [s (join "=" &(Array.suffix splt 1))]
(case &s
"Lax" (Result.Success (set-samesite c (SameSite.Lax)))
"Strict" (Result.Success (set-samesite c (SameSite.Strict)))
"None" (Result.Success (set-samesite c (SameSite.None)))
(Result.Error
(fmt "malformed samesite property in set-cookie, unknown value: %s" &s)))))
(Result.Error (fmt "Unknown set-cookie property: %s" prop))))))
(doc parse-set "parses a `Set-Cookie` form.")
(defn parse-set [s]
(let [splt (split-by s &[\;])]
(Array.reduce &parse-set-prop (parse (Array.unsafe-first &splt))
&(Array.suffix &splt 1))))
)
(doc Request "is a request data type. It holds the `verb` of the request, the
`version`, the `uri`, the `cookies`, the `headers`, and the `body`.")
(deftype Request [verb String,
version String,
uri URI,
cookies (Array Cookie),
headers (Map String (Array String)),
body String])
(defmodule Request
(doc ignore-body? "checks whether the body of the request should be ignored.")
(defn ignore-body? [r] (= (verb r) "HEAD"))
(private str-headers)
(hidden str-headers)
(defn str-headers [r]
(Map.kv-reduce
&(fn [acc k v]
(fmt "%s\r\n%s"
&acc
&(join "\r\n" &(Array.copy-map &(fn [x] (fmt "%s: %s" k x)) v))
))
@""
(headers r)))
(private str-cookies)
(hidden str-cookies)
(defn str-cookies [r]
(if (empty? (cookies r))
@""
(fmt "Cookie: %s" &(join ";" &(Array.copy-map &Cookie.kv (cookies r))))))
(doc str "stringifies the request. It should be stringified exactly as it
looks on the wire.")
(defn str [r]
(fmt "%s %s %s%s\r\n%s\r\n\r\n%s"
(verb r)
&(str (uri r))
(version r)
&(str-headers r)
&(str-cookies r)
(body r)))
(implements str Request.str)
(doc request "builds a HTTP `1.1` request.")
(defn request [verb uri cookies headers body]
(init verb @"HTTP/1.1" uri cookies headers body))
(doc get "builds a HTTP GET request (version `1.1`).")
(defn get [uri cookies headers body]
(request @"GET" uri cookies headers body))
(doc post "builds a HTTP POST request (version `1.1`).")
(defn post [uri cookies headers body]
(request @"POST" uri cookies headers body))
(doc put "builds a HTTP PUT request (version `1.1`).")
(defn put [uri cookies headers body]
(request @"PUT" uri cookies headers body))
(doc del "builds a HTTP DELETE request (version `1.1`).")
(defn del [uri cookies headers body]
(request @"DELETE" uri cookies headers body))
(doc patch "builds a HTTP PATCH request (version `1.1`).")
(defn patch [uri cookies headers body]
(request @"PATCH" uri cookies headers body))
(doc parse "parses a HTTP request from a string `txt`.
Returns an `(Error String)` holding the error message if it fails, otherwise
it will return a `(Success Request)`.")
(defn parse [txt]
(let [ls &(Pattern.split #"\r\n" txt)
fst (Array.first ls)]
(match fst
(Maybe.Nothing) (Result.Error @"Malformed request: empty")
(Maybe.Just s)
(let [splt (words &s)]
(if (/= (Array.length &splt) 3)
(Result.Error (fmt "Malformed request: found first line '%s'" &s))
(let-do [headers {}
cookies []
body @""
failed @""]
(for [i 1 (Array.length ls)]
(let [l (Array.unsafe-nth ls i)]
(if (= l "")
(do
(when (> (Array.length ls) (Int.inc i))
(set! body
(join "\n" &(Array.suffix ls (Int.inc i)))))
(break))
(let [splt (split-by l &[\:])]
(if (< (Array.length &splt) 2)
(do
(set! failed @l)
(break))
(let [k (Array.unsafe-nth &splt 0)
v &(trim &(join ":" &(Array.suffix &splt 1)))]
(if (= k "Cookie")
(match (Cookie.parse-many v)
(Result.Error err)
(do
(set! failed err)
(break))
(Result.Success arr)
(set! cookies (Array.concat &[cookies arr])))
(set! headers
(Map.update-with-default
headers
k
&(fn [h] (Array.push-back h @v))
[])))))))))
(if (/= &failed "")
(Result.Error (fmt "Malformed request: found header '%s'" &failed))
(let [uri (URI.parse (Array.unsafe-nth &splt 1))]
(match uri
(Result.Success uri)
(Result.Success
(init
@(Array.unsafe-nth &splt 0)
@(Array.unsafe-nth &splt 2)
uri
cookies
headers
body))
(Result.Error err)
(Result.Error
(fmt "Malformed request: uri decoding error: '%s'" &err)))))))))))
)
(doc Response "is a response data type. It holds the `code` of the request, the
`version`, the `message`, the `cookies`, the `headers`, and the `body`.")
(deftype Response [code Int,
message String,
version String,
cookies (Array Cookie),
headers (Map String (Array String)),
body String])
(defmodule Response
(private str-headers)
(hidden str-headers)
(defn str-headers [r]
(Map.kv-reduce
&(fn [acc k v]
(fmt "%s\r\n%s"
&acc
&(join "\r\n" &(Array.copy-map &(fn [x] (fmt "%s: %s" k x)) v))
))
@""
(headers r)))
(private str-cookies)
(hidden str-cookies)
(defn str-cookies [r]
(Array.reduce
&(fn [acc c]
(fmt "%s\r\nSet-Cookie: %s"
&acc
&(Cookie.set c)))
@""
(cookies r)))
(doc str "stringifies the request. It should be stringified exactly as it
looks on the wire.")
(defn str [r]
(fmt "%s %d %s%s%s\r\n\r\n%s"
(version r)
@(code r)
(message r)
&(str-headers r)
&(str-cookies r)
(body r)))
(implements str Response.str)
(doc ok? "checks whether the status code is less than 400.")
(defn ok? [r] (< @(code r) 400))
(doc client-error? "checks whether the status code is between 400 and 500.")
(defn client-error? [r] (let [c @(code r)] (and (<= 400 c) (< c 500))))
(doc server-error? "checks whether the status code is between 500 and 600.")
(defn server-error? [r] (let [c @(code r)] (and (<= 500 c) (< c 600))))
(doc parse "parses a HTTP response from a string `txt`.
Returns a `(Error String)` holding the error message if it fails, otherwise
it will return a `(Success Response)`.")
(defn parse [txt]
(let [ls &(Pattern.split #"\r\n" txt)
fst (Array.first ls)]
(match fst
(Maybe.Nothing) (Result.Error @"Malformed response: empty")
(Maybe.Just s)
(let [splt (words &s)]
(if (< (Array.length &splt) 3)
(Result.Error (fmt "Malformed response: found first line '%s'" &s))
(let-do [headers {}
cookies []
body @""
failed @""]
(for [i 1 (Array.length ls)]
(let [l (Array.unsafe-nth ls i)]
(if (= l "")
(do
(when (> (Array.length ls) (Int.inc i))
(set! body
(join "\n" &(Array.suffix ls (Int.inc i)))))
(break))
(let [splt (split-by l &[\:])]
(if (< (Array.length &splt) 2)
(do
(set! failed @l)
(break))
(let [k (Array.unsafe-nth &splt 0)
v &(trim &(join ":" &(Array.suffix &splt 1)))]
(if (= k "Set-Cookie")
(match (Cookie.parse-set v)
(Result.Error err)
(do
(set! failed err)
(break))
(Result.Success c) (Array.push-back! &cookies c))
(set! headers
(Map.update-with-default
headers
k
&(fn [h] (Array.push-back h @v))
[])))))))))
(if (/= &failed "")
(Result.Error (fmt "Malformed response: found header '%s'" &failed))
(let [msc (Int.from-string (Array.unsafe-nth &splt 1))]
(match msc
(Maybe.Just status-code)
(Result.Success
(init
status-code
(join " " &(Array.suffix &splt 2))
@(Array.unsafe-nth &splt 0)
cookies
headers
body))
(Maybe.Nothing)
(Result.Error
(fmt "Malformed request: status code decoding error: '%s'"
(Array.unsafe-nth &splt 1))))))))))))
)