http.ml 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. (*
  2. * _ _ ____ _
  3. * _| || |_/ ___| ___ _ __ _ __ ___ | |
  4. * |_ .. _\___ \ / _ \ '_ \| '_ \ / _ \| |
  5. * |_ _|___) | __/ |_) | |_) | (_) |_|
  6. * |_||_| |____/ \___| .__/| .__/ \___/(_)
  7. * |_| |_|
  8. *
  9. * Personal Social Web.
  10. *
  11. * Copyright (C) The #Seppo contributors. All rights reserved.
  12. *
  13. * This program is free software: you can redistribute it and/or modify
  14. * it under the terms of the GNU General Public License as published by
  15. * the Free Software Foundation, either version 3 of the License, or
  16. * (at your option) any later version.
  17. *
  18. * This program is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. * GNU General Public License for more details.
  22. *
  23. * You should have received a copy of the GNU General Public License
  24. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  25. *)
  26. let ( let* ) = Result.bind
  27. let ( let*% ) r f : ('b,'e) Lwt_result.t =
  28. (* https://discuss.ocaml.org/t/idiomatic-let-result-bind-and-lwt-bind/12554?u=mro *)
  29. match r with
  30. | Error _ as e -> Lwt.return e (* similar to Result.map_error but without unwrapping *)
  31. | Ok v -> f v
  32. let pp_status ppf status = Format.pp_print_string ppf (status |> Cohttp.Code.string_of_status)
  33. let reso ~base url =
  34. Uri.resolve "https" base url
  35. (** subtract the base from path, so as Uri.resolve "" base x = path *)
  36. let relpa base path =
  37. let rec f = function
  38. | _ :: [], p -> p
  39. | bh :: bt, ph :: pt when String.equal bh ph -> f (bt,pt)
  40. | _ -> []
  41. in
  42. let is_sep = Astring.Char.equal '/' in
  43. let ba = base |> Astring.String.fields ~is_sep
  44. and pa = path |> Astring.String.fields ~is_sep in
  45. f (ba,pa) |> Astring.String.concat ~sep:"/"
  46. let abs_to_rel ~base url =
  47. match url |> Uri.host with
  48. | None -> url
  49. | Some _ as ho ->
  50. let url = if Option.equal String.equal (Uri.host base) ho
  51. then Uri.with_host url None
  52. else url in
  53. let url = if Option.equal String.equal (Uri.scheme base) (Uri.scheme url)
  54. then Uri.with_scheme url None
  55. else url in
  56. let url = if Option.equal Int.equal (Uri.port base) (Uri.port url)
  57. then Uri.with_port url None
  58. else url in
  59. let url = Uri.with_path url (relpa (Uri.path base) (Uri.path url)) in
  60. url
  61. (* https://tools.ietf.org/html/rfc2616/#section-3.3.1
  62. https://tools.ietf.org/html/rfc1123#page-55
  63. https://tools.ietf.org/html/rfc822#section-5.1
  64. *)
  65. let to_rfc1123 (time : Ptime.t) =
  66. (* MIT License, Copyright 2021 Anton Bachin
  67. https://github.com/aantron/dream/blob/master/src/pure/formats.ml#L51 *)
  68. let weekday =
  69. match Ptime.weekday time with
  70. | `Sun -> "Sun"
  71. | `Mon -> "Mon"
  72. | `Tue -> "Tue"
  73. | `Wed -> "Wed"
  74. | `Thu -> "Thu"
  75. | `Fri -> "Fri"
  76. | `Sat -> "Sat"
  77. in
  78. let (y, m, d), ((hh, mm, ss), _tz_offset_s) = Ptime.to_date_time time in
  79. let month =
  80. match m with
  81. | 1 -> "Jan"
  82. | 2 -> "Feb"
  83. | 3 -> "Mar"
  84. | 4 -> "Apr"
  85. | 5 -> "May"
  86. | 6 -> "Jun"
  87. | 7 -> "Jul"
  88. | 8 -> "Aug"
  89. | 9 -> "Sep"
  90. | 10 -> "Oct"
  91. | 11 -> "Nov"
  92. | 12 -> "Dec"
  93. | _ -> failwith "Month < 1 or > 12 not allowed"
  94. in
  95. (* [Ptime.to_date_time] docs give range 0..60 for [ss], accounting for
  96. leap seconds. However, RFC 6265 §5.1.1 states:
  97. 5. Abort these steps and fail to parse the cookie-date if:
  98. * the second-value is greater than 59.
  99. (Note that leap seconds cannot be represented in this syntax.)
  100. See https://tools.ietf.org/html/rfc6265#section-5.1.1.
  101. Even though [Ptime.to_date_time] time does not return leap seconds, in
  102. case I misunderstood the gmtime API, of system differences, or future
  103. refactoring, make sure no leap seconds creep into the output. *)
  104. Printf.sprintf "%s, %02i %s %04i %02i:%02i:%02i GMT" weekday d month y hh mm
  105. (min 59 ss)
  106. module Mime = struct
  107. module C = As2_vocab.Constants.ContentType
  108. let _app_act_json= C._app_act_json
  109. let app_jlda = C.app_jlda
  110. let app_jrd = C.app_jrd
  111. let app_atom_xml = C.app_atom_xml
  112. let app_form_url = "application/x-www-form-urlencoded"
  113. let app_json = C.app_json
  114. let img_jpeg = "image/jpeg"
  115. let text_css = "text/css; charset=utf8"
  116. let text_html = "text/html; charset=utf8"
  117. let text_plain = "text/plain; charset=utf8"
  118. let text_xml = "text/xml"
  119. let text_xsl = "text/xsl"
  120. let is_app_json m =
  121. _app_act_json |> String.equal m
  122. || app_json |> String.equal m
  123. end
  124. module H = struct
  125. type t = string * string
  126. let add' h (n, v) = Cohttp.Header.add h n v
  127. let acc_app_json = ("Accept", Mime.app_json)
  128. let acc_app_jrd = ("Accept", Mime.app_jrd)
  129. let acc_app_jlda = ("Accept", Mime.app_jlda)
  130. let agent = ("User-Agent", St.seppo_s)
  131. let content_type ct : t = ("Content-Type", ct)
  132. let ct_jlda = content_type Mime.app_jlda
  133. let ct_html = content_type Mime.text_html
  134. let ct_json = content_type Mime.app_json
  135. let ct_plain = content_type Mime.text_plain
  136. let ct_xml = content_type Mime.text_xml
  137. let content_length cl:t = ("Content-Length", cl |> string_of_int)
  138. let location url : t = ("Location", url)
  139. let retry_after t : t = ("Retry-After", t |> to_rfc1123)
  140. let set_cookie v : t = ("Set-Cookie", v)
  141. let max_age _ : t = assert false (* set via webserver config *)
  142. let x_request_id u : t = ("X-Request-Id", Uuidm.to_string u)
  143. end
  144. module R = Cgi.Response
  145. (** See also https://github.com/aantron/dream/blob/master/src/pure/status.ml
  146. RFC1945 demands absolute uris https://www.rfc-editor.org/rfc/rfc1945#section-10.11 *)
  147. let s302 ?(header = []) url = Error (`Found, [ H.ct_plain; H.location url ] @ header, R.nobody)
  148. let s400' = (`Bad_request, [ H.ct_plain ], R.nobody)
  149. let s400 = Error s400'
  150. let s400x = Error (`Bad_request, [ H.ct_xml ], R.nobody)
  151. let s401 = Error (`Unauthorized, [ H.ct_plain ], R.nobody)
  152. let s403' = (`Forbidden, [ H.ct_plain ], R.nobody)
  153. let s403 = Error s403'
  154. let s404 = Error (`Not_found, [ H.ct_plain ], R.nobody)
  155. let s405 = Error (`Method_not_allowed, [ H.ct_plain ], R.nobody)
  156. let s411' = (`Length_required, [ H.ct_plain ], R.nobody)
  157. let s411 = Error s411'
  158. let s413 = Error (`Code 413, [ H.ct_plain ], R.nobody) (* Payload too large *)
  159. (* https://stackoverflow.com/a/42171674/349514 *)
  160. let s422' = (`Unprocessable_entity, [ H.ct_plain ], R.nobody)
  161. let s422 = Error s422'
  162. let s422x = Error (`Unprocessable_entity, [ H.ct_xml ], R.nobody)
  163. (* https://tools.ietf.org/html/rfc6585#section-4
  164. Retry-After https://tools.ietf.org/html/rfc2616#section-14.37
  165. HTTP-date https://tools.ietf.org/html/rfc1123
  166. https://github.com/inhabitedtype/ocaml-webmachine/blob/master/lib/rfc1123.ml
  167. *)
  168. let s429_t t = Error (`Too_many_requests, [ H.ct_plain; H.retry_after t ], ("429: Too many requests." |> R.body))
  169. let s500' = (`Internal_server_error, [ H.ct_plain ], R.nobody) (** HTTP 500 Internal Server error and empty body (camel) *)
  170. let s500 = Error s500' (** HTTP 500 Internal Server error and empty body (camel) *)
  171. let s501 = Error (`Not_implemented, [ H.ct_plain ], R.nobody)
  172. let s502' ~(body : out_channel -> unit) = (`Bad_gateway, [ H.ct_plain ], body)
  173. let s502 ~body = Error (s502' ~body)
  174. let err500 ?(error = s500') ?(level = Logs.Error) msg e =
  175. Logr.msg level (fun m -> m "%s: %s" msg e);
  176. error
  177. (** Send a clob as is and 200 Ok *)
  178. let clob_send _ ct clob =
  179. Ok (`OK, [H.content_type ct], clob |> Cgi.Response.body)
  180. (*
  181. * https://datatracker.ietf.org/doc/html/draft-cavage-http-signatures-12
  182. * see also https://github.com/Gopiandcode/http_sig_ocaml/blob/254d464c16025e189ceb20190710fe50e9bd8d2b/http_sig.ml#L50
  183. *
  184. * Another list of k-v-pairs but in idiosyncratic encoding. Different from Cookie.
  185. *)
  186. module Signature = struct
  187. (* https://datatracker.ietf.org/doc/html/rfc7230#section-3.2.6 *)
  188. module P = struct
  189. open Tyre
  190. (*
  191. let _htab = char '\t'
  192. (* https://stackoverflow.com/a/52336696/349514 *)
  193. let _vchar = pcre {|[!-~]|}
  194. let _sp = char ' '
  195. (* https://datatracker.ietf.org/doc/html/rfc7230#section-3.2.6 *)
  196. let _tchar = pcre {|[!#$%&'*+-.^_`|~0-9a-zA-Z]|}
  197. let _obs_text = pcre {|€-ÿ|} (* %x80-FF *)
  198. *)
  199. (* https://datatracker.ietf.org/doc/html/rfc7230#section-3.2.6 *)
  200. let token = pcre {|[!#$%&'*+-.^_`|~0-9a-zA-Z]+|} (* rep1 tchar *)
  201. let qdtext = pcre {|[\t !#-\[\]-~€-ÿ]|}
  202. (* htab (* HTAB *)
  203. <|> sp (* SP *)
  204. <|> char '!' (* %x21 *)
  205. <|> pcre {|[#-\[]|} (* %x23-5B *)
  206. <|> pcre {|[\]-~]|} (* %x5D-7E *)
  207. <|> obs_text
  208. *)
  209. let dquote = char '"'
  210. let quoted_pair = char '\\' *> pcre {|[\t !-~€-ÿ]|} (* (htab <|> sp <|> vchar <|> obs_text) *)
  211. let quoted_string =
  212. conv
  213. (fun x ->
  214. let buf = Buffer.create 100 in
  215. x
  216. |> Seq.fold_left (fun bu u ->
  217. (match u with
  218. | `Left ch
  219. | `Right ch -> ch)
  220. |> Buffer.add_string bu; bu) buf
  221. |> Buffer.contents)
  222. (fun x ->
  223. x
  224. |> String.to_seq
  225. |> Seq.map (fun c ->
  226. let s = Astring.String.of_char c in
  227. if c == '"' (* quote more? *)
  228. then `Right s
  229. else `Left s))
  230. (dquote *> (rep (qdtext <|> quoted_pair)) <* dquote)
  231. let ows = pcre {|[ \t]*|}
  232. let bws = ows
  233. (* https://datatracker.ietf.org/doc/html/rfc7235#section-2.1 *)
  234. let auth_param =
  235. conv
  236. (function
  237. | (t,`Left x)
  238. | (t,`Right x) -> t,x)
  239. (fun (t,s) ->
  240. (* TODO make s a token (`Left) if possible *)
  241. (t,`Right s))
  242. (token <* bws <* char '=' <* bws <&> (token <|> quoted_string))
  243. let list_auth_param =
  244. (* implement production 'credentials' at https://datatracker.ietf.org/doc/html/rfc7235#appendix-C *)
  245. let sep = bws *> char ',' <* bws in
  246. start *> separated_list ~sep auth_param <* stop
  247. (* https://gabriel.radanne.net/papers/tyre/tyre_paper.pdf#page=9 *)
  248. let list_auth_param' = compile list_auth_param
  249. end
  250. (** https://datatracker.ietf.org/doc/html/draft-cavage-http-signatures-12#section-4.1 *)
  251. let decode = Tyre.exec P.list_auth_param'
  252. (** the header value without escaping e.g. = or "" *)
  253. let encode =
  254. (*
  255. |> List.fold_left (fun init (k,v) -> Printf.sprintf {|%s="%s"|} k v :: init) []
  256. |> Astring.String.concat ~sep:"," in
  257. *)
  258. Tyre.eval P.list_auth_param
  259. (** add (request-target) iff request given *)
  260. let to_sign_string0 ~request h : string =
  261. let h = h |> Cohttp.Header.to_frames in
  262. (match request with
  263. | None -> h
  264. | Some (meth,uri) ->
  265. let s = Printf.sprintf "(request-target): %s %s"
  266. (meth |> Cohttp.Code.string_of_method |> String.lowercase_ascii)
  267. (uri |> Uri.path_and_query) in
  268. s :: h)
  269. |> Astring.String.concat ~sep:"\n"
  270. (**
  271. - key_id
  272. - pk
  273. - now *)
  274. type t_key = Uri.t * X509.Private_key.t * Ptime.t
  275. let mkey id pk t : t_key = (id,pk,t)
  276. (** build the string to sign *)
  277. let to_sign_string'
  278. (meth : Cohttp.Code.meth)
  279. (targ : Uri.t)
  280. (hdrs : (string * string) list) =
  281. let n,s = [],[] in
  282. let n,s = match hdrs |> List.assoc_opt "digest" with
  283. | None -> n,s
  284. | Some d -> "digest" :: n,("digest",d) :: s in
  285. let n = "(request-target)" :: "host" :: "date" :: n in
  286. let s = ("(request-target)",Printf.sprintf "%s %s"
  287. (meth |> Cohttp.Code.string_of_method |> Astring.String.map Astring.Char.Ascii.lowercase)
  288. (targ |> Uri.path_and_query))
  289. :: ("host",targ |> Uri.host |> Option.get)
  290. :: ("date",hdrs |> List.assoc "date")
  291. :: s in
  292. n,s
  293. let to_sign_string meth targ hdrs =
  294. let n,l = to_sign_string' meth targ hdrs in
  295. n |> Astring.String.concat ~sep:" "
  296. ,
  297. l |> Cohttp.Header.of_list
  298. |> Cohttp.Header.to_frames
  299. |> Astring.String.concat ~sep:"\n"
  300. (**
  301. HTTP signature according https://tools.ietf.org/id/draft-cavage-http-signatures-12.html#rfc.appendix.C
  302. *)
  303. module RSA_SHA256 = struct
  304. let hash = `SHA256
  305. and scheme = `RSA_PKCS1
  306. let name = "rsa-sha256"
  307. and sign = X509.Private_key.sign hash ~scheme
  308. and verify = X509.Public_key.verify hash ~scheme
  309. end
  310. (**
  311. HTTP signature according https://tools.ietf.org/id/draft-cavage-http-signatures-12.html#rfc.appendix.C
  312. *)
  313. module HS2019 = struct
  314. let hash = `SHA512
  315. and scheme = `RSA_PSS
  316. let name = "hs2019"
  317. and sign = X509.Private_key.sign hash ~scheme
  318. and verify = X509.Public_key.verify hash ~scheme
  319. end
  320. let add
  321. (priv : X509.Private_key.t)
  322. (meth : Cohttp.Code.meth)
  323. (targ : Uri.t)
  324. (hdrs : (string * string) list) =
  325. assert (hdrs |> List.assoc_opt "date" |> Option.is_some);
  326. assert (targ |> Uri.host |> Option.is_some);
  327. assert (hdrs |> List.assoc_opt "host" |> Option.is_some);
  328. assert (hdrs |> List.assoc "host" |> Astring.String.equal (targ |> Uri.host_with_default ~default:""));
  329. let n,s = to_sign_string meth targ hdrs in
  330. (* build the signature header value *)
  331. match RSA_SHA256.(name,(sign priv (`Message (s |> Cstruct.of_string) ))) with
  332. | _,(Error _ as e) -> e
  333. | alg,Ok si ->
  334. let v = [
  335. "algorithm",alg;
  336. "headers" ,n;
  337. "signature", si |> Cstruct.to_string |> Base64.encode_string;
  338. ]
  339. |> encode in
  340. Ok ( hdrs @ ["signature",v] )
  341. end
  342. (** Create headers including a signature for a POST request.
  343. https://blog.joinmastodon.org/2018/06/how-to-implement-a-basic-activitypub-server/#http-signatures
  344. https://socialhub.activitypub.rocks/t/help-needed-http-signatures/2458
  345. https://tools.ietf.org/id/draft-cavage-http-signatures-12.html
  346. HTTP signature according https://tools.ietf.org/id/draft-cavage-http-signatures-12.html#rfc.appendix.C
  347. https://www.ietf.org/archive/id/draft-ietf-httpbis-message-signatures-10.html#name-creating-a-signature
  348. Digest http://tools.ietf.org/html/rfc3230#section-4.3.2
  349. https://docs.joinmastodon.org/spec/security/#http
  350. https://w3id.org/security#publicKey
  351. https://w3id.org/security/v1
  352. NOT: https://datatracker.ietf.org/doc/draft-ietf-httpbis-message-signatures/
  353. *)
  354. let signed_headers (key_id,pk,date : Signature.t_key) dige uri =
  355. let open Cohttp in
  356. let hdr = (
  357. ("host", uri |> Uri.host |> Option.value ~default:"-") ::
  358. ("date", date |> to_rfc1123) ::
  359. match dige with
  360. | None -> []
  361. | Some dige -> ("digest", dige) :: []
  362. ) in
  363. let meth,lst = match dige with
  364. | None -> `GET, ""
  365. | Some _ -> `POST," digest"
  366. in
  367. (*
  368. let _n,tx_ = Signature.to_sign_string2 meth uri hdr in
  369. let tx_ = tx_ |> Cohttp.Header.of_list |> Cohttp.Header.to_frames |> Astring.String.concat ~sep:"\n" in
  370. assert (tx_ |> String.equal tx');
  371. *)
  372. let tx = hdr
  373. |> Cohttp.Header.of_list
  374. |> Signature.to_sign_string0 ~request:(Some (meth,uri)) in
  375. let sgna =
  376. Signature.RSA_SHA256.sign
  377. pk
  378. (`Message (Cstruct.of_string tx))
  379. |> Result.get_ok
  380. |> Cstruct.to_string
  381. |> Base64.encode_exn
  382. in
  383. ["keyId", key_id |> Uri.to_string ;
  384. "algorithm", Signature.RSA_SHA256.name ;
  385. "headers", "(request-target) host date" ^ lst ;
  386. "signature", sgna ;
  387. ]
  388. |> Signature.encode
  389. (*
  390. Printf.sprintf (* must be symmetric to Signature.decode *)
  391. "keyId=\"%s\",\
  392. algorithm=\"%s\",\
  393. headers=\"(request-target) host date%s\",\
  394. signature=\"%s\""
  395. (key_id |> Uri.to_string)
  396. algo
  397. lst
  398. (sgna |> Cstruct.to_string |> Base64.encode_exn)
  399. *)
  400. |> Header.add (hdr |> Header.of_list) "signature"
  401. (* https://github.com/mirage/ocaml-cohttp#dealing-with-timeouts *)
  402. let timeout ~seconds ~f =
  403. try%lwt
  404. Lwt.pick
  405. [
  406. Lwt.map Result.ok (f ()) ;
  407. Lwt.map (fun () -> Error "Timeout") (Lwt_unix.sleep seconds);
  408. ]
  409. with
  410. | Failure s -> Lwt.return (Error s)
  411. (* don't care about maximum redirects but rather enforce a timeout *)
  412. let get
  413. ?(key = None)
  414. ?(seconds = 5.0)
  415. ?(headers = Cohttp.Header.init())
  416. uri =
  417. let t0 = Sys.time () in
  418. let uuid = Uuidm.v `V4 in
  419. let headers = H.agent |> H.add' headers in
  420. let headers = uuid |> H.x_request_id |> H.add' headers in
  421. (* based on https://github.com/mirage/ocaml-cohttp#dealing-with-redirects *)
  422. let rec get_follow uri =
  423. let headers = match key with
  424. | None -> headers
  425. | Some key ->
  426. Cohttp.Header.(signed_headers key None uri |> to_list |> add_list headers) in
  427. let%lwt r = Cohttp_lwt_unix.Client.get ~headers uri in
  428. follow_redirect ~base:uri r
  429. and follow_redirect ~base (response, body) =
  430. let sta = response.status in
  431. Logr.debug (fun m -> m "%s.%s %a %a" "Http" "get.follow_redirect" Uuidm.pp uuid pp_status sta);
  432. match sta with
  433. | #Cohttp.Code.redirection_status ->
  434. (* should we ignore the status and just use location if present? *)
  435. ( match "location" |> Cohttp.Header.get (Cohttp.Response.headers response) with
  436. | Some loc ->
  437. Logr.debug (fun m -> m "%s.%s HTTP %a location: %s" "Http" "get.follow_redirect" pp_status sta loc);
  438. (* The unconsumed body would leak memory *)
  439. let%lwt _ = Cohttp_lwt.Body.drain_body body in
  440. loc
  441. |> Uri.of_string
  442. |> reso ~base
  443. |> get_follow
  444. | None ->
  445. Logr.warn (fun m -> m "%s.%s missing location header %a" "Http" "get.follow_redirect" Uri.pp_hum base);
  446. Lwt.return (response, body) )
  447. | _ ->
  448. (* here the http header signature validation could be done.
  449. But not for now: https://seppo.social/issues/23 *)
  450. Logr.debug (fun m -> m "%s.%s %a %a" "Http" "get" Uuidm.pp uuid Cohttp.Response.pp_hum response);
  451. Lwt.return (response, body)
  452. and f () = get_follow uri in
  453. Logr.debug (fun m -> m "%s.%s %a %a" "Http" "get" Uri.pp uri Cohttp.Header.pp_hum headers);
  454. let r = timeout ~seconds ~f in
  455. Logr.info (fun m -> m "%s.%s %a dt=%.3fs localhost -> %a" "Http" "get" Uuidm.pp uuid (Sys.time() -. t0) Uri.pp uri);
  456. r
  457. let post
  458. ?(seconds = 5.0)
  459. ~headers
  460. body
  461. uri : 'a Lwt.t =
  462. let t0 = Sys.time () in
  463. let uuid = Uuidm.v `V4 in
  464. let headers = uuid |> H.x_request_id |> H.add' headers in
  465. let headers = H.agent |> H.add' headers in
  466. let headers = body |> String.length |> H.content_length |> H.add' headers in
  467. let f () = Cohttp_lwt_unix.Client.post ~body:(`String body) ~headers uri
  468. (* here the http header signature validation could be done.
  469. But no for now: https://seppo.social/issues/23 *)
  470. in
  471. let r = timeout ~seconds ~f in
  472. Logr.info (fun m -> m "%s.%s %a dt=%.3fs localhost -> %a" "Http" "post" Uuidm.pp uuid (Sys.time() -. t0) Uri.pp uri);
  473. Logr.debug (fun m -> m "%s.%s\n%s%s" "Http" "post" (headers |> Cohttp.Header.to_string) body);
  474. r
  475. let get_jsonv
  476. ?(key = None)
  477. ?(seconds = 5.0)
  478. ?(headers = [ H.acc_app_jlda ] |> Cohttp.Header.of_list)
  479. fkt
  480. uri =
  481. Logr.debug (fun m -> m "%s.%s %a" "Http" "get_jsonv" Uri.pp uri);
  482. let err fmt msg =
  483. Error (Printf.sprintf fmt msg) in
  484. let%lwt p = get ~key ~seconds ~headers uri in
  485. match p with
  486. | Error _ as e -> Lwt.return e
  487. | Ok (resp, body) ->
  488. match resp.status with
  489. | #Cohttp.Code.success_status as sta ->
  490. Logr.debug (fun m -> m "%s.%s get %a %a" "Http" "get_jsonv" Uri.pp uri pp_status sta);
  491. let%lwt body = body |> Cohttp_lwt.Body.to_string in
  492. (* doesn't validate the digest https://seppo.social/issues/23 *)
  493. (try
  494. (resp, body |> Ezjsonm.value_from_string)
  495. |> fkt
  496. with
  497. | Ezjsonm.Parse_error (_,msg) ->
  498. err "parsing json: '%s'" msg
  499. | e ->
  500. err "parsing json: '%s'" (e |> Printexc.to_string) )
  501. |> Lwt.return
  502. | sta -> err "Gateway error: %s" (sta |> Cohttp.Code.string_of_status)
  503. |> Lwt.return
  504. let err400 k =
  505. (`Bad_request, [ H.ct_plain ], ("required input missing: " ^ k) |> R.body)
  506. (** Extract one required parameter from a get query
  507. pq: typically Cgi.Request.path_and_query *)
  508. let par1 ?(err = err400) pq k0 =
  509. let* v0 = k0 |> Uri.get_query_param pq |> Option.to_result ~none:(err k0) in
  510. Ok v0
  511. (** Extract two required parameters from a get query
  512. pq: typically Cgi.Request.path_and_query *)
  513. let par2 ?(err = err400) pq (k0,k1) =
  514. let* v0 = k0 |> Uri.get_query_param pq |> Option.to_result ~none:(err k0) in
  515. let* v1 = k1 |> Uri.get_query_param pq |> Option.to_result ~none:(err k1) in
  516. Ok (v0,v1)
  517. (** run a value through a function *)
  518. let f1 ?(f = Uri.of_string) v0 =
  519. Ok (v0 |> f)
  520. (** run a tuple's values through a function *)
  521. let f2 ?(f = Uri.of_string) (v0,v1) =
  522. Ok (v0 |> f,v1 |> f)