Source file client.ml
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
open Monads
open Util
module Connection_info = Connection.Connection_info
module Version = Httpaf.Version
let src = Logs.Src.create "piaf.client" ~doc:"Piaf Client module"
module Log = (val Logs.src_log src : Logs.LOG)
type t =
{ mutable conn : Connection.t
; mutable conn_info : Connection_info.t
; mutable persistent : bool
; mutable uri : Uri.t
; config : Config.t
}
let create_http_connection ~config fd =
let (module Http), version =
match
( config.Config.http2_prior_knowledge
, config.max_http_version
, config.h2c_upgrade )
with
| true, _, _ ->
(module Http2.HTTP : Http_intf.HTTP), Versions.HTTP.v2_0
| false, { Versions.HTTP.major = 2; _ }, true ->
(module Http1.HTTP : Http_intf.HTTP), Versions.HTTP.v1_1
| false, _, _ ->
let version =
if Versions.HTTP.(compare config.max_http_version v2_0) >= 0 then
Versions.HTTP.v1_1
else
config.max_http_version
in
(module Http1.HTTP : Http_intf.HTTP), version
in
Http_impl.create_connection (module Http) ~config ~version fd
let create_https_connection ~config ~conn_info fd =
let { Connection_info.host; _ } = conn_info in
let alpn_protocols =
Versions.ALPN.protocols_of_version config.Config.max_http_version
in
let open Lwt_result.Syntax in
let* ssl_client = Openssl.connect ~config ~hostname:host ~alpn_protocols fd in
match Lwt_ssl.ssl_socket ssl_client with
| None ->
failwith "handshake not established?"
| Some ssl_socket ->
let (module Https), version =
match Ssl.get_negotiated_alpn_protocol ssl_socket with
| None ->
Log.warn (fun m ->
let protos =
String.concat
", "
(List.map
(fun proto -> Format.asprintf "%S" proto)
alpn_protocols)
in
m "ALPN: Failed to negotiate requested protocols (%s)" protos);
let impl, version =
if config.http2_prior_knowledge then
(module Http2.HTTPS : Http_intf.HTTPS), Versions.HTTP.v2_0
else
( (module Http1.HTTPS : Http_intf.HTTPS)
, if Versions.HTTP.(compare config.max_http_version v2_0) >= 0 then
Versions.HTTP.v1_1
else
config.max_http_version )
in
Log.info (fun m -> m "Defaulting to %a" Versions.HTTP.pp_hum version);
impl, version
| Some negotiated_proto ->
Log.info (fun m -> m "ALPN: server agreed to use %s" negotiated_proto);
(match Versions.ALPN.of_string negotiated_proto with
| Some HTTP_1_0 ->
(module Http1.HTTPS : Http_intf.HTTPS), Versions.HTTP.v1_0
| Some HTTP_1_1 ->
(module Http1.HTTPS : Http_intf.HTTPS), Versions.HTTP.v1_1
| Some HTTP_2 ->
(module Http2.HTTPS : Http_intf.HTTPS), Versions.HTTP.v2_0
| None ->
assert false)
in
Http_impl.create_connection (module Https) ~config ~version ssl_client
let close_connection ~conn_info fd =
Log.info (fun m ->
m "Closing connection to %a" Connection_info.pp_hum conn_info);
Lwt_unix.close fd
let connect ~config ~conn_info fd =
let { Connection_info.addresses; _ } = conn_info in
let address = List.hd addresses in
Lwt.catch
(fun () ->
Log.debug (fun m ->
m "Trying connection to %a" Connection_info.pp_hum conn_info);
Lwt_unix.with_timeout config.Config.connect_timeout (fun () ->
Lwt_result.ok (Lwt_unix.connect fd address)))
(function
| Lwt_unix.Timeout ->
let msg =
Format.asprintf
"Connection timed out after %.0f milliseconds"
(config.connect_timeout *. 1000.)
in
Logs.err (fun m -> m "%s" msg);
Lwt_result.fail (`Connect_error msg)
| Unix.Unix_error (ECONNREFUSED, _, _) ->
Lwt_result.fail
(`Connect_error
(Format.asprintf
"Failed connecting to %a: connection refused"
Connection_info.pp_hum
conn_info))
| exn ->
Lwt_result.fail
(`Connect_error
(Format.asprintf
"FIXME: unhandled connection error (%s)"
(Printexc.to_string exn))))
let make_impl ~config ~conn_info fd =
let open Lwt_result.Syntax in
let* () = connect ~config ~conn_info fd in
Log.info (fun m -> m "Connected to %a" Connection_info.pp_hum conn_info);
let open Lwt.Syntax in
let* impl =
match conn_info.scheme with
| Scheme.HTTP ->
create_http_connection ~config fd
| HTTPS ->
create_https_connection ~config ~conn_info fd
in
match impl with
| Ok _ ->
Lwt.return impl
| Error _ ->
let open Lwt.Syntax in
let+ () = close_connection ~conn_info fd in
impl
let open_connection ~config conn_info =
let fd = Lwt_unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in
if config.Config.tcp_nodelay then (
Lwt_unix.setsockopt fd Lwt_unix.TCP_NODELAY true;
Logs.debug (fun m -> m "TCP_NODELAY set"));
make_impl ~config ~conn_info fd
let change_connection t conn_info =
let open Lwt_result.Syntax in
let+ conn' = open_connection ~config:t.config conn_info in
t.conn <- conn';
t.conn_info <- conn_info
let shutdown_conn ~conn_info (Connection.Conn { impl; handle; _ }) =
Log.info (fun m ->
m
"Tearing down %s connection to %a"
(String.uppercase_ascii
(Scheme.to_string conn_info.Connection_info.scheme))
Connection_info.pp_hum
conn_info);
Http_impl.shutdown (module (val impl)) handle
let drain_available_body_bytes_and_shutdown ~conn_info conn response_body =
let open Lwt.Syntax in
Log.debug (fun m -> m "Ignoring the response body");
Lwt.async (fun () ->
let* () = Body.drain_available response_body in
shutdown_conn ~conn_info conn)
let shutdown { conn; conn_info; _ } = shutdown_conn ~conn_info conn
let reuse_or_set_up_new_connection
({ conn = Connection.Conn { impl = (module Http); handle; _ }
; conn_info
; _
} as t)
new_uri
=
let open Lwt_result.Syntax in
match Scheme.of_uri new_uri with
| Error _ as e ->
Lwt.return e
| Ok new_scheme ->
let new_conn_info =
{ conn_info with
port = Connection_info.infer_port ~scheme:new_scheme new_uri
; scheme = new_scheme
; host = Uri.host_exn new_uri
; uri = new_uri
}
in
if (not t.persistent) || Http_impl.is_closed (module Http) handle then (
Lwt.ignore_result (shutdown t);
let* new_addresses =
Connection.resolve_host ~port:new_conn_info.port new_conn_info.host
in
let new_conn_info = { new_conn_info with addresses = new_addresses } in
let+ () = change_connection t new_conn_info in
false)
else if Connection_info.equal_without_resolving conn_info new_conn_info then (
Log.debug (fun m ->
m "Reusing the same connection as the host / port didn't change");
t.conn_info <- new_conn_info;
Lwt_result.return true)
else
let* new_addresses =
Connection.resolve_host ~port:new_conn_info.port new_conn_info.host
in
let new_conn_info = { new_conn_info with addresses = new_addresses } in
if Connection_info.equal conn_info new_conn_info then (
Log.debug (fun m ->
m "Reusing the same connection as the remote address didn't change");
t.conn_info <- new_conn_info;
Lwt_result.return true)
else
let+ () = change_connection t new_conn_info in
false
type request_info =
{ remaining_redirects : int
; headers : (string * string) list
; request : Request.t
; meth : H2.Method.t
; target : string
; is_h2c_upgrade : bool
}
let rec return_response
({ conn = Connection.Conn { impl = (module Http); runtime; _ }
; conn_info
; config
; _
} as t)
({ request; _ } as request_info)
({ Response.status; ; version; body } as response)
=
let { Connection_info.scheme; _ } = conn_info in
match request_info.is_h2c_upgrade, scheme, version, status, config with
| ( true
, Scheme.HTTP
, { Versions.HTTP.major = 1; minor = 1 }
, `Switching_protocols
, { Config.h2c_upgrade = true
; max_http_version = { Versions.HTTP.major = 2; minor = 0 }
; http2_prior_knowledge = false
; _
} ) ->
(match
Headers.(
get headers Well_known.connection, get headers Well_known.upgrade)
with
| Some ("Upgrade" | "upgrade"), Some "h2c" ->
Log.debug (fun m -> m "Received 101, server accepted HTTP/2 upgrade");
let (module Http2) = (module Http2.HTTP : Http_intf.HTTP2) in
let open Lwt_result.Syntax in
let* () = Body.drain body in
let* h2_conn, response =
(Http_impl.create_h2c_connection ~config ~http_request:request runtime
:> (Connection.t * Response.t, Error.t) Lwt_result.t)
in
t.conn <- h2_conn;
return_response t request_info response
| _ ->
Lwt_result.return response)
| _ ->
Lwt_result.return response
let is_h2c_upgrade ~config ~version ~scheme =
match
( config.Config.http2_prior_knowledge
, version
, config.max_http_version
, config.h2c_upgrade
, scheme )
with
| false, cur_version, max_version, true, Scheme.HTTP ->
Versions.HTTP.(equal max_version v2_0 && equal cur_version v1_1)
| _ ->
false
let make_request_info
{ conn = Connection.Conn { version; _ }; conn_info; config; _ }
?(remaining_redirects = config.max_redirects)
~meth
~
~body
target
=
let { Connection_info.host; scheme; _ } = conn_info in
let is_h2c_upgrade = is_h2c_upgrade ~config ~version ~scheme in
let h2_settings = H2.Settings.to_base64 (Config.to_http2_settings config) in
let =
let =
let open Headers in
if is_h2c_upgrade then
(Well_known.connection, "Upgrade, HTTP2-Settings")
:: (Well_known.upgrade, "h2c")
:: ("HTTP2-Settings", Stdlib.Result.get_ok h2_settings)
:: headers
else
headers
in
Headers.canonicalize_headers
~version
~host
~body_length:body.Body.length
headers
in
let request =
Request.create
~meth
~version
~scheme
~headers:canonical_headers
~body
target
in
{ remaining_redirects; headers; request; meth; target; is_h2c_upgrade }
let rec send_request_and_handle_response
({ conn; conn_info; uri; config; _ } as t)
~body
({ remaining_redirects; request; ; meth; _ } as request_info)
=
let open Lwt_result.Syntax in
let* response =
(Http_impl.send_request conn ~body request
:> (Response.t, Error.t) Lwt_result.t)
in
if t.persistent then
t.persistent <- Response.persistent_connection response;
match
( H2.Status.is_redirection response.status
, config.follow_redirects
, remaining_redirects
, Headers.(get response.headers Well_known.location) )
with
| true, true, 0, _ ->
let msg =
Format.asprintf "Maximum (%d) redirects followed" config.max_redirects
in
Log.err (fun m -> m "%s" msg);
Lwt_result.fail (`Connect_error msg)
| true, true, _, Some location ->
let { Connection_info.scheme; _ } = conn_info in
let new_uri = Uri.parse_with_base_uri ~scheme ~uri location in
let* did_reuse =
(reuse_or_set_up_new_connection t new_uri :> (bool, Error.t) Lwt_result.t)
in
if did_reuse then
Lwt.ignore_result (Body.drain response.body)
else
drain_available_body_bytes_and_shutdown ~conn_info conn response.body;
if Status.is_permanent_redirection response.status then t.uri <- new_uri;
let target = Uri.path_and_query new_uri in
let meth' =
match meth, response.status with
| `POST, (`Found | `Moved_permanently) ->
`GET
| _ ->
meth
in
let request_info' =
make_request_info
t
~remaining_redirects:(remaining_redirects - 1)
~meth:meth'
~headers
~body
target
in
send_request_and_handle_response t ~body request_info'
| false, _, _, _ | _, false, _, _ | true, true, _, None ->
return_response t request_info response
let create ?(config = Config.default) uri =
let open Lwt_result.Syntax in
let* conn_info = Connection_info.of_uri uri in
let+ conn =
(open_connection ~config conn_info :> (Connection.t, Error.t) Lwt_result.t)
in
{ conn; conn_info; persistent = true; uri; config }
let call t ~meth ?( = []) ?(body = Body.empty) target =
let open Lwt_result.Syntax in
let (Connection.Conn { impl = (module Http); handle; _ }) = t.conn in
let* (_did_reuse : bool) =
if t.config.follow_redirects || Http_impl.is_closed (module Http) handle
then
(reuse_or_set_up_new_connection t t.uri :> (bool, Error.t) Lwt_result.t)
else
Lwt_result.return true
in
let = t.config.default_headers @ headers in
let request_info = make_request_info t ~meth ~headers ~body target in
t.persistent <- Request.persistent_connection request_info.request;
send_request_and_handle_response t ~body request_info
let request t ? ?body ~meth target = call t ?headers ?body ~meth target
let head t ? target = call t ?headers ~meth:`HEAD target
let get t ? target = call t ?headers ~meth:`GET target
let post t ? ?body target = call t ?headers ?body ~meth:`POST target
let put t ? ?body target = call t ?headers ?body ~meth:`PUT target
let patch t ? ?body target =
call t ?headers ?body ~meth:(`Other "PATCH") target
let delete t ? ?body target = call t ?headers ?body ~meth:`DELETE target
module Oneshot = struct
let call
?(config = Config.default) ?( = []) ?(body = Body.empty) ~meth uri
=
let open Lwt_result.Syntax in
let* t = create ~config uri in
let target = Uri.path_and_query t.uri in
let = t.config.default_headers @ headers in
let request_info = make_request_info t ~meth ~headers ~body target in
t.persistent <- Request.persistent_connection request_info.request;
let response_result =
send_request_and_handle_response t ~body request_info
in
Lwt.async (fun () ->
let open Lwt.Syntax in
let* response = response_result in
match response with
| Ok { Response.body; _ } ->
(match body.contents with
| `Empty _ | `String _ | `Bigstring _ ->
shutdown t
| `Stream stream ->
let* () = Lwt_stream.closed stream in
shutdown t)
| Error _ ->
Lwt.return_unit);
response_result
let request ?config ? ?body ~meth uri =
call ?config ?headers ?body ~meth uri
let head ?config ? uri = call ?config ~meth:`HEAD ?headers uri
let get ?config ? uri = call ?config ~meth:`GET ?headers uri
let post ?config ? ?body uri =
call ?config ?headers ?body ~meth:`POST uri
let put ?config ? ?body uri =
call ?config ?headers ?body ~meth:`PUT uri
let patch ?config ? ?body uri =
call ?config ?headers ?body ~meth:(`Other "PATCH") uri
let delete ?config ? ?body uri =
call ?config ?headers ?body ~meth:`DELETE uri
end