package_name
stringlengths
2
45
version
stringclasses
308 values
license
stringclasses
51 values
homepage
stringclasses
370 values
dev_repo
stringclasses
368 values
file_type
stringclasses
6 values
file_path
stringlengths
4
151
file_content
stringlengths
0
9.28M
uspf
0.2.0
MIT
https://github.com/mirage/uspf
git+https://github.com/mirage/uspf.git
dune
uspf-0.2.0/lib-lwt/dune
(library (name uspf_lwt) (public_name uspf-lwt) (libraries uspf dns-client-lwt lwt))
uspf
0.2.0
MIT
https://github.com/mirage/uspf
git+https://github.com/mirage/uspf.git
ml
uspf-0.2.0/lib-lwt/uspf_lwt.ml
open Lwt.Infix external reraise : exn -> 'a = "%reraise" let ( % ) f g = fun x -> f (g x) let eval : type a. dns:Dns_client_lwt.t -> a Uspf.t -> Uspf.Result.t option Lwt.t = fun ~dns t -> let rec go : type a. a Uspf.t -> a Lwt.t = function | Request (domain_name, record, fn) -> Dns_client_lwt.get_resource_record dns record domain_name >>= fun resp -> go (fn resp) | Return v -> Lwt.return v | Tries lst -> Lwt_list.iter_p (fun fn -> go (fn ())) lst | Map (x, fn) -> go x >|= fn | Choose_on c -> begin Lwt.catch (go % c.fn) @@ function | Uspf.Result result -> let none _ = Uspf.terminate result in let some = Fun.id in let fn = match result with | `None -> Option.fold ~none ~some c.none | `Neutral -> Option.fold ~none ~some c.neutral | `Fail -> Option.fold ~none ~some c.fail | `Softfail -> Option.fold ~none ~some c.softfail | `Temperror -> Option.fold ~none ~some c.temperror | `Permerror -> Option.fold ~none ~some c.permerror | `Pass m -> begin fun () -> match c.pass with Some pass -> pass m | None -> none () end in go (fn ()) | exn -> reraise exn end in let fn () = go t >>= fun _ -> Lwt.return_none in Lwt.catch fn @@ function | Uspf.Result result -> Lwt.return_some result | _exn -> Lwt.return_none let get_and_check dns ctx = eval ~dns (Uspf.get_and_check ctx) let eval : type a. dns:Dns_client_lwt.t -> a Uspf.t -> a Lwt.t = fun ~dns t -> let rec go : type a. a Uspf.t -> a Lwt.t = function | Request (domain_name, record, fn) -> Dns_client_lwt.get_resource_record dns record domain_name >>= fun resp -> go (fn resp) | Return v -> Lwt.return v | Tries _ -> assert false | Map (x, fn) -> go x >|= fn | Choose_on _ -> assert false in go t let get dns ctx = eval ~dns (Uspf.get ctx)
uspf
0.2.0
MIT
https://github.com/mirage/uspf
git+https://github.com/mirage/uspf.git
mli
uspf-0.2.0/lib-lwt/uspf_lwt.mli
(** LWT layer of uSPF. uSPF is a standalone library which requires some specialisations like the {i scheduler} and the DNS stack used to get DNS record. This module specialises specifically the scheduler with LWT. It lets the user to choose the DNS implementation {i via} a first-class module (see {!module-type:DNS}). {b NOTE}: This layer is currently incomplete and it uses mostly use to get the DNS record and do some verifications on it - but it does not actually do (and can not) the SPF check (as the Unix layer, see {!module:Uspf_unix}). *) val get_and_check : Dns_client_lwt.t -> Uspf.ctx -> Uspf.Result.t option Lwt.t val get : Dns_client_lwt.t -> Uspf.ctx -> (Uspf.Term.t, [> `Msg of string ]) result Lwt.t
uspf
0.2.0
MIT
https://github.com/mirage/uspf
git+https://github.com/mirage/uspf.git
dune
uspf-0.2.0/lib-mirage/dune
(library (name uspf_mirage) (public_name uspf-mirage) (libraries uspf lwt dns-client-mirage))
uspf
0.2.0
MIT
https://github.com/mirage/uspf
git+https://github.com/mirage/uspf.git
ml
uspf-0.2.0/lib-mirage/uspf_mirage.ml
open Lwt.Infix external reraise : exn -> 'a = "%reraise" let ( % ) f g = fun x -> f (g x) module Make (Dns_client : Dns_client_mirage.S) = struct let eval : type a. dns:Dns_client.t -> a Uspf.t -> Uspf.Result.t option Lwt.t = fun ~dns t -> let rec go : type a. a Uspf.t -> a Lwt.t = function | Request (domain_name, record, fn) -> Dns_client.get_resource_record dns record domain_name >>= fun resp -> go (fn resp) | Return v -> Lwt.return v | Tries lst -> Lwt_list.iter_p (fun fn -> go (fn ())) lst | Map (x, fn) -> go x >|= fn | Choose_on c -> begin Lwt.catch (go % c.fn) @@ function | Uspf.Result result -> let none _ = Uspf.terminate result in let some = Fun.id in let fn = match result with | `None -> Option.fold ~none ~some c.none | `Neutral -> Option.fold ~none ~some c.neutral | `Fail -> Option.fold ~none ~some c.fail | `Softfail -> Option.fold ~none ~some c.softfail | `Temperror -> Option.fold ~none ~some c.temperror | `Permerror -> Option.fold ~none ~some c.permerror | `Pass m -> begin fun () -> match c.pass with Some pass -> pass m | None -> none () end in go (fn ()) | exn -> reraise exn end in let fn () = go t >>= fun _ -> Lwt.return_none in Lwt.catch fn @@ function | Uspf.Result result -> Lwt.return_some result | _exn -> Lwt.return_none let get_and_check dns ctx = eval ~dns (Uspf.get_and_check ctx) end
uspf
0.2.0
MIT
https://github.com/mirage/uspf
git+https://github.com/mirage/uspf.git
mli
uspf-0.2.0/lib-mirage/uspf_mirage.mli
module Make (Dns_client : Dns_client_mirage.S) : sig val get_and_check : Dns_client.t -> Uspf.ctx -> Uspf.Result.t option Lwt.t end
uspf
0.2.0
MIT
https://github.com/mirage/uspf
git+https://github.com/mirage/uspf.git
dune
uspf-0.2.0/lib-unix/dune
(library (name uspf_unix) (public_name uspf.unix) (libraries unix dns-client.unix uspf))
uspf
0.2.0
MIT
https://github.com/mirage/uspf
git+https://github.com/mirage/uspf.git
ml
uspf-0.2.0/lib-unix/uspf_unix.ml
let eval : type a. dns:Dns_client_unix.t -> a Uspf.t -> Uspf.Result.t option = fun ~dns t -> let rec go : type a. a Uspf.t -> a = function | Request (domain_name, record, fn) -> let resp = Dns_client_unix.get_resource_record dns record domain_name in go (fn resp) | Return v -> v | Tries fns -> List.iter (fun fn -> go (fn ())) fns | Map (x, fn) -> fn (go x) | Choose_on c -> try go (c.fn ()) with Uspf.Result result -> let none _ = Uspf.terminate result in let some = Fun.id in let fn = match result with | `None -> Option.fold ~none ~some c.none | `Neutral -> Option.fold ~none ~some c.neutral | `Fail -> Option.fold ~none ~some c.fail | `Softfail -> Option.fold ~none ~some c.softfail | `Temperror -> Option.fold ~none ~some c.temperror | `Permerror -> Option.fold ~none ~some c.permerror | `Pass m -> begin fun () -> match c.pass with Some pass -> pass m | None -> none () end in go (fn ()) in match go t with exception Uspf.Result result -> Some result | _ -> None let get_and_check dns ctx = eval ~dns (Uspf.get_and_check ctx) let extract_received_spf ?(newline = `LF) ic = let buf = Bytes.create 0x7ff in let rec go extract = match Uspf.Extract.extract extract with | `Fields fields -> Ok fields | `Malformed _ -> Error (`Msg "Invalid email") | `Await extract -> match input ic buf 0 (Bytes.length buf) with | 0 -> go (Uspf.Extract.src extract "" 0 0) | len when newline = `CRLF -> go (Uspf.Extract.src extract (Bytes.sub_string buf 0 len) 0 len) | len -> let str = Bytes.sub_string buf 0 len in let str = String.split_on_char '\n' str in let str = String.concat "\r\n" str in let len = String.length str in go (Uspf.Extract.src extract str 0 len) in go (Uspf.Extract.extractor ())
uspf
0.2.0
MIT
https://github.com/mirage/uspf
git+https://github.com/mirage/uspf.git
mli
uspf-0.2.0/lib-unix/uspf_unix.mli
(** Unix layer of uSPF. uSPF is a standalone library which requires some specialisations like the {i scheduler} and the DNS stack used to get DNS records. This module specialises uSPF with the module [Unix] and [ocaml-dns]. {!val:check} does the SPF verification from a given {!type:Uspf.ctx} and {!val:extract_received_spf} extracts the [Received-SPF] field from a given email. For more details about uSPF and how to use it, please take a look on {!module:Uspf}. *) val get_and_check : Dns_client_unix.t -> Uspf.ctx -> Uspf.Result.t option val extract_received_spf : ?newline:[ `LF | `CRLF ] -> in_channel -> (Uspf.Extract.field list, [> `Msg of string ]) result
uspf
0.2.0
MIT
https://github.com/mirage/uspf
git+https://github.com/mirage/uspf.git
dune
uspf-0.2.0/lib/dune
(library (name uspf) (public_name uspf) (libraries colombe.emile mrmime dns logs colombe ipaddr hmap angstrom domain-name))
uspf
0.2.0
MIT
https://github.com/mirage/uspf
git+https://github.com/mirage/uspf.git
ml
uspf-0.2.0/lib/map.ml
type 'a tag = { name: string; pp: 'a Fmt.t; equal: 'a -> 'a -> bool } module Info = struct type 'a t = 'a tag = { name: string; pp: 'a Fmt.t; equal: 'a -> 'a -> bool } end include Hmap.Make (Info) let pp_local ppf = function | `String x -> Fmt.(quote string) ppf x | `Dot_string l -> Fmt.(list ~sep:(const string ".") string) ppf l let pp_path ppf { Colombe.Path.local; domain; _ } = Fmt.pf ppf "%a@%a" pp_local local Colombe.Domain.pp domain (* XXX(dinosaure): SPF does not follow RFC 5321 when we want to print * a path. It shows the path a simple mailbox. *) module K = struct let ip : Ipaddr.t key = let equal a b = Ipaddr.compare a b = 0 in let pp ppf = function | Ipaddr.V4 _ as v -> Ipaddr.pp ppf v | Ipaddr.V6 v6 -> let a, b, c, d, e, f, g, h = Ipaddr.V6.to_int16 v6 in Fmt.pf ppf "%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x" (a lsr 12) ((a lsr 8) land 0xf) ((a lsr 4) land 0xf) (a land 0xf) (b lsr 12) ((b lsr 8) land 0xf) ((b lsr 4) land 0xf) (b land 0xf) (c lsr 12) ((c lsr 8) land 0xf) ((c lsr 4) land 0xf) (c land 0xf) (d lsr 12) ((d lsr 8) land 0xf) ((d lsr 4) land 0xf) (d land 0xf) (e lsr 12) ((e lsr 8) land 0xf) ((e lsr 4) land 0xf) (e land 0xf) (f lsr 12) ((f lsr 8) land 0xf) ((f lsr 4) land 0xf) (f land 0xf) (g lsr 12) ((g lsr 8) land 0xf) ((g lsr 4) land 0xf) (g land 0xf) (h lsr 12) ((h lsr 8) land 0xf) ((h lsr 4) land 0xf) (h land 0xf) in Key.create { name= "<ip>"; pp; equal } let domain : [ `raw ] Domain_name.t key = let pp = Domain_name.pp in let equal = Domain_name.equal in Key.create { name= "<domain>"; pp; equal } let sender : [ `HELO of [ `raw ] Domain_name.t | `MAILFROM of Colombe.Path.t ] key = let pp ppf = function | `HELO v -> Domain_name.pp ppf v | `MAILFROM v -> pp_path ppf v in let equal a b = match (a, b) with | `HELO a, `HELO b -> Domain_name.equal a b | `MAILFROM a, `MAILFROM b -> Colombe.Path.equal a b | _ -> false in Key.create { name= "<sender>"; pp; equal } let local : [ `String of string | `Dot_string of string list ] key = let pp ppf = function | `String v -> Fmt.string ppf v | `Dot_string vs -> Fmt.(list ~sep:(const string ".") string) ppf vs in let equal a b = match (a, b) with | `String a, `String b -> String.equal a b | `Dot_string a, `Dot_string b -> begin try List.for_all2 String.equal a b with _ -> false end | _ -> false in Key.create { name= "local-part"; pp; equal } let domain_of_sender : Colombe.Domain.t key = let pp = Colombe.Domain.pp in let equal = Colombe.Domain.equal in Key.create { name= "domain-of-sender"; pp; equal } let v : [ `In_addr | `Ip6 ] key = let pp ppf = function | `In_addr -> Fmt.string ppf "in-addr" | `Ip6 -> Fmt.string ppf "ip6" in let equal a b = match (a, b) with | `In_addr, `In_addr -> true | `Ip6, `Ip6 -> true | _ -> false in Key.create { name= "v"; pp; equal } let helo : Colombe.Domain.t key = let pp = Colombe.Domain.pp in let equal = Colombe.Domain.equal in Key.create { name= "helo"; pp; equal } let origin : [ `HELO | `MAILFROM ] key = let pp ppf = function | `HELO -> Fmt.string ppf "HELO" | `MAILFROM -> Fmt.string ppf "MAILFROM" in let equal a b = match (a, b) with | `HELO, `HELO -> true | `MAILFROM, `MAILFROM -> true | _ -> false in Key.create { name= "origin"; pp; equal } end
uspf
0.2.0
MIT
https://github.com/mirage/uspf
git+https://github.com/mirage/uspf.git
ml
uspf-0.2.0/lib/uspf.ml
let error_msgf fmt = Fmt.kstr (fun msg -> Error (`Msg msg)) fmt let failwith_error_msg = function Ok v -> v | Error (`Msg err) -> failwith err let ( >>| ) x f = Result.map f x let ( % ) f g x = f (g x) let src = Logs.Src.create "spf" module Log = (val Logs.src_log src : Logs.LOG) type mechanism = | A of [ `raw ] Domain_name.t option * int option * int option | All | Exists of [ `raw ] Domain_name.t | Include of [ `raw ] Domain_name.t | Mx of [ `raw ] Domain_name.t option * int option * int option | Ptr of [ `raw ] Domain_name.t option | V4 of Ipaddr.V4.Prefix.t | V6 of Ipaddr.V6.Prefix.t module Result = struct type t = [ `None | `Neutral | `Pass of mechanism | `Fail | `Softfail | `Temperror | `Permerror ] let none = `None let neutral = `Neutral let pass mechanism = `Pass mechanism let fail = `Fail let softfail = `Softfail let temperror = `Temperror let permerror = `Permerror let pp ppf = function | `None -> Format.pp_print_string ppf "none" | `Neutral -> Format.pp_print_string ppf "neutral" | `Pass _ -> Format.pp_print_string ppf "pass" | `Fail -> Format.pp_print_string ppf "fail" | `Softfail -> Format.pp_print_string ppf "softfail" | `Temperror -> Format.pp_print_string ppf "temperror" | `Permerror -> Format.pp_print_string ppf "permerror" end type error = [ `Msg of string | `No_data of [ `raw ] Domain_name.t * Dns.Soa.t | `No_domain of [ `raw ] Domain_name.t * Dns.Soa.t ] type 'a response = ('a, error) result type 'a record = 'a Dns.Rr_map.key type 'a choose = { none: (unit -> 'a t) option ; neutral: (unit -> 'a t) option ; pass: (mechanism -> 'a t) option ; fail: (unit -> 'a t) option ; softfail: (unit -> 'a t) option ; temperror: (unit -> 'a t) option ; permerror: (unit -> 'a t) option ; fn: unit -> 'a t } and 'a t = | Return : 'a -> 'a t | Request : _ Domain_name.t * 'a record * ('a response -> 'b t) -> 'b t | Tries : (unit -> unit t) list -> unit t | Map : 'a t * ('a -> 'b) -> 'b t | Choose_on : 'a choose -> 'a t let ( let* ) (domain_name, record) fn = Request (domain_name, record, fn) let tries fns = Tries fns let ( let+ ) x fn = Map (x, fn) let return x = Return x exception Result of Result.t let terminate result = raise (Result result) let choose_on ?none ?neutral ?pass ?fail ?softfail ?temperror ?permerror fn = Choose_on { none; neutral; pass; fail; softfail; temperror; permerror; fn } type ctx = Map.t let empty = Map.empty let with_sender sender ctx = match sender with | `HELO (domain_name : [ `raw ] Domain_name.t) -> let domain = Colombe.Domain.Domain (Domain_name.to_strings domain_name) in let ctx = Map.add Map.K.origin `HELO ctx in let ctx = Map.add Map.K.helo domain ctx in let ctx = Map.add Map.K.domain_of_sender domain ctx in let ctx = Map.add Map.K.sender sender ctx in let ctx = Map.add Map.K.domain domain_name ctx in let ctx = Map.add Map.K.local (`Dot_string [ "postmaster" ]) ctx in (* XXX(dinosaure): see RFC 7208, 4.3, If the sender has no local-part, * substitute the string "postmaster" for the local-part. *) ctx | `MAILFROM { Colombe.Path.local; domain; _ } -> let ctx = Map.add Map.K.origin `MAILFROM ctx in let ctx = Map.add Map.K.local local ctx in let ctx = Map.add Map.K.domain_of_sender domain ctx in let ctx = Map.add Map.K.sender sender ctx in let ctx = match (domain, Map.find Map.K.domain ctx) with | Colombe.Domain.Domain vs, None -> (* XXX(dinosaure): assume that an [HELO] should be already done with * the same domain-name. *) Map.add Map.K.domain (Domain_name.of_strings_exn vs) ctx | Colombe.Domain.Domain vs, Some vs' -> let vs = Domain_name.of_strings_exn vs in if not (Domain_name.equal vs vs') then Map.add Map.K.domain vs ctx else ctx | _ -> ctx in ctx let with_ip ip ctx = match ip with | Ipaddr.V4 _ -> let ctx = Map.add Map.K.v `In_addr ctx in let ctx = Map.add Map.K.ip ip ctx in ctx | Ipaddr.V6 _ -> let ctx = Map.add Map.K.v `Ip6 ctx in let ctx = Map.add Map.K.ip ip ctx in ctx let merge ctx0 ctx1 = (* ip, domain, sender, local, domain_of_sender, v, helo, origin *) let same_or_unknown k ctx0 ctx1 = match (Map.find k ctx0, Map.find k ctx1) with | None, None | Some _, None | None, Some _ -> true | Some a, Some b -> let info = Map.Key.info k in info.Map.Info.equal a b in if same_or_unknown Map.K.ip ctx0 ctx1 && same_or_unknown Map.K.domain ctx0 ctx1 && same_or_unknown Map.K.local ctx0 ctx1 && same_or_unknown Map.K.domain_of_sender ctx0 ctx1 && same_or_unknown Map.K.v ctx0 ctx1 && same_or_unknown Map.K.helo ctx0 ctx1 && same_or_unknown Map.K.origin ctx0 ctx1 then let fn (Map.B (k, v)) ctx = Map.add k v ctx in let ctx = Map.fold fn Map.empty ctx0 in let ctx = Map.fold fn ctx ctx1 in Some ctx else None let colombe_domain_to_domain_name = function | Colombe.Domain.Domain lst -> Domain_name.of_strings lst | v -> error_msgf "Invalid domain-name: %a" Colombe.Domain.pp v let domain ctx = match ( Map.find Map.K.helo ctx , Map.find Map.K.domain_of_sender ctx , Map.find Map.K.domain ctx , Map.find Map.K.sender ctx ) with | _, _, Some v, _ | _, _, _, Some (`HELO v) -> Some v | Some v, None, None, None | _, Some v, None, None | _, _, _, Some (`MAILFROM { Colombe.Path.domain= v; _ }) -> Stdlib.Result.to_option (colombe_domain_to_domain_name v) | None, None, None, None -> None let origin ctx = Map.find Map.K.origin ctx module Macro = struct open Angstrom let is_alpha = function 'a' .. 'z' | 'A' .. 'Z' -> true | _ -> false let is_digit = function '0' .. '9' -> true | _ -> false let is_alphanum chr = is_alpha chr || is_digit chr let is_wsp = ( = ) ' ' let toplabel = take_while1 is_alpha >>= (fun a -> take_while is_alphanum >>= fun b -> return (a ^ b)) <|> ( take_while1 is_alphanum >>= fun a -> char '-' *> take_while1 (fun chr -> is_alphanum chr || chr = '-') >>= fun b -> if String.length b > 0 && b.[String.length b - 1] = '-' then fail "toplabel" else return (a ^ "-" ^ b) ) let macro_literal = let satisfy = function | '\x21' .. '\x24' | '\x26' .. '\x7e' -> true | _ -> false in take_while1 satisfy >>| fun str -> `Literal str let junk_with v = advance 1 *> return v let macro_letter = peek_char >>= function | Some (('s' | 'l' | 'o' | 'd' | 'i' | 'p' | 'h' | 'c' | 'r' | 't' | 'v') as chr) -> junk_with chr | _ -> fail "macro-letter" let transformers = take_while is_digit >>= function | "" -> option false (char 'r' *> return true) >>= fun rev -> return (None, rev) | number -> ( peek_char >>= function | Some 'r' -> junk_with (Some (int_of_string number), true) | _ -> return (Some (int_of_string number), false)) let is_delimiter = function | '.' | '-' | '+' | ',' | '/' | '_' | '=' -> true | _ -> false let macro_expand = let macro = macro_letter >>= fun letter -> transformers >>= fun transformers -> take_while is_delimiter >>= fun delimiter -> return (`Macro (letter, transformers, delimiter)) in choice [ string "%%" *> return `Macro_percent; string "%_" *> return `Macro_space ; string "%-" *> return `Macro_encoded_space ; string "%{" *> macro <* string "}" ] let macro_string = many (macro_expand <|> macro_literal) let _explain_string = many (macro_string <|> (take_while1 is_wsp >>| fun wsp -> [ `Space wsp ])) let domain_end = char '.' *> toplabel <* option '.' (char '.') let domain_spec = both macro_string (option None (domain_end >>| Option.some)) type macro = [ `Literal of string | `Macro of char * (int option * bool) * string | `Macro_encoded_space | `Macro_space | `Macro_percent ] type t = macro list * string option let pp ppf (ms, domain) = let pp_macro ppf = function | `Literal v -> Fmt.pf ppf "%s" v | `Macro (letter, (transformers, true), delimiter) -> Fmt.pf ppf "%%{%c%ar%s}" letter Fmt.(option int) transformers delimiter | `Macro (letter, (transformers, false), delimiter) -> Fmt.pf ppf "%%{%c%a%s}" letter Fmt.(option int) transformers delimiter | `Macro_encoded_space -> Fmt.pf ppf "%%-" | `Macro_space -> Fmt.pf ppf "%%_" | `Macro_percent -> Fmt.pf ppf "%%%%" in Fmt.pf ppf "%a" (Fmt.list ~sep:Fmt.nop pp_macro) ms ; match domain with Some domain -> Fmt.pf ppf ".%s" domain | None -> () let to_string = Fmt.to_to_string pp type key = Key : 'a Map.key -> key let key_of_letter = function | 'i' -> Key Map.K.ip | 's' -> Key Map.K.sender | 'l' -> Key Map.K.local | 'd' -> Key Map.K.domain | 'o' -> Key Map.K.domain_of_sender | 'v' -> Key Map.K.v | 'h' -> Key Map.K.helo | _ -> assert false let keep n lst = let rec go acc n lst = if n = 0 then acc else match lst with [] -> acc | x :: r -> go (x :: acc) (n - 1) r in go [] n (List.rev lst) (* Copyright (c) 2016 The astring programmers *) let add ~empty s ~start ~stop acc = if start = stop then if not empty then acc else "" :: acc else String.sub s start (stop - start) :: acc let cuts ~empty ~sep s = let sep_len = String.length sep in if sep_len = 0 then invalid_arg "cuts: the separator is empty" ; let s_len = String.length s in let max_sep_idx = sep_len - 1 in let max_s_idx = s_len - sep_len in let rec check_sep start i k acc = if k > max_sep_idx then let new_start = i + sep_len in scan new_start new_start (add ~empty s ~start ~stop:i acc) else if s.[i + k] = sep.[k] then check_sep start i (k + 1) acc else scan start (i + 1) acc and scan start i acc = if i > max_s_idx then if start = 0 then if (not empty) && s_len = 0 then [] else [ s ] else List.rev (add ~empty s ~start ~stop:s_len acc) else if s.[i] = sep.[0] then check_sep start i 1 acc else scan start (i + 1) acc in scan 0 0 [] let expand_macro hmp buf = function | `Literal str -> Buffer.add_string buf str | `Macro_encoded_space -> Buffer.add_string buf "%20" | `Macro_space -> Buffer.add_string buf " " | `Macro_percent -> Buffer.add_string buf "%" | `Macro (letter, (n, rev), sep) -> let (Key key) = key_of_letter letter in let pp = (Map.Key.info key).pp in let str = Fmt.str "%a" pp (Map.get key hmp) in let sep = if sep = "" then "." else sep in let vs = cuts ~sep ~empty:true str in let vs = if rev then List.rev vs else vs in let vs = Option.fold ~none:vs ~some:(fun n -> keep n vs) n in let str = String.concat "." vs in Buffer.add_string buf str let expand hmp (macro, rest) = let buf = Buffer.create 0x100 in List.iter (expand_macro hmp buf) macro ; match rest with | None -> Buffer.contents buf | Some str -> Buffer.add_string buf "." ; Buffer.add_string buf str ; Buffer.contents buf let expand_macro hmp t = try Domain_name.of_string (expand hmp t) with Not_found -> Fmt.error_msg "Missing informations while expanding macro" let expand_string hmp str = match Angstrom.parse_string ~consume:All domain_spec str with | Ok v -> expand_macro hmp v | Error _ -> error_msgf "Invalid macro specification: %S" str end module Term = struct open Angstrom let is_sp = ( = ) ' ' let is_digit = function '0' .. '9' -> true | _ -> false let junk_with v = advance 1 *> return v let junk_only_if p = peek_char >>= function | Some chr when p chr -> advance 1 *> return (Some chr) | _ -> return None let ip4_cidr_length = char '/' *> peek_char >>= function | Some '0' -> junk_with (Some 0) | Some ('\x31' .. '\x39' as chr) -> ( junk_with chr >>= fun a -> peek_char >>= function | Some ('0' .. '9' as b) -> let tmp = Bytes.create 2 in Bytes.set tmp 0 a ; Bytes.set tmp 1 b ; junk_with (Some (int_of_string (Bytes.unsafe_to_string tmp))) | _ -> return (Some (int_of_string (String.make 1 a)))) | _ -> return None let ip6_cidr_length = char '/' *> peek_char >>= function | Some '0' -> junk_with (Some 0) | Some '\x31' .. '\x39' -> ( junk_only_if is_digit >>= fun chr0 -> junk_only_if is_digit >>= fun chr1 -> match (chr0, chr1) with | Some chr0, Some chr1 -> let str = Bytes.create 2 in Bytes.set str 0 chr0 ; Bytes.set str 1 chr1 ; return (Some (int_of_string (Bytes.unsafe_to_string str))) | Some chr0, _ -> let str = Bytes.create 1 in Bytes.set str 0 chr0 ; return (Some (int_of_string (Bytes.unsafe_to_string str))) | None, Some _ -> fail "ip6-cidr-length" | None, None -> return None) | _ -> return None let dual_cidr_length = option None ip4_cidr_length >>= fun ip4 -> option None (char '/' *> ip6_cidr_length) >>= fun ip6 -> return (ip4, ip6) let all = string "all" *> return `All let include_mechanism = string "include" *> skip_while is_sp *> char ':' *> skip_while is_sp *> Macro.domain_spec >>| fun macro -> `Include macro let mx = string "mx" *> option None (skip_while is_sp *> char ':' *> skip_while is_sp *> Macro.domain_spec >>| Option.some) >>= fun macro -> option (None, None) dual_cidr_length >>= fun dual_cidr_length -> return (`Mx (macro, dual_cidr_length)) let a = char 'a' *> option None (skip_while is_sp *> char ':' *> skip_while is_sp *> Macro.domain_spec >>| Option.some) >>= fun macro -> option (None, None) dual_cidr_length >>= fun dual_cidr_length -> return (`A (macro, dual_cidr_length)) let ptr = string "ptr" *> option None (skip_while is_sp *> char ':' *> skip_while is_sp *> Macro.domain_spec >>| Option.some) >>= fun macro -> return (`Ptr macro) let qnum = string "25" *> (satisfy @@ function '\x30' .. '\x35' -> true | _ -> false) >>= (fun a -> return ("25" ^ String.make 1 a)) <|> ( char '2' *> both (satisfy @@ function '\x30' .. '\x34' -> true | _ -> false) (satisfy is_digit) >>= fun (a, b) -> let tmp = Bytes.create 3 in Bytes.set tmp 0 '2' ; Bytes.set tmp 1 a ; Bytes.set tmp 2 b ; return (Bytes.unsafe_to_string tmp) ) <|> ( char '1' *> both (satisfy is_digit) (satisfy is_digit) >>= fun (a, b) -> let tmp = Bytes.create 3 in Bytes.set tmp 0 '1' ; Bytes.set tmp 1 a ; Bytes.set tmp 2 b ; return (Bytes.unsafe_to_string tmp) ) <|> ( both (satisfy @@ function '\x31' .. '\x39' -> true | _ -> false) (satisfy is_digit) >>= fun (a, b) -> let tmp = Bytes.create 2 in Bytes.set tmp 0 a ; Bytes.set tmp 1 b ; return (Bytes.unsafe_to_string tmp) ) <|> (satisfy is_digit >>| String.make 1) let ip6_network = available >>= fun len -> Unsafe.peek len Bigstringaf.substring >>= fun str -> let idx = ref 0 in try let v6 = Ipaddr.V6.of_string_raw str idx in advance !idx *> return v6 with _ -> fail "ip6-network" let ip4_network = qnum <* char '.' >>= fun a -> qnum <* char '.' >>= fun b -> qnum <* char '.' >>= fun c -> qnum >>= fun d -> return (a, b, c, d) let ip4 = string "ip4" *> skip_while is_sp *> char ':' *> skip_while is_sp *> ip4_network >>= fun (a, b, c, d) -> option None ip4_cidr_length >>= fun cidr -> let str = Fmt.str "%s.%s.%s.%s%a" a b c d Fmt.(option ~none:(const string "/32") (const string "/" ++ int)) cidr in return (`V4 (Ipaddr.V4.Prefix.of_string_exn str)) let ip6 = string "ip6" *> skip_while is_sp *> char ':' *> skip_while is_sp *> ip6_network >>= fun v6 -> option None ip6_cidr_length >>= fun cidr -> let cidr = Option.value ~default:128 cidr in return (`V6 (Ipaddr.V6.Prefix.make cidr v6)) let exists = string "exists" *> skip_while is_sp *> char ':' *> skip_while is_sp *> Macro.domain_spec >>= fun macro -> return (`Exists macro) let redirect = string "redirect" *> skip_while is_sp *> char '=' *> skip_while is_sp *> Macro.domain_spec >>| fun macro -> `Redirect macro let explanation = string "exp" *> skip_while is_sp *> char '=' *> skip_while is_sp *> Macro.domain_spec >>| fun macro -> `Explanation macro let unknown_modifier = let name = peek_char >>= function | Some ('a' .. 'z' | 'A' .. 'Z') -> ( take_while1 @@ function | 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '-' | '_' | '.' -> true | _ -> false) | _ -> fail "name" in name >>= fun name -> skip_while is_sp *> char '=' *> skip_while is_sp *> Macro.macro_string >>= fun str -> return (`Unknown (name, str)) let mechanism = all <|> include_mechanism <|> a <|> mx <|> ptr <|> ip4 <|> ip6 <|> exists let modifier = redirect <|> explanation <|> unknown_modifier let qualifier = peek_char >>= function | Some (('+' | '-' | '?' | '~') as chr) -> junk_with (Some chr) | _ -> return None let directive = qualifier >>= fun qualifier -> mechanism >>= fun mechanism -> return (`Directive (qualifier, mechanism)) let terms = many (take_while1 is_sp *> (directive <|> modifier)) let record = string "v=spf1" *> terms <* skip_while is_sp type t = [ `Directive of char option * [ `A of Macro.t option * (int option * int option) | `All | `Exists of Macro.t | `Include of Macro.t | `Mx of Macro.t option * (int option * int option) | `Ptr of Macro.t option | `V4 of Ipaddr.V4.Prefix.t | `V6 of Ipaddr.V6.Prefix.t ] | `Explanation of Macro.t | `Redirect of Macro.t | `Unknown of string * Macro.macro list ] list let pp ppf ts = let pp_qualifier = Fmt.(option char) in let pp_cidr ppf = function | Some v4, Some v6 -> Fmt.pf ppf "/%d//%d" v4 v6 | Some v4, None -> Fmt.pf ppf "/%d" v4 | None, Some v6 -> Fmt.pf ppf "//%d" v6 | None, None -> () in let pp ppf = function | `Directive (qualifier, `A (Some macro, cidr)) -> Fmt.pf ppf "%aa:%a%a" pp_qualifier qualifier Macro.pp macro pp_cidr cidr | `Directive (qualifier, `A (None, cidr)) -> Fmt.pf ppf "%aa%a" pp_qualifier qualifier pp_cidr cidr | `Directive (qualifier, `All) -> Fmt.pf ppf "%aall" pp_qualifier qualifier | `Directive (qualifier, `Exists v) -> Fmt.pf ppf "%aexists:%a" pp_qualifier qualifier Macro.pp v | `Directive (qualifier, `Include v) -> Fmt.pf ppf "%ainclude:%a" pp_qualifier qualifier Macro.pp v | `Directive (qualifier, `Mx (Some macro, cidr)) -> Fmt.pf ppf "%amx:%a%a" pp_qualifier qualifier Macro.pp macro pp_cidr cidr | `Directive (qualifier, `Mx (None, cidr)) -> Fmt.pf ppf "%amx%a" pp_qualifier qualifier pp_cidr cidr | `Directive (qualifier, `Ptr (Some macro)) -> Fmt.pf ppf "%aptr:%a" pp_qualifier qualifier Macro.pp macro | `Directive (qualifier, `Ptr None) -> Fmt.pf ppf "%aptr" pp_qualifier qualifier | `Directive (qualifier, `V4 v4) -> Fmt.pf ppf "%aip4:%a" pp_qualifier qualifier Ipaddr.V4.Prefix.pp v4 | `Directive (qualifier, `V6 v6) -> Fmt.pf ppf "%aip6:%a" pp_qualifier qualifier Ipaddr.V6.Prefix.pp v6 | `Explanation macro -> Fmt.pf ppf "exp=%a" Macro.pp macro | `Redirect macro -> Fmt.pf ppf "redirect=%a" Macro.pp macro | `Unknown (identifier, ms) -> Fmt.pf ppf "%s=%a" identifier Macro.pp (ms, None) in Fmt.pf ppf "v=spf1 %a" Fmt.(list ~sep:(any " ") pp) ts let to_string = Fmt.to_to_string pp let equal = ( = ) let parse_record str = match Angstrom.parse_string ~consume:All record str with | Ok (v : t) -> Ok v | Error _ -> error_msgf "Invalid SPF record: %S" str end type qualifier = Pass | Fail | Softfail | Neutral type modifier = Explanation of string | Redirect of string let qualifier_of_letter = function | Some '+' | None -> Pass | Some '-' -> Fail | Some '~' -> Softfail | Some '?' -> Neutral | _ -> invalid_arg "qualifier_of_letter" let concat sep lst = let _, lst = List.partition (( = ) "") lst in let len = List.fold_right (( + ) % String.length) lst 0 in match lst with | [] -> "" | [ x ] -> x | x :: r -> let sep_len = String.length sep in let res = Bytes.create (len + (List.length r * sep_len)) in Bytes.blit_string x 0 res 0 (String.length x) ; let pos = ref (String.length x) in let blit x = Bytes.blit_string sep 0 res !pos sep_len ; Bytes.blit_string x 0 res (!pos + sep_len) (String.length x) ; pos := !pos + sep_len + String.length x in List.iter blit r ; Bytes.unsafe_to_string res module Record = struct type t = { mechanisms: (qualifier * mechanism) list ; modifiers: modifier Lazy.t list } let equal : t -> t -> bool = fun a b -> (* TODO(dinosaure): replace [Stdlib.compare]. *) let ma = List.sort Stdlib.compare a.mechanisms in let mb = List.sort Stdlib.compare b.mechanisms in try List.for_all2 ( = ) ma mb with _ -> false let v mechanisms modifiers = { mechanisms; modifiers= List.map Lazy.from_val modifiers } let pp_qualifier ppf = function | Pass -> () | Fail -> Fmt.string ppf "-" | Softfail -> Fmt.string ppf "~" | Neutral -> Fmt.string ppf "?" let pp_cidr ppf = function None -> () | Some v -> Fmt.pf ppf "/%d" v let pp_dual_cidr ppf = function | v4, (Some _ as v6) -> Fmt.pf ppf "%a/%a" pp_cidr v4 pp_cidr v6 | v4, None -> Fmt.pf ppf "%a" pp_cidr v4 let pp_mechanism ppf = function | A (v, cidr_v4, cidr_v6) -> Fmt.pf ppf "a%a%a" Fmt.(option (any ":" ++ Domain_name.pp)) v pp_dual_cidr (cidr_v4, cidr_v6) | All -> Fmt.string ppf "all" | Exists v -> Fmt.pf ppf "exists:%a" Domain_name.pp v | Include v -> Fmt.pf ppf "include:%a" Domain_name.pp v | Mx (v, cidr_v4, cidr_v6) -> Fmt.pf ppf "mx%a%a" Fmt.(option (any ":" ++ Domain_name.pp)) v pp_dual_cidr (cidr_v4, cidr_v6) | Ptr (Some v) -> Fmt.pf ppf "ptr:%a" Domain_name.pp v | Ptr None -> () | V4 ipv4 -> Fmt.pf ppf "ip4:%a" Ipaddr.V4.Prefix.pp ipv4 | V6 ipv6 -> Fmt.pf ppf "ip6:%a" Ipaddr.V6.Prefix.pp ipv6 let pp_modifier ppf = function | Explanation v -> Fmt.pf ppf "exp=%s" v | Redirect v -> Fmt.pf ppf "redirect=%s" v let pp ppf { mechanisms; modifiers } = Fmt.pf ppf "%a" Fmt.(list ~sep:(any " ") (pair ~sep:nop pp_qualifier pp_mechanism)) mechanisms ; match modifiers with | [] -> () | _ :: _ -> let modifiers = List.map Lazy.force modifiers in Fmt.pf ppf " %a" Fmt.(list ~sep:(any " ") pp_modifier) modifiers let to_string { mechanisms; modifiers } = let mechanism_to_string (q, m) = Fmt.str "%a%a" pp_qualifier q pp_mechanism m in let modifier_to_string m = Fmt.to_to_string pp_modifier m in let mechanisms = List.map mechanism_to_string mechanisms in let modifiers = List.map (modifier_to_string % Lazy.force) modifiers in concat " " [ concat " " mechanisms; concat " " modifiers ] let fold ctx acc = function | `Directive (qualifier, `A (macro, (cidr_v4, cidr_v6))) -> let macro = Option.map (Stdlib.Result.to_option % Macro.expand_macro ctx) macro in let macro = Option.join macro in let mechanism = (qualifier_of_letter qualifier, A (macro, cidr_v4, cidr_v6)) in { acc with mechanisms= mechanism :: acc.mechanisms } | `Directive (qualifier, `All) -> { acc with mechanisms= (qualifier_of_letter qualifier, All) :: acc.mechanisms } | `Directive (qualifier, `Exists macro) -> ( let qualifier = qualifier_of_letter qualifier in match Macro.expand_macro ctx macro with | Ok macro -> { acc with mechanisms= (qualifier, Exists macro) :: acc.mechanisms } | Error _ -> acc (* TODO *)) | `Directive (qualifier, `Include macro) -> ( let qualifier = qualifier_of_letter qualifier in match Macro.expand_macro ctx macro with | Ok macro -> { acc with mechanisms= (qualifier, Include macro) :: acc.mechanisms } | Error _ -> acc (* TODO *)) | `Directive (qualifier, `Mx (macro, (cidr_v4, cidr_v6))) -> let macro = Option.map (Stdlib.Result.to_option % Macro.expand_macro ctx) macro in let macro = Option.join macro in let mechanism = (qualifier_of_letter qualifier, Mx (macro, cidr_v4, cidr_v6)) in { acc with mechanisms= mechanism :: acc.mechanisms } | `Directive (qualifier, `Ptr macro) -> let qualifier = qualifier_of_letter qualifier in let macro = Option.map (Stdlib.Result.to_option % Macro.expand_macro ctx) macro in let macro = Option.join macro in { acc with mechanisms= (qualifier, Ptr macro) :: acc.mechanisms } | `Directive (qualifier, `V4 ipv4) -> let qualifier = qualifier_of_letter qualifier in { acc with mechanisms= (qualifier, V4 ipv4) :: acc.mechanisms } | `Directive (qualifier, `V6 ipv6) -> let qualifier = qualifier_of_letter qualifier in { acc with mechanisms= (qualifier, V6 ipv6) :: acc.mechanisms } | `Explanation macro -> let modifier = Lazy.from_fun @@ fun () -> let macro = Macro.expand_macro ctx macro in let macro = failwith_error_msg macro in let e = Domain_name.to_string macro in Explanation e in { acc with modifiers= modifier :: acc.modifiers } | `Redirect macro -> let modifier = Lazy.from_fun @@ fun () -> let macro = Macro.expand_macro ctx macro in let macro = failwith_error_msg macro in let r = Domain_name.to_string macro in Redirect r in { acc with modifiers= modifier :: acc.modifiers } | `Unknown _ -> acc let of_string ~ctx str = Term.parse_record str >>| fun terms -> List.fold_left (fold ctx) { mechanisms= []; modifiers= [] } terms end let rec select_spf1 = function | [] -> None | x :: r when String.length x >= 6 -> if String.sub x 0 6 = "v=spf1" then Some x else select_spf1 r | _ :: r -> select_spf1 r let of_qualifier ~mechanism q match' = match (q, match') with | Pass, true -> raise (Result (Result.pass mechanism)) | Fail, true -> terminate Result.fail | Softfail, true -> terminate Result.softfail | Neutral, true -> terminate Result.neutral | _ -> () let ipv4_with_cidr cidr v4 = Option.fold ~none:(Ipaddr.V4.Prefix.of_addr v4) ~some:(fun v -> Ipaddr.V4.Prefix.make v v4) cidr let ipv6_with_cidr cidr v6 = Option.fold ~none:(Ipaddr.V6.Prefix.of_addr v6) ~some:(fun v -> Ipaddr.V6.Prefix.make v v6) cidr let ipaddrs_of_mx { Dns.Mx.mail_exchange; _ } (cidr_v4, cidr_v6) = let* response = (mail_exchange, Dns.Rr_map.A) in match response with | Ok (_, v4s) -> let v4s = Ipaddr.V4.Set.elements v4s in let v4s = List.map (ipv4_with_cidr cidr_v4) v4s in return (List.map (fun v -> Ipaddr.V4 v) v4s) | Error _ -> begin let* response = (mail_exchange, Dns.Rr_map.Aaaa) in match response with | Ok (_, v6s) -> let v6s = Ipaddr.V6.Set.elements v6s in let v6s = List.map (ipv6_with_cidr cidr_v6) v6s in return (List.map (fun v -> Ipaddr.V6 v) v6s) | Error (`Msg _) -> terminate Result.temperror | Error (`No_domain _ | `No_data _) -> return [] end let rec mx_mechanism ctx ~limit q domain_name dual_cidr = let* response = (domain_name, Dns.Rr_map.Mx) in match response with | Error (`Msg _) -> terminate Result.temperror | Error (`No_data _ | `No_domain _) (* RCODE:3 *) -> return () | Ok (_, mxs) -> match Map.get Map.K.ip ctx with | value -> go ~limit q value (Dns.Rr_map.Mx_set.elements mxs) domain_name dual_cidr | exception _ -> return () and go ~limit q expected mxs domain_name ((cidr_v4, cidr_v6) as dual_cidr) = if limit >= 10 then raise (Result Result.permerror) ; let mechanism = Mx (Some domain_name, cidr_v4, cidr_v6) in let mxs = List.filteri (fun idx _mx -> limit + idx < 10) mxs in let mxs = Array.of_list mxs in let fn idx () = if idx >= Array.length mxs then terminate Result.permerror ; let+ ipaddrs = ipaddrs_of_mx mxs.(idx) dual_cidr in let exists = List.exists (Ipaddr.Prefix.mem expected) ipaddrs in of_qualifier ~mechanism q exists in let+ () = tries (List.init 10 fn) in terminate Result.permerror let a_mechanism ctx ~limit:_ q domain_name (cidr_v4, cidr_v6) = let mechanism = A (Some domain_name, cidr_v4, cidr_v6) in let* response = (domain_name, Dns.Rr_map.A) in match response with | Ok (_, v4s) -> let v4s = Ipaddr.V4.Set.elements v4s in let v4s = List.map (ipv4_with_cidr cidr_v4) v4s in let expected = Map.get Map.K.ip ctx in let v4s = List.map (fun v -> Ipaddr.V4 v) v4s in let exists = List.exists (Ipaddr.Prefix.mem expected) v4s in of_qualifier ~mechanism q exists ; return () | Error _ -> begin let* response = (domain_name, Dns.Rr_map.Aaaa) in match response with | Ok (_, v6s) -> let v6s = Ipaddr.V6.Set.elements v6s in let v6s = List.map (ipv6_with_cidr cidr_v6) v6s in let expected = Map.get Map.K.ip ctx in let v6s = List.map (fun v -> Ipaddr.V6 v) v6s in let exists = List.exists (Ipaddr.Prefix.mem expected) v6s in of_qualifier ~mechanism q exists ; return () | Error (`Msg _) -> terminate Result.temperror | Error (`No_domain _ | `No_data _) -> return () end let exists_mechanism _ctx ~limit:_ q domain_name = let mechanism = Exists domain_name in let* response = (domain_name, Dns.Rr_map.A) in match response with | Ok _ -> of_qualifier ~mechanism q true ; return () | Error _ -> begin let* response = (domain_name, Dns.Rr_map.Aaaa) in match response with | Ok _ -> of_qualifier ~mechanism q true ; return () | Error (`Msg _) -> terminate Result.temperror | Error (`No_domain _ | `No_data _) -> return () end let has_redirect modifiers = let fold acc modifier = match (acc, modifier) with | (Some redirect, acc), modifier -> (Some redirect, modifier :: acc) | (None, acc), modifier -> match Lazy.force modifier with | Redirect redirect -> (Some redirect, acc) | _ -> (None, modifier :: acc) | exception exn -> raise exn in let redirect, modifiers = List.fold_left fold (None, []) modifiers in (redirect, List.rev modifiers) let rec do_redirect ctx ~limit ~modifiers = match has_redirect modifiers with | exception _ -> terminate Result.permerror | None, _ -> terminate Result.neutral | Some redirect, modifiers -> ( let domain_name = Domain_name.of_string redirect in let domain_name = Stdlib.Result.get_ok domain_name in let* response = (domain_name, Dns.Rr_map.Txt) in match response with | Error (`No_domain _ | `No_data _) -> go ctx ~limit:(succ limit) ~modifiers [] | Error (`Msg _err) -> terminate Result.temperror | Ok (_, txts) -> let txts = Dns.Rr_map.Txt_set.elements txts in let terms = match select_spf1 txts with | Some terms -> terms | None -> terminate Result.permerror in let terms = match Term.parse_record terms with | Ok terms -> terms | Error _ -> terminate Result.permerror in let empty = { Record.mechanisms= []; modifiers= [] } in let record = List.fold_left (Record.fold ctx) empty terms in let record = { record with mechanisms= List.rev record.mechanisms } in let record = { record with modifiers= List.rev record.modifiers } in let ctx' = Map.add Map.K.domain domain_name ctx in let fn () = go ctx' ~limit ~modifiers:record.modifiers record.mechanisms in let neutral () = go ctx ~limit:(succ limit) ~modifiers [] in choose_on fn ~neutral) and include_mechanism ctx ~limit q domain_name = let ctx = Map.add Map.K.domain domain_name ctx in let* response = (domain_name, Dns.Rr_map.Txt) in match response with | Error (`Msg _) -> terminate Result.temperror | Error (`No_domain _ | `No_data _) -> terminate Result.permerror | Ok (_, txts) -> let txts = Dns.Rr_map.Txt_set.elements txts in let terms = match select_spf1 txts with | Some terms -> terms | None -> terminate Result.permerror in let terms = match Term.parse_record terms with | Ok terms -> terms | Error _ -> terminate Result.permerror in let empty = { Record.mechanisms= []; modifiers= [] } in let record = List.fold_left (Record.fold ctx) empty terms in let record = { record with mechanisms= List.rev record.mechanisms } in let record = { record with modifiers= List.rev record.modifiers } in let permerror () = terminate Result.permerror in let pass mechanism = of_qualifier ~mechanism q true ; return () in let fn () = check ctx ~limit:(succ limit) record in choose_on fn ~permerror ~none:permerror ~pass and apply ctx ~limit (q, mechanism) = match mechanism with | All -> of_qualifier ~mechanism q true ; return () | A (Some domain_name, cidr_ipv4, cidr_ipv6) -> Log.debug (fun m -> m "Apply A mechanism with %a." Domain_name.pp domain_name) ; a_mechanism ctx ~limit q domain_name (cidr_ipv4, cidr_ipv6) | A (None, cidr_ipv4, cidr_ipv6) -> let domain_name = Map.get Map.K.domain ctx in Log.debug (fun m -> m "Apply A mechanism with no domain, using %a." Domain_name.pp domain_name) ; a_mechanism ctx ~limit q domain_name (cidr_ipv4, cidr_ipv6) | Mx (Some domain_name, cidr_ipv4, cidr_ipv6) -> Log.debug (fun m -> m "Apply MX mechanism with %a." Domain_name.pp domain_name) ; mx_mechanism ctx ~limit q domain_name (cidr_ipv4, cidr_ipv6) | Mx (None, cidr_ipv4, cidr_ipv6) -> let domain_name = Map.get Map.K.domain ctx in Log.debug (fun m -> m "Apply MX mechanism with no domain, using %a." Domain_name.pp domain_name) ; mx_mechanism ctx ~limit q domain_name (cidr_ipv4, cidr_ipv6) | Include domain_name -> Log.debug (fun m -> m "Apply INCLUDE mechanism with %a." Domain_name.pp domain_name) ; include_mechanism ctx ~limit q domain_name | V4 v4 -> Log.debug (fun m -> m "Apply IPv4 mechanism with %a." Ipaddr.V4.Prefix.pp v4) ; let exists = Ipaddr.Prefix.mem (Map.get Map.K.ip ctx) (Ipaddr.V4 v4) in of_qualifier ~mechanism q exists ; return () | V6 v6 -> Log.debug (fun m -> m "Apply IPv6 mechanism with %a." Ipaddr.V6.Prefix.pp v6) ; let exists = Ipaddr.Prefix.mem (Map.get Map.K.ip ctx) (Ipaddr.V6 v6) in of_qualifier ~mechanism q exists ; return () | Exists domain_name -> exists_mechanism ctx ~limit q domain_name | Ptr _ -> return () (* See RFC 7802, Appendix B. *) and check ctx ~limit record = go ctx ~limit ~modifiers:record.modifiers record.mechanisms and go ctx ~limit ~modifiers = function | [] -> do_redirect ctx ~limit ~modifiers | ms -> let ms = List.filteri (fun idx _m -> idx + limit < 10) ms in let ms = Array.of_list ms in let fn idx () = if idx >= Array.length ms then terminate Result.permerror ; Log.debug (fun m -> m "Apply the mechanism %02d" idx) ; apply ctx ~limit:(limit + idx) ms.(idx) in let+ () = tries (List.init 10 fn) in terminate Result.permerror let check ctx record = check ctx ~limit:0 record let get_and_check ctx = match Map.find Map.K.domain ctx with | None -> failwith "Missing domain-name into the given context" | Some domain_name -> ( let* response = (domain_name, Dns.Rr_map.Txt) in match response with | Error (`No_domain _ | `No_data _) -> terminate Result.none | Error (`Msg _err) -> terminate Result.temperror | Ok (_, txts) -> let txts = Dns.Rr_map.Txt_set.elements txts in let txts = match select_spf1 txts with | None -> raise (Result Result.none) | Some txts -> txts in let terms = match Term.parse_record txts with | Ok terms -> terms | Error _ -> raise (Result Result.permerror) in let empty = { Record.mechanisms= []; modifiers= [] } in let record = List.fold_left (Record.fold ctx) empty terms in let record = { record with mechanisms= List.rev record.mechanisms } in let record = { record with modifiers= List.rev record.modifiers } in check ctx record) let get ctx = match Map.find Map.K.domain ctx with | None -> failwith "Missing domain-name into the given context" | Some domain_name -> ( let* response = (domain_name, Dns.Rr_map.Txt) in match response with | Error (`No_domain _ | `No_data _) -> terminate Result.none | Error (`Msg _err) -> terminate Result.temperror | Ok (_, txts) -> ( let txts = Dns.Rr_map.Txt_set.elements txts in match select_spf1 txts with | Some txts -> return (Term.parse_record txts) | None -> return (error_msgf "SPF record not found"))) module Encoder = struct open Prettym let result ppf = function | `None -> string ppf "none" | `Neutral -> string ppf "neutral" | `Pass _ -> string ppf "pass" | `Fail -> string ppf "fail" | `Softfail -> string ppf "softfail" | `Temperror -> string ppf "temperror" | `Permerror -> string ppf "permerror" let to_safe_string pp v = Fmt.str "%a" pp v (* TODO *) let kv : type a v. name:string -> a Map.key -> ?pp:a Fmt.t -> Map.t -> (v, v) fmt = fun ~name key ?pp ctx -> match Map.find key ctx with | None -> [ cut ] | Some v -> let pp = match pp with Some pp -> pp | None -> (Map.Key.info key).Map.pp in [ spaces 1; string $ name; cut; char $ '='; cut ; string $ to_safe_string pp v; cut; char $ ';' ] let ( ^^ ) a b = concat a b let pp_identity ppf = function | `MAILFROM _ -> Fmt.string ppf "mailfrom" | `HELO _ -> Fmt.string ppf "helo" let sender ppf v = eval ppf [ !!string ] (Fmt.to_to_string Map.pp_path v) let domain_name ppf = function | `Addr (Emile.IPv4 v) -> eval ppf [ !!string ] (Ipaddr.V4.to_string v) | `Addr (Emile.IPv6 v) -> eval ppf [ !!string ] (Ipaddr.V6.to_string v) | `Addr (Emile.Ext (k, v)) -> eval ppf [ char $ '['; !!string; char $ ':'; !!string; char $ ']' ] k v | `Domain vs -> let sep = ((fun ppf () -> string ppf "."), ()) in eval ppf [ !!(list ~sep string) ] vs | `Literal v -> eval ppf [ char $ '['; !!string; char $ ']' ] v let ipaddr ppf v = eval ppf [ !!string ] (Ipaddr.to_string v) let comment ~ctx ?receiver ppf (v : Result.t) = match (receiver, Map.get Map.K.sender ctx, v) with | None, _, _ -> ppf | Some receiver, `MAILFROM p, `Pass _ -> eval ppf [ char $ '('; !!domain_name; char $ ':'; spaces 1; string $ "domain" ; spaces 1; string $ "of"; spaces 1; !!sender; spaces 1 ; string $ "designates"; spaces 1; !!ipaddr; spaces 1; string $ "as" ; spaces 1; string $ "permitted"; spaces 1; string $ "sender" ; char $ ')' ] receiver p (Map.get Map.K.ip ctx) | Some receiver, `MAILFROM p, _ -> begin match Map.get Map.K.ip ctx with | value -> eval ppf [ char $ '('; !!domain_name; char $ ':'; spaces 1 ; string $ "domain"; spaces 1; string $ "of"; spaces 1; !!sender ; spaces 1; string $ "does"; spaces 1; string $ "not"; spaces 1 ; string $ "designates"; spaces 1; !!ipaddr; spaces 1 ; string $ "as"; spaces 1; string $ "permitted"; spaces 1 ; string $ "sender"; char $ ')' ] receiver p value | exception _ -> ppf end | Some _, `HELO _, _ -> ppf let field ~ctx ?receiver ppf v = eval ppf ([ tbox 1; !!result; fws; !!(comment ~ctx ?receiver) ] ^^ kv ~name:"client-ip" Map.K.ip ~pp:Ipaddr.pp ctx ^^ kv ~name:"envelope-from" Map.K.sender ctx ^^ kv ~name:"helo" Map.K.helo ctx ^^ kv ~name:"identity" Map.K.sender ~pp:pp_identity ctx ^^ (match receiver with | None -> [ cut ] | Some receiver -> [ spaces 1; string $ "receiver"; cut; char $ '='; cut ; string $ Fmt.to_to_string Emile.pp_domain receiver; cut ; char $ ';' ]) ^^ (match v with | `Pass m -> [ spaces 1; string $ "mechanism"; cut; char $ '='; cut ; string $ to_safe_string Record.pp_mechanism m; cut; char $ ';' ] | _ -> [ cut ]) ^^ [ close; new_line ]) v v end let field_received_spf = Mrmime.Field_name.v "Received-SPF" let to_field : ctx:ctx -> ?receiver:Emile.domain -> Result.t -> Mrmime.Field_name.t * Unstrctrd.t = fun ~ctx ?receiver res -> let v = Prettym.to_string (Encoder.field ~ctx ?receiver) res in let _, v = Stdlib.Result.get_ok (Unstrctrd.of_string v) in (field_received_spf, v) module Decoder = struct open Angstrom let is_alpha = function 'A' .. 'Z' | 'a' .. 'z' -> true | _ -> false let is_space = ( = ) ' ' let result = choice [ (string "pass" >>| fun _ -> `Pass); (string "fail" >>| fun _ -> `Fail) ; (string "softfail" >>| fun _ -> `Softfail) ; (string "neutral" >>| fun _ -> `Neutral) ; (string "none" >>| fun _ -> `None) ; (string "temperror" >>| fun _ -> `Temperror) ; (string "permerror" >>| fun _ -> `Permerror) ] let key = let name = satisfy is_alpha >>= fun x -> ( take_while @@ function | 'a' .. 'z' | 'A' .. 'Z' -> true | '0' .. '9' -> true | '-' | '_' | '.' -> true | _ -> false ) >>= fun r -> return (String.make 1 x ^ r) in choice [ string "client-ip"; string "envelope-from"; string "helo" ; string "problem"; string "receiver"; string "identity" ; string "mechanism"; name ] (* XXX(dinosaure): [dot-atom] and [quoted-string] are specified by RFC 5322 * and they are implemented by [emile]/[mrmime]. We took them in this case. *) let dot_atom = Emile.Parser.dot_atom >>| String.concat "." let quoted_string = Emile.Parser.quoted_string let key_value_pair = key >>= fun key -> skip_while is_space *> char '=' *> skip_while is_space *> (dot_atom <|> quoted_string) >>= fun value -> return (key, value) let key_value_list = key_value_pair >>= fun x -> many (skip_while is_space *> char ';' *> skip_while is_space *> key_value_pair) >>= fun r -> option () (skip_while is_space *> char ';' *> skip_while is_space) >>= fun () -> return (x :: r) let ipaddr = Term.ip6_network >>| (fun v -> Ipaddr.V6 v) <|> ( Term.ip4_network >>| fun (a, b, c, d) -> Ipaddr.V4 (Ipaddr.V4.of_string_exn (Fmt.str "%s.%s.%s.%s" a b c d)) ) (* XXX(dinosaure): this part is not specified but it can give to us informations such as * the domain of the [receiver], the mailbox of the [sender] (it should be the same as [From]) * and the IP address of the [sender]. *) let good_comment = char '(' *> skip_while is_space *> Emile.Parser.domain >>= fun receiver -> skip_while is_space *> char ':' *> skip_while is_space *> string "domain" *> skip_while is_space *> string "of" *> skip_while is_space *> Emile.Parser.addr_spec >>= fun sender -> skip_while is_space *> string "designates" *> skip_while is_space *> ipaddr >>= fun ip -> skip_while is_space *> string "as" *> skip_while is_space *> string "permitted" *> skip_while is_space *> string "sender" *> skip_while is_space *> char ')' *> return (receiver, sender, ip) let bad_comment = char '(' *> skip_while is_space *> Emile.Parser.domain >>= fun receiver -> skip_while is_space *> char ':' *> skip_while is_space *> string "domain" *> skip_while is_space *> string "of" *> skip_while is_space *> Emile.Parser.addr_spec >>= fun sender -> skip_while is_space *> string "does" *> skip_while is_space *> string "not" *> skip_while is_space *> string "designate" *> skip_while is_space *> ipaddr >>= fun ip -> skip_while is_space *> string "as" *> skip_while is_space *> string "permitted" *> skip_while is_space *> string "sender" *> skip_while is_space *> char ')' *> return (receiver, sender, ip) let comment = good_comment <|> bad_comment let header_field = skip_while is_space *> result >>= fun res -> option None (skip_while is_space *> comment >>| Option.some) >>= fun comment -> option [] (skip_while is_space *> key_value_list) >>= fun kvs -> return (res, comment, kvs) let parse_received_spf_field_value unstrctrd = let str = Unstrctrd.(to_utf_8_string (fold_fws unstrctrd)) in match Angstrom.parse_string ~consume:Prefix header_field str with | Ok v -> Ok v | Error _ -> error_msgf "Invalid Received-SPF value: %S" str end let pp_result ppf = function | `None -> Fmt.string ppf "none" | `Neutral -> Fmt.string ppf "neutral" | `Pass -> Fmt.string ppf "pass" | `Fail -> Fmt.string ppf "fail" | `Softfail -> Fmt.string ppf "softfail" | `Temperror -> Fmt.string ppf "temperror" | `Permerror -> Fmt.string ppf "permerror" let to_unstrctrd unstructured = let fold acc = function #Unstrctrd.elt as elt -> elt :: acc | _ -> acc in let unstrctrd = List.fold_left fold [] unstructured in match Unstrctrd.of_list (List.rev unstrctrd) with | Ok v -> v | _ -> assert false let ctx_of_kvs kvs = let identity = match List.assoc_opt "identity" kvs with | Some "mailfrom" -> Some `MAILFROM | Some "helo" -> Some `HELO | _ -> None in let receiver = Option.bind (List.assoc_opt "receiver" kvs) (Stdlib.Result.to_option % Colombe.Domain.of_string) in let fold ctx = function | "client-ip", v -> ( match Ipaddr.of_string v with | Ok (Ipaddr.V4 _ as v) -> Map.add Map.K.ip v (Map.add Map.K.v `In_addr ctx) | Ok (Ipaddr.V6 _ as v) -> Map.add Map.K.ip v (Map.add Map.K.v `Ip6 ctx) | _ -> ctx) | "helo", v -> ( match (Colombe.Domain.of_string v, Domain_name.of_string v) with | Ok v0, Ok v1 -> Map.add Map.K.helo v0 (Map.add Map.K.domain v1 ctx) | Ok v, Error _ -> Map.add Map.K.helo v ctx | Error _, Ok v -> Map.add Map.K.domain v ctx | _ -> ctx) | "envelope-from", v -> ( match (Colombe.Path.of_string (Fmt.str "<%s>" v), identity) with | Ok { Colombe.Path.local; domain; _ }, Some `HELO -> let ctx = Map.add Map.K.local local ctx in let ctx = Map.add Map.K.domain_of_sender domain ctx in let ctx = match (domain, Map.find Map.K.domain ctx) with | Colombe.Domain.Domain vs, None -> let v = Domain_name.of_strings_exn vs in Map.add Map.K.sender (`HELO v) ctx |> Map.add Map.K.domain v | Colombe.Domain.Domain vs, Some _ -> let v = Domain_name.of_strings_exn vs in Map.add Map.K.sender (`HELO v) ctx | _ -> ctx in ctx | Ok ({ Colombe.Path.local; domain; _ } as v), (Some `MAILFROM | None) -> let ctx = Map.add Map.K.sender (`MAILFROM v) ctx in let ctx = Map.add Map.K.local local ctx in let ctx = Map.add Map.K.domain_of_sender domain ctx in let ctx = match (domain, Map.find Map.K.domain ctx) with | Colombe.Domain.Domain vs, None -> Map.add Map.K.domain (Domain_name.of_strings_exn vs) ctx | _ -> ctx in ctx | Error _, _ -> ctx) | _ -> ctx in let ctx = match identity with | Some value -> Map.singleton Map.K.origin value | None -> Map.empty in (identity, receiver, List.fold_left fold ctx kvs) let colombe_domain_to_emile_domain = function | Colombe.Domain.IPv4 v -> `Addr (Emile.IPv4 v) | Colombe.Domain.IPv6 v -> `Addr (Emile.IPv6 v) | Colombe.Domain.Domain vs -> `Domain vs | Colombe.Domain.Extension (k, v) -> `Addr (Emile.Ext (k, v)) let to_mailbox { Colombe.Path.local; domain; _ } = let local = match local with | `Dot_string vs -> List.map (fun v -> `Atom v) vs | `String v -> [ `String v ] in let domain = colombe_domain_to_emile_domain domain in { Emile.local; domain= (domain, []); name= None } (* *) let p = let open Mrmime in let unstructured = Field.(Witness Unstructured) in let open Field_name in Map.empty |> Map.add date unstructured |> Map.add from unstructured |> Map.add sender unstructured |> Map.add reply_to unstructured |> Map.add (v "To") unstructured |> Map.add cc unstructured |> Map.add bcc unstructured |> Map.add subject unstructured |> Map.add message_id unstructured |> Map.add comments unstructured |> Map.add content_type unstructured |> Map.add content_encoding unstructured module Extract = struct type result = [ `None | `Neutral | `Pass | `Fail | `Softfail | `Temperror | `Permerror ] type field = { result: result ; receiver: Emile.domain option ; sender: Emile.mailbox option ; ip: Ipaddr.t option ; ctx: ctx } let pp ppf t = Fmt.pf ppf "{ @[<hov>result= %a;@ receiver= @[<hov>%a@];@ sender= @[<hov>%a@];@ ip= \ @[<hov>%a@];@ ctx= #ctx;@] }" pp_result t.result Fmt.(Dump.option Emile.pp_domain) t.receiver Fmt.(Dump.option Emile.pp_mailbox) t.sender Fmt.(Dump.option Ipaddr.pp) t.ip let to_field = function | result, Some ((receiver' : Emile.domain), sender', ip'), kvs -> let p' = failwith_error_msg (Colombe_emile.to_path sender') in let identity, receiver, ctx = ctx_of_kvs kvs in let receiver = Option.value ~default:receiver' (Option.map colombe_domain_to_emile_domain receiver) in let ctx, ip = match Map.find Map.K.ip ctx with | Some ip -> (ctx, ip) | None -> (Map.add Map.K.ip ip' ctx, ip') in let ctx, sender = match (Map.find Map.K.sender ctx, identity) with | Some (`HELO _), Some `MAILFROM -> (ctx, None) | Some (`HELO _), (Some `HELO | None) -> (ctx, Some (to_mailbox p')) | Some (`MAILFROM p), _ -> (ctx, Some (to_mailbox p)) | None, (Some `MAILFROM | None) -> let { Colombe.Path.local; domain; _ } = p' in let ctx = Map.add Map.K.sender (`MAILFROM p') ctx in let ctx = Map.add Map.K.local local ctx in let ctx = Map.add Map.K.domain_of_sender domain ctx in let ctx = match (domain, Map.find Map.K.domain ctx) with | Colombe.Domain.Domain vs, None -> Map.add Map.K.domain (Domain_name.of_strings_exn vs) ctx | _ -> ctx in (ctx, Some (to_mailbox p')) | None, Some `HELO -> let { Colombe.Path.local; domain; _ } = p' in let ctx = Map.add Map.K.local local ctx in let ctx = Map.add Map.K.domain_of_sender domain ctx in let ctx = match (domain, Map.find Map.K.domain ctx) with | Colombe.Domain.Domain vs, None -> let v = Domain_name.of_strings_exn vs in Map.add Map.K.sender (`HELO v) ctx |> Map.add Map.K.domain v | Colombe.Domain.Domain vs, Some _ -> let v = Domain_name.of_strings_exn vs in Map.add Map.K.sender (`HELO v) ctx | _ -> ctx in (ctx, Some (to_mailbox p')) in { result; receiver= Some receiver; sender; ip= Some ip; ctx } | result, None, kvs -> let _identity, receiver, ctx = ctx_of_kvs kvs in let receiver = Option.map colombe_domain_to_emile_domain receiver in let sender = match Map.find Map.K.sender ctx with | Some (`MAILFROM p) -> Some (to_mailbox p) | _ -> None in let ip = Map.find Map.K.ip ctx in { result; receiver; sender; ip; ctx } type state = Extraction of Mrmime.Hd.decoder * field list type extract = { input: bytes; input_pos: int; input_len: int; state: state } type decode = [ `Await of extract | `Fields of field list | `Malformed of string ] let extractor () = let input, input_pos, input_len = (Bytes.empty, 1, 0) in let dec = Mrmime.Hd.decoder p in let state = Extraction (dec, []) in { input; input_pos; input_len; state } let src_rem t = t.input_len - t.input_pos + 1 let end_of_input extractor = { extractor with input= Bytes.empty; input_pos= 0; input_len= min_int } let src t src idx len = if idx < 0 || len < 0 || idx + len > String.length src then Fmt.invalid_arg "Uspf.Extract.src: source out of bounds" ; let input = Bytes.unsafe_of_string src in let input_pos = idx in let input_len = idx + len - 1 in let t = { t with input; input_pos; input_len } in match t.state with | Extraction (v, _) -> Mrmime.Hd.src v src idx len ; if len == 0 then end_of_input t else t let parse_received_spf_field_value unstrctrd = match Decoder.parse_received_spf_field_value unstrctrd with | Ok v -> Ok (to_field v) | Error _ as err -> err let extract t decoder fields = let open Mrmime in let rec go acc = match Hd.decode decoder with | `Field field -> begin let (Field.Field (field_name, w, v)) = Location.prj field in match (Field_name.equal field_name field_received_spf, w) with | true, Field.Unstructured -> begin let v = to_unstrctrd v in match parse_received_spf_field_value v with | Ok v -> go (v :: acc) | Error (`Msg _err) -> go acc end | _ -> go acc end | `Malformed _ as err -> err | `End _ -> `Fields (List.rev acc) | `Await -> let state = Extraction (decoder, acc) in let rem = src_rem t in let input_pos = t.input_pos + rem in let t = { t with state; input_pos } in `Await t in go fields let extract t = let (Extraction (decoder, fields)) = t.state in extract t decoder fields let of_unstrctrd unstrctrd = let ( let* ) = Stdlib.Result.bind in let* v = Decoder.parse_received_spf_field_value unstrctrd in Ok (to_field v) let of_string str = let ( let* ) = Stdlib.Result.bind in let* _, unstrctrd = Unstrctrd.of_string (str ^ "\r\n") in of_unstrctrd unstrctrd end (* let extract_received_spf : type flow t. ?newline:[ `LF | `CRLF ] -> flow -> t state -> (module FLOW with type flow = flow and type backend = t) -> ((extracted, [> `Msg of string ]) result, t) io = fun ?(newline = `LF) flow { bind; return } (module Flow) -> let open Mrmime in let ( >>= ) = bind in let chunk = 0x1000 in let raw = Bytes.create chunk in let decoder = Hd.decoder p in let rec go acc = match Hd.decode decoder with | `Field field -> ( let (Field.Field (field_name, w, v)) = Location.prj field in match (Field_name.equal field_name field_received_spf, w) with | true, Field.Unstructured -> ( let v = to_unstrctrd v in match parse_received_spf_field_value v with | Ok v -> go (v :: acc) | Error (`Msg err) -> Log.warn (fun m -> m "Ignore Received-SPF value: %s." err) ; go acc) | _ -> go acc) | `Malformed _err -> Log.err (fun m -> m "The given email is malformed.") ; return (error_msg "Invalid email") | `End _rest -> return (Ok (List.rev acc)) | `Await -> Flow.input flow raw 0 (Bytes.length raw) >>= fun len -> let raw = sanitize_input newline raw len in Hd.src decoder raw 0 (String.length raw) ; go acc in go [] *) let a ?cidr_v4 ?cidr_v6 domain_name = A (Some domain_name, cidr_v4, cidr_v6) let all = All let exists domain_name = Exists domain_name let inc domain_name = Include domain_name (* TODO(dinosaure): currently, [mechanism] is a **result** of the macro expansion - the user can not specify by this way its own macro, he can specify only a domain-name. We must provide something else than the [mechanism] type which accepts macro. *) let mx ?cidr_v4 ?cidr_v6 domain_name = Mx (Some domain_name, cidr_v4, cidr_v6) let v4 v = V4 v let v6 v = V6 v let pass m = (Pass, m) let fail m = (Fail, m) let softfail m = (Softfail, m) let neutral m = (Neutral, m)
uspf
0.2.0
MIT
https://github.com/mirage/uspf
git+https://github.com/mirage/uspf.git
mli
uspf-0.2.0/lib/uspf.mli
(** {1 (Un)Sender Policy Framework.} uSPF is a framework to check the identity of the email's sender. When an email passes through an SMTP server, some informations are available such as the source of the email, the IP address (because the sender must initiate a TCP/IP connexion). From these informations and via uSPF (and DNS records), we are able to {i authorize} the given email or not. Indeed, the email submission process requires an identity with the SMTP [MAILFROM] command. At this stage, we are able to check if the domain name given by [MAILFROM] and the current IP address of the sender match! The domain-name used by [MAILFROM] should have some DNS records which describe which IP address is allowed to send an email via the [MAILFROM]'s identity. uSPF will check that and it will try to find a {i match}. In any results - if uSPF fails or not - the SMTP server will put the result of such check into the given email. Finally, it permits to check, at any step of the submission, the identity of the sender. However, it does not ensure a high level of securities when uSPF should be use with DKIM/DMARC to ensure some others aspects such as the integrity of the given email. {2 How to use uSPF.} uSPF requires some {i meta} informations such as the [MAILFROM] identity and the IP address of the sender. The user can create a {!type:ctx} and fill it with these information: {[ let ctx = Uspf.empty |> Uspf.with_sender (`MAILFROM path) |> Uspf.with_ip ipaddr ]} From this [ctx], then the user is able to {i check} the identity of the sender via a DNS implementation. The user must get the SPF DNS record, analyze it and use it then with the [ctx]: {[ let res = Uspf.get ctx sched dns (module DNS) >>= Uspf.check ctx sched dns (module DNS) ]} From the result, the user is able to generate an {i header field}. It optional to give your identity (your domain) to be exhaustive about {i meta} information on the field value: {[ let field_name, value = Uspf.to_field ~ctx ?receiver res ]} The value is well-formed for the incoming email. You just need to prepend the field before the email. {2 Reproductibility.} The API provides a possibility to extract SPF results from an incoming email and regenerate the [ctx] from them. By this way, locally, you can reproduce the process above. By this way, you are able to reproduce the written result and check if it still is valid. Indeed, due to the DNS record requirement to check the identity of the sender, it possible that {i meta} informations from the given email are obsoletes (for any reasons). {2 As a server.} uSPF allows the end-user to craft its own record and publish it then into its primary/secondary DNS server. Multiple values exists such as: - {!val:a} - {!val:mx} - {!val:all} - {!val:pass} - or {!val:fail} They permits to describe {i via} OCaml the SPF record. It can be serialized to a simple [string] then and the user can save it into its own primary/secondary DNS server. *) type ctx (** The type for contexts. It's a {i heterogeneous map} of values to help uSPF to validate the sender. It requires the [MAILFROM] parameter given by the SMTP protocol (which can be filled {i via} {!val:with_sender}) and/or the IP address of the sender (which can be filled {i via} {!val:with_ip}). *) val empty : ctx (** [empty] is an empty context. *) val with_sender : [ `HELO of [ `raw ] Domain_name.t | `MAILFROM of Colombe.Path.t ] -> ctx -> ctx (** [with_sender v ctx] adds into the given [ctx] the sender of the incoming email (its simple domain name or the complete email address). *) val with_ip : Ipaddr.t -> ctx -> ctx (** [with_ip v ctx] adds into the given [ctx] the IP address of the sender. *) val domain : ctx -> [ `raw ] Domain_name.t option (** [domain ctx] returns the domain-name of the sender if it exists. *) val origin : ctx -> [ `HELO | `MAILFROM ] option (** [origin ctx] returns the origin of the sender (from the [HELO] SMTP command or the [MAILFROM] command). *) val merge : ctx -> ctx -> ctx option (** [merge ctx0 ctx1] merges the given contexts and ensure that they are partially equal. *) module Macro : sig type macro = [ `Literal of string | `Macro of char * (int option * bool) * string | `Macro_encoded_space | `Macro_space | `Macro_percent ] type t = macro list * string option val to_string : t -> string val pp : t Fmt.t val expand_string : ctx -> string -> ([ `raw ] Domain_name.t, [> `Msg of string ]) result end module Term : sig type t = [ `Directive of char option * [ `A of Macro.t option * (int option * int option) | `All | `Exists of Macro.t | `Include of Macro.t | `Mx of Macro.t option * (int option * int option) | `Ptr of Macro.t option | `V4 of Ipaddr.V4.Prefix.t | `V6 of Ipaddr.V6.Prefix.t ] | `Explanation of Macro.t | `Redirect of Macro.t | `Unknown of string * Macro.macro list ] list val to_string : t -> string val pp : t Fmt.t val equal : t -> t -> bool val parse_record : string -> (t, [> `Msg of string ]) result end type mechanism (** The type of mechanisms. A mechanism permits to design and identify a set of IP addresses as being permitted or not permitted to use the {!val:domain} for sending mail. *) val a : ?cidr_v4:int -> ?cidr_v6:int -> [ `raw ] Domain_name.t -> mechanism (** This mechanism matches if the sender's IP address is one of the domain-name's IP addresses. For clarity, this means the [a] mechanism also matches [AAAA] records. An address lookup is done on the domain-name using the type of lookup (A or AAAA) appropriate for the connection type. The IP is compared to the returned address(es). If any address matches, the mechanism matches. A {i Classless Inter-Domain Routing} can be applied to returned address(es) (IPv4 or IPv6) to compare with the sender's IP address. For instance, [a=10.0.0.42/32] matches only [10.0.0.42] as the sender's IP address but [a=10.0.0.42/24] matches any [10.0.0.*] addresses. By default, [cidr_v4 = 32] and [cidr_v6 = 128]. *) val all : mechanism (** The [all] mechanism is a test that always matches. It is used as the rightmost mechanism (the last mechanism) in a record to provide an explicit default. For example [v=spf1 a mx -all]. Mechanisms after [all] will never be tested. *) val exists : [ `raw ] Domain_name.t -> mechanism (** This mechanism is used to construct an arbitrary domain name that is used for a DNS A record query. It allows for complicated schemes involving arbitrary parts on the mail envelope to determine what is permitted. *) val inc : [ `raw ] Domain_name.t -> mechanism (** The [include] mechanism triggers a {i recursive} evaluation of {!val:check}: + The macro is expanded according to the given {!val:ctx} + We re-execute {!val:check} with the produced domain-name (IP and sender arguments remain the same) + The recursive evaluation returns {i match}, {i not-match} or an error. + If it returns {i match}, then the appropriate result for the [include] mechanism is used (see {!type:qualifier}) + It it returns {i not-match} or an error, the {!val:check} process tests the next mechanism. {b Note}: for instance, if the domain-name has [-all], [include] does not strictly terminates the processus. It fails and let {!val:check} to process the next mechanism. *) val mx : ?cidr_v4:int -> ?cidr_v6:int -> [ `raw ] Domain_name.t -> mechanism (** This mechanims matches if the sender's IP is one of the MX hosts for a domain-name. A domain-name should have a MX record which is an IP address. If this IP address is the same as the given IP address into the given {!type:ctx}, we consider that the sender {i matches}. {b Note}: if the domain-name has no MX record, {!val:check} does not apply the implicit MX rules by querying for an A or AAAA record for the same name. *) val v4 : Ipaddr.V4.Prefix.t -> mechanism (** This mechanism test whether the given IP from the given {!type:ctx} is contained within a given IPv4 network. *) val v6 : Ipaddr.V6.Prefix.t -> mechanism (** This mechanism test whether the given IP from the given {!type:ctx} is contained within a given IPv: network. *) type modifier (** The type of modifiers. They are not available because they mostly provide additional information which are not needed for {!val:check}. By this way, it's not needed to let the user to define some when they are not effective on the user's sender policy. *) type qualifier = | Pass | Fail | Softfail | Neutral (** The type of qualifiers. A qualifier specifies what the mechanism returns when it matches or not: - [+] returns [pass] if the mechanism matches - [-] returns [fail] if the mechanism matches - [~] returns [softfail] if the mechanism matches - [?] returns [neutral] if the mechanism matches *) val pass : mechanism -> qualifier * mechanism (** [pass m] specifies the {!type:qualifier} of the given mechanism [m]. If the mechanism {i matches} from the given {!type:ctx}, {!val:check} returns [`Pass]. Otherwise, {!val:check} tries the next mechanism. *) val fail : mechanism -> qualifier * mechanism (** [fail m] specifies the {!type:qualifier} of the given mechanism [m]. If the mechanism {i matches} from the given {!type:ctx}, {!val:check} tries the next mechanism (as it considers the current one as a failure). If the mechanism is the last one, {!val:check} returns [`Fail] so. *) val softfail : mechanism -> qualifier * mechanism (** [softfail m] specifies the {!type:qualifier} of the given mechanism [m]. If the mechanism {i matches} from the given {!type:ctx}, {!val:check} tries the next mechanism (as it considers the current one as a {i soft} failure). If the mechanism is the last one, {!val:check} returns [`Softfail] so. *) val neutral : mechanism -> qualifier * mechanism (** [neutral m] specifies the {!type:qualifier} of the given mechanism [m]. Regardless the result of the mechanism (if it matches or not), {!val:check} tries the next mechanism. If the mechanism is the last one, {!val:check} returns [`Neutral] so. *) module Record : sig type t val v : (qualifier * mechanism) list -> modifier list -> t (** [record ms []] returns a record which can be serialized into the zone file of a specific domain-name as the sender policy. *) val to_string : t -> string (** [record_to_string v] returns the serialized version of the record to be able to save it into the zone file of a domain-name as the sender policy. *) val of_string : ctx:ctx -> string -> (t, [> `Msg of string ]) result (** [record_of_string ~ctx str] tries to parse {b and} expand macro of the given string which should come from the TXT record of a domain-name as the sender policy of this domain-name. *) val pp : t Fmt.t val equal : t -> t -> bool end module Result : sig type t = [ `None | `Neutral | `Pass of mechanism | `Fail | `Softfail | `Temperror | `Permerror ] val pp : Format.formatter -> t -> unit end type error = [ `Msg of string | `No_data of [ `raw ] Domain_name.t * Dns.Soa.t | `No_domain of [ `raw ] Domain_name.t * Dns.Soa.t ] type 'a response = ('a, error) result type 'a record = 'a Dns.Rr_map.key type 'a choose = { none: (unit -> 'a t) option ; neutral: (unit -> 'a t) option ; pass: (mechanism -> 'a t) option ; fail: (unit -> 'a t) option ; softfail: (unit -> 'a t) option ; temperror: (unit -> 'a t) option ; permerror: (unit -> 'a t) option ; fn: unit -> 'a t } and 'a t = | Return : 'a -> 'a t | Request : _ Domain_name.t * 'a record * ('a response -> 'b t) -> 'b t | Tries : (unit -> unit t) list -> unit t | Map : 'a t * ('a -> 'b) -> 'b t | Choose_on : 'a choose -> 'a t exception Result of Result.t val terminate : Result.t -> 'a val get_and_check : ctx -> unit t val get : ctx -> (Term.t, [> `Msg of string ]) result t val to_field : ctx:ctx -> ?receiver:Emile.domain -> Result.t -> Mrmime.Field_name.t * Unstrctrd.t (** [to_field ~ctx ?received v] serializes as an email field the result of the sender policy check according to the given [ctx]. The user is able to prepend then its email with this field. *) module Extract : sig type result = [ `None | `Neutral | `Pass | `Fail | `Softfail | `Temperror | `Permerror ] type field = { result: result ; receiver: Emile.domain option ; sender: Emile.mailbox option ; ip: Ipaddr.t option ; ctx: ctx } type extract type decode = [ `Await of extract | `Fields of field list | `Malformed of string ] val pp : field Fmt.t val extractor : unit -> extract val extract : extract -> decode val src : extract -> string -> int -> int -> extract val of_string : string -> (field, [> `Msg of string ]) Stdlib.result val of_unstrctrd : Unstrctrd.t -> (field, [> `Msg of string ]) Stdlib.result end module Encoder : sig open Prettym val result : Prettym.ppf -> Result.t -> Prettym.ppf val comment : ctx:ctx -> ?receiver:Emile.domain -> ppf -> Result.t -> ppf val field : ctx:ctx -> ?receiver:Emile.domain -> ppf -> Result.t -> ppf end val field_received_spf : Mrmime.Field_name.t
uspf
0.2.0
MIT
https://github.com/mirage/uspf
git+https://github.com/mirage/uspf.git
dune
uspf-0.2.0/test/dune
(executable (name test_macro) (libraries logs.fmt rresult uspf alcotest)) (rule (alias runtest) (action (run ./test_macro.exe --color=always)))
uspf
0.2.0
MIT
https://github.com/mirage/uspf
git+https://github.com/mirage/uspf.git
ml
uspf-0.2.0/test/test_macro.ml
open Rresult let msg = Alcotest.testable Rresult.R.pp_msg ( = ) let ( % ) f g x = f (g x) let reporter ppf = let report src level ~over k msgf = let k _ = over () ; k () in let with_metadata header _tags k ppf fmt = Format.kfprintf k ppf ("%a[%a]: " ^^ fmt ^^ "\n%!") Logs_fmt.pp_header (level, header) Fmt.(styled `Magenta string) (Logs.Src.name src) in msgf @@ fun ?header ?tags fmt -> with_metadata header tags k ppf fmt in { Logs.report } let () = Logs.set_reporter (reporter Fmt.stdout) let () = Logs.set_level ~all:true (Some Logs.Debug) let test01 = Alcotest.test_case "rfc7208" `Quick @@ fun () -> let ctx = Uspf.empty |> Uspf.with_sender (`HELO (Domain_name.of_string_exn "mx.example.org")) |> Uspf.with_sender (`MAILFROM (Colombe.Path.of_string_exn "<strong-bad@email.example.com>")) in Alcotest.(check (result string msg)) "01" (Uspf.Macro.expand_string ctx "%{s}" >>| Domain_name.to_string) (Ok "strong-bad@email.example.com") ; Alcotest.(check (result string msg)) "02" (Uspf.Macro.expand_string ctx "%{o}" >>| Domain_name.to_string) (Ok "email.example.com") ; Alcotest.(check (result string msg)) "03" (Uspf.Macro.expand_string ctx "%{d}" >>| Domain_name.to_string) (Ok "email.example.com") ; Alcotest.(check (result string msg)) "04" (Uspf.Macro.expand_string ctx "%{d4}" >>| Domain_name.to_string) (Ok "email.example.com") ; Alcotest.(check (result string msg)) "05" (Uspf.Macro.expand_string ctx "%{d3}" >>| Domain_name.to_string) (Ok "email.example.com") ; Alcotest.(check (result string msg)) "06" (Uspf.Macro.expand_string ctx "%{d2}" >>| Domain_name.to_string) (Ok "example.com") ; Alcotest.(check (result string msg)) "07" (Uspf.Macro.expand_string ctx "%{d1}" >>| Domain_name.to_string) (Ok "com") ; Alcotest.(check (result string msg)) "08" (Uspf.Macro.expand_string ctx "%{dr}" >>| Domain_name.to_string) (Ok "com.example.email") ; Alcotest.(check (result string msg)) "09" (Uspf.Macro.expand_string ctx "%{d2r}" >>| Domain_name.to_string) (Ok "example.email") ; Alcotest.(check (result string msg)) "10" (Uspf.Macro.expand_string ctx "%{l}" >>| Domain_name.to_string) (Ok "strong-bad") ; Alcotest.(check (result string msg)) "11" (Uspf.Macro.expand_string ctx "%{l-}" >>| Domain_name.to_string) (Ok "strong.bad") ; Alcotest.(check (result string msg)) "12" (Uspf.Macro.expand_string ctx "%{lr}" >>| Domain_name.to_string) (Ok "strong-bad") ; Alcotest.(check (result string msg)) "13" (Uspf.Macro.expand_string ctx "%{lr-}" >>| Domain_name.to_string) (Ok "bad.strong") ; Alcotest.(check (result string msg)) "14" (Uspf.Macro.expand_string ctx "%{l1r-}" >>| Domain_name.to_string) (Ok "strong") let test02 = Alcotest.test_case "rfc7208" `Quick @@ fun () -> let ctx = Uspf.empty |> Uspf.with_ip (Ipaddr.of_string_exn "192.0.2.3") |> Uspf.with_sender (`HELO (Domain_name.of_string_exn "mx.example.org")) |> Uspf.with_sender (`MAILFROM (Colombe.Path.of_string_exn "<strong-bad@email.example.com>")) in Alcotest.(check (result string msg)) "01" (Uspf.Macro.expand_string ctx "%{ir}.%{v}._spf.%{d2}" >>| Domain_name.to_string) (Ok "3.2.0.192.in-addr._spf.example.com") ; Alcotest.(check (result string msg)) "02" (Uspf.Macro.expand_string ctx "%{lr-}.lp._spf.%{d2}" >>| Domain_name.to_string) (Ok "bad.strong.lp._spf.example.com") ; Alcotest.(check (result string msg)) "03" (Uspf.Macro.expand_string ctx "%{ir}.%{v}.%{l1r-}.lp._spf.%{d2}" >>| Domain_name.to_string) (Ok "3.2.0.192.in-addr.strong.lp._spf.example.com") ; Alcotest.(check (result string msg)) "04" (Uspf.Macro.expand_string ctx "%{d2}.trusted-domains.example.net" >>| Domain_name.to_string) (Ok "example.com.trusted-domains.example.net") ; let ctx = Uspf.with_ip (Ipaddr.of_string_exn "2001:db8::cb01") ctx in Alcotest.(check (result string msg)) "05" (Uspf.Macro.expand_string ctx "%{ir}.%{v}._spf.%{d2}" >>| Domain_name.to_string) (Ok "1.0.b.c.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6._spf.example.com") let test03 = Alcotest.test_case "record" `Quick @@ fun () -> let record = "v=spf1 ip4:184.104.202.128/27 ip4:184.104.202.96/27 ip4:216.218.159.0/27 \ ip4:216.218.240.64/26 ip4:64.71.168.192/26 ip4:65.19.128.64/26 \ ip4:66.220.12.128/27 ip4:72.52.80.0/26 ip4:64.62.250.96/27 \ ip6:2001:470:1:235::/64 ip6:2001:470:1:258::/64 ip6:2001:470:1:3a8::/64 \ ip6:2001:470:1:59e::/64 ip6:2001:470:1:669::/64 ip6:2001:470:1:791::/64 \ ip6:2001:470:1:9a5::/64 ip6:2001:470:1:9f1::/64 \ ip6:2602:fd3f:0000:ff06::/64 include:mailgun.org mx ptr ~all" in match Uspf.Term.parse_record record with | Ok _ -> () | Error (`Msg err) -> Alcotest.failf "%s." err let test04 = Alcotest.test_case "record" `Quick @@ fun () -> let ipv4_0 = Uspf.(pass @@ v4 (Ipaddr.V4.Prefix.of_string_exn "192.168.0.0/24")) in let ipv4_1 = Uspf.(pass @@ v4 (Ipaddr.V4.Prefix.of_string_exn "10.0.0.0/24")) in let reject = Uspf.(fail all) in let record = Uspf.Record.v [ ipv4_0; ipv4_1; reject ] [] in let str = Uspf.Record.to_string record in Alcotest.(check string) "record" str "ip4:192.168.0.0/24 ip4:10.0.0.0/24 -all" type getrrecord = { fn: 'a 'r. 'a Domain_name.t -> 'r Dns.Rr_map.key -> 'r Uspf.response } let eval : type a. getrrecord:getrrecord -> a Uspf.t -> Uspf.Result.t option = fun ~getrrecord t -> let rec go : type a. a Uspf.t -> a = function | Request (domain_name, record, fn) -> Logs.debug (fun m -> m "DNS request on %a" Domain_name.pp domain_name) ; let resp = getrrecord.fn domain_name record in go (fn resp) | Return v -> v | Tries fns -> List.iter (fun fn -> go (fn ())) fns | Map (x, fn) -> fn (go x) | Choose_on c -> try go (c.fn ()) with Uspf.Result result -> let none _ = Uspf.terminate result in let some = Fun.id in let fn = match result with | `None -> Option.fold ~none ~some c.none | `Neutral -> Option.fold ~none ~some c.neutral | `Fail -> Option.fold ~none ~some c.fail | `Softfail -> Option.fold ~none ~some c.softfail | `Temperror -> Option.fold ~none ~some c.temperror | `Permerror -> Option.fold ~none ~some c.permerror | `Pass m -> begin fun () -> match c.pass with Some pass -> pass m | None -> none () end in go (fn ()) in match go t with exception Uspf.Result result -> Some result | _ -> None let test05 = Alcotest.test_case "mx optional domain name" `Quick @@ fun () -> let getrrecord : type a r. a Domain_name.t -> r Dns.Rr_map.key -> r Uspf.response = fun domain_name record -> let _192_168_1_1 = Ipaddr.V4.(Set.singleton (of_string_exn "192.168.1.1")) in let mxs = Dns.Rr_map.Mx_set.singleton { Dns.Mx.preference= 10 ; mail_exchange= Domain_name.(host_exn (of_string_exn "mail.bar.com")) } in match (record, Domain_name.to_string domain_name) with | Dns.Rr_map.Txt, "bar.com" -> Ok (0l, Dns.Rr_map.Txt_set.singleton "v=spf1 mx a:foo.com -all") | Dns.Rr_map.A, "mail.bar.com" -> Ok (0l, _192_168_1_1) | Dns.Rr_map.Mx, "bar.com" -> Ok (0l, mxs) | _ -> R.error_msgf "Error on %a:%a." Dns.Rr_map.ppk (Dns.Rr_map.K record) Domain_name.pp domain_name in let getrrecord = { fn= getrrecord } in let ctx = Uspf.empty |> Uspf.with_sender (`HELO (Domain_name.of_string_exn "bar.com")) |> Uspf.with_sender (`MAILFROM (Colombe.Path.of_string_exn "<x@bar.com>")) |> Uspf.with_ip (Ipaddr.of_string_exn "192.168.1.1") in let result = eval ~getrrecord (Uspf.get_and_check ctx) in match result with | Some (`Pass _) -> Alcotest.(check pass) "spf" () () | Some result -> Alcotest.failf "Invalid SPF result: %a" Uspf.Result.pp result | None -> Alcotest.failf "Impossible to compute a result" let () = Alcotest.run "decoding" [ ("macro", [ test01; test02 ]); ("record", [ test03; test04 ]) ; ("spf", [ test05 ]) ]
uspf
0.2.0
MIT
https://github.com/mirage/uspf
git+https://github.com/mirage/uspf.git
opam
uspf-0.2.0/uspf-lwt.opam
version: "0.2.0" opam-version: "2.0" name: "uspf" maintainer: "Romain Calascibetta <romain.calascibetta@gmail.com>" authors: "Romain Calascibetta <romain.calascibetta@gmail.com>" homepage: "https://github.com/mirage/uspf" bug-reports: "https://github.com/mirage/uspf/issues" dev-repo: "git+https://github.com/mirage/uspf.git" doc: "https://mirage.github.io/uspf/" license: "MIT" synopsis: "SPF implementation in OCaml (with LWT)" description: """uspf-lwt is an implementation of the SPF verifier in OCaml compatible with MirageOS. It uses LWT as the scheduler.""" build: [ "dune" "build" "-p" name "-j" jobs ] run-test: [ "dune" "runtest" "-p" name "-j" jobs ] depends: [ "ocaml" {>= "4.12.0"} "dune" {>= "2.8.0"} "uspf" {= version} "lwt" "dns-client-lwt" "alcotest" {with-test} "rresult" {>= "0.7.0" & with-test} ] x-maintenance-intent: [ "(latest)" ]
uspf
0.2.0
MIT
https://github.com/mirage/uspf
git+https://github.com/mirage/uspf.git
opam
uspf-0.2.0/uspf-mirage.opam
version: "0.2.0" opam-version: "2.0" name: "uspf" maintainer: "Romain Calascibetta <romain.calascibetta@gmail.com>" authors: "Romain Calascibetta <romain.calascibetta@gmail.com>" homepage: "https://github.com/mirage/uspf" bug-reports: "https://github.com/mirage/uspf/issues" dev-repo: "git+https://github.com/mirage/uspf.git" doc: "https://mirage.github.io/uspf/" license: "MIT" synopsis: "SPF implementation in OCaml (with for Mirage)" description: """uspf-mirage is an implementation of the SPF verifier in OCaml compatible with MirageOS. It uses LWT as the scheduler.""" build: [ "dune" "build" "-p" name "-j" jobs ] run-test: [ "dune" "runtest" "-p" name "-j" jobs ] depends: [ "ocaml" {>= "4.12.0"} "dune" {>= "2.8.0"} "uspf" {= version} "lwt" "dns-client-mirage" "alcotest" {with-test} "rresult" {>= "0.7.0" & with-test} ] x-maintenance-intent: [ "(latest)" ]
uspf
0.2.0
MIT
https://github.com/mirage/uspf
git+https://github.com/mirage/uspf.git
opam
uspf-0.2.0/uspf.opam
version: "0.2.0" opam-version: "2.0" name: "uspf" maintainer: "Romain Calascibetta <romain.calascibetta@gmail.com>" authors: "Romain Calascibetta <romain.calascibetta@gmail.com>" homepage: "https://github.com/mirage/uspf" bug-reports: "https://github.com/mirage/uspf/issues" dev-repo: "git+https://github.com/mirage/uspf.git" doc: "https://mirage.github.io/uspf/" license: "MIT" synopsis: "SPF implementation in OCaml" description: """uspf is an implementation of the SPF verifier in OCaml compatible with MirageOS.""" build: [ "dune" "build" "-p" name "-j" jobs ] run-test: [ "dune" "runtest" "-p" name "-j" jobs ] depends: [ "ocaml" {>= "4.12.0"} "dune" {>= "2.8.0"} "logs" "colombe" {>= "0.4.2"} "mrmime" {>= "0.5.0"} "ipaddr" {>= "5.2.0"} "hmap" "angstrom" {>= "0.15.0"} "domain-name" "dns" {>= "5.0.1"} "lwt" "dns-client" {>= "6.1.0"} "fmt" {>= "0.8.9"} "alcotest" {with-test} "rresult" {>= "0.7.0" & with-test} ] x-maintenance-intent: [ "(latest)" ]
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
opam
cohttp-6.2.1/cohttp-async.opam
version: "6.2.1" # This file is generated by dune, edit dune-project instead opam-version: "2.0" synopsis: "CoHTTP implementation for the Async concurrency library" description: """ An implementation of an HTTP client and server using the Async concurrency library. See the `Cohttp_async` module for information on how to use this. The package also installs `cohttp-curl-async` and a `cohttp-server-async` binaries for quick uses of a HTTP(S) client and server respectively. """ maintainer: ["Anil Madhavapeddy <anil@recoil.org>"] authors: [ "Anil Madhavapeddy" "Stefano Zacchiroli" "David Sheets" "Thomas Gazagnaire" "David Scott" "Rudi Grinberg" "Andy Ray" "Anurag Soni" ] license: "ISC" homepage: "https://github.com/mirage/ocaml-cohttp" doc: "https://mirage.github.io/ocaml-cohttp/" bug-reports: "https://github.com/mirage/ocaml-cohttp/issues" depends: [ "dune" {>= "3.8"} "ocaml" {>= "4.14" & < "5.3.0"} "http" {= version} "cohttp" {= version} "async_kernel" {>= "v0.17.0"} "async_unix" {>= "v0.16.0"} "async" {>= "v0.16.0"} "base" {>= "v0.16.0"} "core" {with-test} "core_unix" {>= "v0.14.0"} "conduit-async" {>= "1.2.0"} "magic-mime" "digestif" {with-test} "logs" "fmt" {>= "0.8.2"} "sexplib0" "ppx_sexp_conv" {>= "v0.13.0"} "ounit2" {with-test} "uri" {>= "2.0.0"} "uri-sexp" "ipaddr" "odoc" {with-doc} ] dev-repo: "git+https://github.com/mirage/ocaml-cohttp.git" build: [ ["dune" "subst"] {dev} [ "dune" "build" "-p" name "-j" jobs "@install" "@cohttp-async/runtest" {with-test} "@doc" {with-doc} ] ] available: arch != "s390x" x-maintenance-intent: [ "(latest)" ]
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-async/bin/cohttp_curl_async.ml
(*{{{ Copyright (c) 2014 Anil Madhavapeddy <anil@recoil.org> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * }}}*) open Base open Async_kernel module Body = Cohttp_async.Body module Client = Cohttp_async.Client let show_headers h = Cohttp.Header.iter (fun k v -> Logs.info (fun m -> m "%s: %s%!" k v)) h let make_net_req uri meth' body () = let meth = Cohttp.Code.method_of_string meth' in let uri = Uri.of_string uri in let headers = Cohttp.Header.of_list [ ("connection", "close") ] in Client.call meth ~headers ~body:Body.(of_string body) uri >>= fun (res, body) -> show_headers (Http.Response.headers res); body |> Body.to_pipe |> Pipe.iter ~f:(fun b -> Stdlib.print_string b; return ()) let _ = (* enable logging to stdout *) Fmt_tty.setup_std_outputs (); Logs.set_level @@ Some Logs.Debug; Logs.set_reporter (Logs_fmt.reporter ()); let open Async_command in async_spec ~summary:"Fetch URL and print it" Spec.( empty +> anon ("url" %: string) +> flag "-X" (optional_with_default "GET" string) ~doc:" Set HTTP method" +> flag "data-binary" (optional_with_default "" string) ~doc:" Data to send when using POST") make_net_req |> Command_unix.run
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-async/bin/cohttp_server_async.ml
(*{{{ Copyright (c) 2013 Anil Madhavapeddy <anil@recoil.org> * Copyright (c) 2014 David Sheets <sheets@alum.mit.edu> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * }}}*) open Base open Async_kernel open Async_unix module Server = Cohttp_async.Server open Cohttp_server let method_filter meth (res, body) = match meth with `HEAD -> return (res, `Empty) | _ -> return (res, body) let serve_file ~docroot ~uri = Cohttp.Path.resolve_local_file ~docroot ~uri |> Server.respond_with_file let serve ~info ~docroot ~index uri path = (* Get a canonical filename from the URL and docroot *) let file_name = Cohttp.Path.resolve_local_file ~docroot ~uri in try_with (fun () -> Unix.stat file_name >>= fun stat -> Logs.debug (fun f -> f "%s" (Sexp.to_string_hum (Unix.Stats.sexp_of_t stat))); match stat.Unix.Stats.kind with (* Get a list of current files and map to HTML *) | `Directory -> ( let path_len = String.length path in if Int.(path_len <> 0) && Char.(path.[path_len - 1] <> '/') then Server.respond_with_redirect (Uri.with_path uri (path ^ "/")) (* Check if the index file exists *) else Sys.file_exists (file_name / index) >>= function | `Yes -> (* Serve the index file directly *) let uri = Uri.with_path uri (path / index) in serve_file ~docroot ~uri | `No | `Unknown -> (* Do a directory listing *) Sys.ls_dir file_name >>= Deferred.List.map ~how:`Parallel ~f:(fun f -> let file_name = file_name / f in try_with (fun () -> Unix.stat file_name >>| fun stat -> (Some stat.Unix.Stats.kind, stat.Unix.Stats.size, f)) >>| function | Ok v -> v | Error _ -> (None, 0L, f)) >>= fun listing -> html_of_listing uri path (sort ((Some `Directory, 0L, "..") :: listing)) info |> Server.respond_string) (* Serve the local file contents *) | `File -> serve_file ~docroot ~uri (* Any other file type is simply forbidden *) | `Socket | `Block | `Fifo | `Char | `Link -> Server.respond_string ~status:`Forbidden (html_of_forbidden_unnormal path info)) >>= function | Ok res -> return res | Error exn -> ( match Monitor.extract_exn exn with | Unix.Unix_error (Unix.Error.ENOENT, "stat", p) -> if String.equal p ("((filename " ^ file_name ^ "))") (* Really? *) then Server.respond_string ~status:`Not_found (html_of_not_found path info) else raise exn | _ -> raise exn) (** HTTP handler *) let handler ~info ~docroot ~index ~body:_ _sock req = let uri = Cohttp.Request.uri req in let path = Uri.path uri in (* Log the request to the console *) printf "%s %s%!" Http.(Method.to_string (Request.meth req)) path; match Http.Request.meth req with | (`GET | `HEAD) as meth -> serve ~info ~docroot ~index uri path >>= method_filter meth | meth -> let meth = Http.Method.to_string meth in let allowed = "GET, HEAD" in let headers = Http.Header.of_list [ ("allow", allowed) ] in Server.respond_string ~headers ~status:`Method_not_allowed (html_of_method_not_allowed meth allowed path info) let determine_mode cert_file_path key_file_path = (* Determines if the server runs in http or https *) match (cert_file_path, key_file_path) with | Some c, Some k -> `OpenSSL (`Crt_file_path c, `Key_file_path k) | None, None -> `TCP | _ -> failwith "Error: must specify both certificate and key for HTTPS" let start_server docroot port index cert_file key_file verbose () = (* enable logging to stdout *) Fmt_tty.setup_std_outputs (); Logs.set_level @@ if verbose then Some Logs.Debug else Some Logs.Info; Logs.set_reporter (Logs_fmt.reporter ()); let mode = determine_mode cert_file key_file in let mode_str = match mode with `OpenSSL _ -> "HTTPS" | `TCP -> "HTTP" in Logs.info (fun f -> f "Listening for %s requests on %d" mode_str port); let info = Printf.sprintf "Served by Cohttp/Async listening on %d" port in Server.create ~on_handler_error: (`Call (fun addr exn -> Logs.err (fun f -> f "Error from %s" (Socket.Address.to_string addr)); Logs.err (fun f -> f "%s" @@ Exn.to_string exn))) ~mode (Tcp.Where_to_listen.of_port port) (handler ~info ~docroot ~index) >>= fun _serv -> Deferred.never () let () = let open Async_command in Command_unix.run @@ async_spec ~summary:"Serve the local directory contents via HTTP or HTTPS" Spec.( empty +> anon (maybe_with_default "." ("docroot" %: string)) +> flag "-p" (optional_with_default 8080 int) ~doc:"port TCP port to listen on" +> flag "-i" (optional_with_default "index.html" string) ~doc:"file Name of index file in directory" +> flag "-cert-file" (optional string) ~doc:"File of cert for https" +> flag "-key-file" (optional string) ~doc:"File of private key for https" +> flag "-v" no_arg ~doc:" Verbose logging output to console") start_server
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
dune
cohttp-6.2.1/cohttp-async/bin/dune
(executables (names cohttp_curl_async cohttp_server_async) (libraries cohttp-async async_kernel async.async_command async_unix base cohttp cohttp_server fmt.tty core_unix.command_unix))
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
dune
cohttp-6.2.1/cohttp-async/examples/dune
(executables (names hello_world receive_post) (libraries digestif.c http cohttp-async base async_kernel core_unix.command_unix)) (alias (name runtest) (package cohttp-async) (deps hello_world.exe receive_post.exe))
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-async/examples/hello_world.ml
(* This file is in the public domain *) open Core open Async_kernel module Server = Cohttp_async.Server (* given filename: hello_world.ml compile with: $ corebuild hello_world.native -pkg cohttp.async *) let handler ~body:_ _sock req = let uri = Cohttp.Request.uri req in match Uri.path uri with | "/test" -> Uri.get_query_param uri "hello" |> Option.map ~f:(fun v -> "hello: " ^ v) |> Option.value ~default:"No param hello supplied" |> Server.respond_string | _ -> Server.respond_string ~status:`Not_found "Route not found" let start_server port () = Stdlib.Printf.eprintf "Listening for HTTP on port %d\n" port; Stdlib.Printf.eprintf "Try 'curl http://localhost:%d/test?hello=xyz'\n%!" port; Server.create ~on_handler_error:`Raise (Async.Tcp.Where_to_listen.of_port port) handler >>= fun server -> Deferred.forever () (fun () -> after Time_ns.Span.(of_sec 0.5) >>| fun () -> Async.Log.Global.printf "Active connections: %d" (Server.num_connections server)); Deferred.never () let () = let module Command = Async_command in Command.async_spec ~summary:"Start a hello world Async server" Command.Spec.( empty +> flag "-p" (optional_with_default 8080 int) ~doc:"int Source port to listen on") start_server |> Command_unix.run
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-async/examples/receive_post.ml
(* This file is in the public domain *) open Base open Async_kernel module Body = Cohttp_async.Body module Server = Cohttp_async.Server (* compile with: $ corebuild receive_post.native -pkg cohttp.async *) let start_server port () = Stdlib.Printf.eprintf "Listening for HTTP on port %d\n" port; Stdlib.Printf.eprintf "Try 'curl -X POST -d 'foo bar' http://localhost:%d\n" port; Cohttp_async.Server.create ~on_handler_error:`Raise (Async.Tcp.Where_to_listen.of_port port) (fun ~body _ req -> match req |> Http.Request.meth with | `POST -> Body.to_string body >>= fun body -> Stdlib.Printf.eprintf "Body: %s" body; Server.respond `OK | _ -> Server.respond `Method_not_allowed) >>= fun _ -> Deferred.never () let () = let module Command = Async_command in Command.async_spec ~summary:"Simple http server that outputs body of POST's" Command.Spec.( empty +> flag "-p" (optional_with_default 8080 int) ~doc:"int Source port to listen on") start_server |> Command_unix.run
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-async/examples/s3_cp.ml
(*{{{ Copyright (C) 2015 Trevor Smith <trevorsummerssmith@gmail.com> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * }}}*) (** This example is here to show how to get and put to s3 using the async client code. This hopes to be a useful example because: 1) it is a real world use of the client 2) s3 auth requires a bit of fiddling with the headers hopefully this is illustative for anyone else doing the same The reader will want to be familiar with the S3 API Documentation found here: http://docs.aws.amazon.com/AmazonS3/latest/API/Welcome.html This example was written using the API Version 2006-03-01. There are two ways to authenticate with S3, this example uses the authorization header approach (p. 19 of the api reference). Downloads from S3 are done using the GET method, and uploads are done using the PUT method. To get this to work, you'll need an AWS access/secret key pair that has the "s3:GetObject" and "s3:PutObject" permissions enabled for the bucket you are interacting with. As this is an example, straightforwardness is prized. One should not use this for a production system, nor assume that it offers a good example of abstraction, interface design or error handling. *) open Base open Core open Async module Time = Time_float (* open Cohttp *) module Client = Cohttp_async.Client module Body = Cohttp_async.Body let ksrt (k, _) (k', _) = String.compare k k' module Compat = struct (** Things we need to make this happen that, ideally, we'd like other libraries to provide and that are orthogonal to the example here *) let encode_string s = (* Percent encode the path as s3 wants it. Uri doesn't encode $, or the other sep characters in a path. If upstream allows that we can nix this function *) let n = String.length s in let buf = Buffer.create (n * 3) in for i = 0 to n - 1 do let c = s.[i] in match c with | 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '_' | '-' | '~' | '.' | '/' -> Buffer.add_char buf c | '%' -> (* Sigh. Annoying we're expecting already escaped strings so ignore the escapes *) let is_hex = function | 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' -> true | _ -> false in if i + 2 < n then if is_hex s.[i + 1] && is_hex s.[i + 2] then Buffer.add_char buf c else Buffer.add_string buf "%25" | _ -> Buffer.add_string buf (Printf.sprintf "%%%X" (Char.to_int c)) done; Buffer.contents buf let hexa = "0123456789abcdef" let of_char c = let x = Char.to_int c in (hexa.[x lsr 4], hexa.[x land 0xf]) let cstruct_to_hex_string cs = let open Cstruct in let n = cs.len in let buf = Buffer.create (n * 2) in for i = 0 to n - 1 do let c = cs.buffer.{cs.off + i} in let x, y = of_char c in Buffer.add_char buf x; Buffer.add_char buf y done; Buffer.contents buf let encode_query_string uri = (* Sort and encode query string. Note that AWS wants null keys to have '=' for all keys. URI.encoded_of_query encodes [""] as ?a=, and [] as ?a. *) Uri.query uri |> List.sort ~compare:ksrt |> List.map ~f:(fun (k, v) -> (k, match v with [] -> [ "" ] | x -> x)) |> Uri.encoded_of_query let format_time t = (* Core.Std.Time doesn't have a format function that takes a timezone *) let d, s = Time.to_date_ofday ~zone:Time.Zone.utc t in let open Time.Span.Parts in let { hr; min; sec; _ } = Time.Ofday.to_parts s in Printf.sprintf "%sT%.2d%.2d%.2dZ" (Date.to_string_iso8601_basic d) hr min sec end type region = [ `Ap_northeast_1 (* Asia Pacific (Tokyo) *) | `Ap_southeast_1 (* Asia Pacific (Singapore) *) | `Ap_southeast_2 (* Asia Pacific (Sydney) *) | `Eu_central_1 (* EU (Frankfurt) *) | `Eu_west_1 (* EU (Ireland) *) | `Sa_east_1 (* South America (Sao Paulo) *) | `Us_east_1 (* US East (N. Virginia) *) | `Us_west_1 (* US West (N. California) *) | `Us_west_2 (* US West (Oregon) *) ] [@@deriving sexp] let region_of_string = function | "ap-northeast-1" -> `Ap_northeast_1 | "ap-southeast-1" -> `Ap_southeast_1 | "ap-southeast-2" -> `Ap_southeast_2 | "eu-central-1" -> `Eu_central_1 | "eu-west-1" -> `Eu_west_1 | "sa-east-1" -> `Sa_east_1 | "us-east-1" -> `Us_east_1 | "us-west-1" -> `Us_west_1 | "us-west-2" -> `Us_west_2 | s -> raise (Invalid_argument ("region_of_string: " ^ s)) let string_of_region = function | `Ap_northeast_1 -> "ap-northeast-1" | `Ap_southeast_1 -> "ap-southeast-1" | `Ap_southeast_2 -> "ap-southeast-2" | `Eu_central_1 -> "eu-central-1" | `Eu_west_1 -> "eu-west-1" | `Sa_east_1 -> "sa-east-1" | `Us_east_1 -> "us-east-1" | `Us_west_1 -> "us-west-1" | `Us_west_2 -> "us-west-2" let region_host_string = function | `Ap_northeast_1 -> "s3-ap-northeast-1.amazonaws.com" | `Ap_southeast_1 -> "s3-ap-southeast-1.amazonaws.com" | `Ap_southeast_2 -> "s3-ap-southeast-2.amazonaws.com" | `Eu_central_1 -> "s3-eu-central-1.amazonaws.com" | `Eu_west_1 -> "s3-eu-west-1.amazonaws.com" | `Sa_east_1 -> "s3-sa-east-1.amazonaws.com" | `Us_east_1 -> "s3.amazonaws.com" | `Us_west_1 -> "s3-us-west-1.amazonaws.com" | `Us_west_2 -> "s3-us-west-2.amazonaws.com" type service = [ `S3 ] [@@deriving sexp] let string_of_service = function `S3 -> "s3" module Auth = struct (** AWS S3 Authorization *) let digest s = (* string -> sha256 as a hex string *) Digestif.SHA256.(digest_string s |> to_hex) let make_amz_headers ?body time = (* Return x-amz-date and x-amz-sha256 headers *) let hashed_payload = match body with | None -> "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" | Some s -> digest s in ( [ ("x-amz-content-sha256", hashed_payload); ("x-amz-date", Compat.format_time time); ], hashed_payload ) let canonical_request hashed_payload (request : Http.Request.t) = (* This corresponds to p.21 of the s3 api doc we're making: <HTTPMethod>\n <CanonicalURI>\n <CanonicalQueryString>\n <CanonicalHeaders>\n <SignedHeaders>\n <HashedPayload> *) let http_method = Http.Method.to_string request.meth in (* Nb the path will be url encoded as per spec *) let uri = Cohttp.Request.uri request in let canoncical_uri = Compat.encode_string (Uri.path uri) in (* Sort query string in alphabetical order by key *) let canonical_query = Compat.encode_query_string uri in let sorted_headers = Http.Header.to_list request.headers |> List.sort ~compare:ksrt in let canonical_headers = sorted_headers |> List.fold ~init:"" ~f:(fun acc (k, v) -> acc ^ Printf.sprintf "%s:%s\n" (String.lowercase k) (String.strip v)) in let signed_headers = sorted_headers |> List.map ~f:(fun (k, _) -> k) |> String.concat ~sep:";" in ( Printf.sprintf "%s\n%s\n%s\n%s\n%s\n%s" http_method canoncical_uri canonical_query canonical_headers signed_headers hashed_payload, signed_headers ) let string_to_sign ?time ~scope ~service canonical_request : string = (* As per p. 23 of s3 api doc. The requests need current time in utc time parameter is there for testing. *) let time_str = match time with | None -> Time.to_string_abs ~zone:Time.Zone.utc (Time.now ()) | Some t -> Compat.format_time t in let scope_date, scope_region = scope in let scope_str = Printf.sprintf "%s/%s/%s/aws4_request" (Date.to_string_iso8601_basic scope_date) (string_of_region scope_region) (string_of_service service) in let hashed_req = digest canonical_request in Printf.sprintf "AWS4-HMAC-SHA256\n%s\n%s\n%s" time_str scope_str hashed_req let make_signing_key ?date ~region ~service ~secret_access_key () = let mac k v = Digestif.SHA256.(hmac_string ~key:k v |> to_raw_string) in let date' = match date with None -> Date.today ~zone:Time.Zone.utc | Some d -> d in let date_str = Date.to_string_iso8601_basic date' in let date_key = mac ("AWS4" ^ secret_access_key) date_str in let date_region_key = mac date_key (string_of_region region) in let date_region_service_key = mac date_region_key (string_of_service service) in let signing_key = mac date_region_service_key "aws4_request" in signing_key let auth_request ?now ~hashed_payload ~region ~service ~aws_access_key ~aws_secret_key request = (* Important use the same time for everything here *) let time = Option.value ~default:(Time.now ()) now in let date = Time.to_date ~zone:Time.Zone.utc time in let canonical_request, signed_headers = canonical_request hashed_payload request in let string_to_sign = string_to_sign ~time ~scope:(date, region) ~service canonical_request in let signing_key = make_signing_key ~date ~region ~service ~secret_access_key:aws_secret_key () in let creds = Printf.sprintf "%s/%s/%s/%s/aws4_request" aws_access_key (Date.to_string_iso8601_basic date) (string_of_region region) (string_of_service service) in let signature = Digestif.SHA256.(hmac_string ~key:signing_key string_to_sign |> to_hex) in let auth_header = Printf.sprintf "AWS4-HMAC-SHA256 Credential=%s,SignedHeaders=%s,Signature=%s" creds signed_headers signature in [ ("Authorization", auth_header) ] end module S3 = struct type conf = { region : region; aws_access_key : string; aws_secret_key : string; } [@@deriving sexp] let make_request ?body conf ~meth ~bucket ~object_ = let host_str = region_host_string conf.region in let uri = Printf.sprintf "https://%s/%s/%s" host_str bucket object_ |> Uri.of_string in let time = Time.now () in (* If PUT add content length *) let headers = match meth with | `PUT -> let length = Option.value_map ~f:String.length ~default:0 body in [ ("Content-length", Int.to_string length) ] | _ -> [] in let headers = headers @ [ ("Host", host_str) ] in let amz_headers, hashed_payload = Auth.make_amz_headers time ?body in let headers = headers @ amz_headers in let request = Cohttp.Request.make ~meth ~headers:(Http.Header.of_list headers) uri in let auth_header = Auth.auth_request ~now:time ~hashed_payload ~region:conf.region ~service:`S3 ~aws_access_key:conf.aws_access_key ~aws_secret_key:conf.aws_secret_key request in let headers = headers @ auth_header |> Http.Header.of_list in let request = { request with Cohttp.Request.headers } in match meth with | `PUT -> Client.request ~body:(Option.value_map ~f:Body.of_string ~default:`Empty body) request | `GET -> Client.request request | _ -> failwith "not possible right now" end type s3path = { bucket : string; object_ : string } type cmd = S3toLocal of s3path * string | LocaltoS3 of string * s3path let determine_s3_parts s = (* Takes: string of the form s3://<bucket>/<object_> *) let s = String.drop_prefix s 5 in let parts = String.split ~on:'/' s in match parts with | bucket :: rst -> { bucket; object_ = String.concat ~sep:"/" rst } | _ -> failwith "error format must be 's3://<bucket>/<object_>'" let determine_paths src dst = let is_s3 s = String.is_prefix ~prefix:"s3://" s in match (is_s3 src, is_s3 dst) with | true, false -> S3toLocal (determine_s3_parts src, dst) | false, true -> LocaltoS3 (src, determine_s3_parts dst) | false, false -> failwith "Use cp(1) :)" | true, true -> failwith "Does not support copying from s3 to s3" let main region_str aws_access_key aws_secret_key src dst () = (* nb client does not support redirects or preflight 100 *) let open S3 in let region = region_of_string region_str in let conf = { region; aws_access_key; aws_secret_key } in match determine_paths src dst with | S3toLocal (src, dst) -> ( make_request conf ~meth:`GET ~bucket:src.bucket ~object_:src.object_ >>= fun (resp, body) -> match Http.Response.(resp.status) with | #Http.Status.success -> Body.to_string body >>| fun s -> Out_channel.with_file ~f:(fun oc -> Out_channel.output_string oc s) dst; Core.Printf.printf "Wrote s3://%s to %s\n" (src.bucket ^ src.object_) dst | _ -> Core.Printf.printf "Error: %s\n" (Sexp.to_string (Cohttp.Response.sexp_of_t resp)); return ()) | LocaltoS3 (src, dst) -> ( let body = In_channel.with_file src ~f:(fun ic -> In_channel.input_all ic) in make_request ~body conf ~meth:`PUT ~bucket:dst.bucket ~object_:dst.object_ >>= fun (resp, body) -> match Http.Response.status resp with | #Http.Status.success -> Core.Printf.printf "Wrote %s to s3://%s\n" src (dst.bucket ^ dst.object_); return () | _ -> Body.to_string body >>| fun s -> Core.Printf.printf "Error: %s\n%s\n" (Sexp.to_string (Cohttp.Response.sexp_of_t resp)) s) let () = let open Async_command in async_spec ~summary:"Simple command line client that copies files to/from S3" Spec.( empty +> flag "-r" (optional_with_default "us-east-1" string) ~doc:"string AWS Region" +> anon ("aws_access_key" %: string) +> anon ("aws_secret_key" %: string) +> anon ("src" %: string) +> anon ("dst" %: string)) main |> Command_unix.run
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-async/src/body.ml
open Base open Async_kernel module B = Cohttp.Body type t = [ B.t | `Pipe of string Pipe.Reader.t ] [@@deriving sexp_of] let empty = `Empty let of_string s = (B.of_string s :> t) let of_pipe p = `Pipe p let to_string = function | #B.t as body -> return (B.to_string body) | `Pipe s -> Pipe.to_list s >>| String.concat let to_string_list = function | #B.t as body -> return (B.to_string_list body) | `Pipe s -> Pipe.to_list s let drain = function #B.t -> return () | `Pipe p -> Pipe.drain p let is_empty (body : t) = match body with | #B.t as body -> if B.is_empty body then `True else `False | `Pipe _ -> `Unknown let to_pipe = function | `Empty -> Pipe.of_list [] | `String s -> Pipe.singleton s | `Strings sl -> Pipe.of_list sl | `Pipe p -> p let disable_chunked_encoding = function | #B.t as body -> return (body, B.length body) | `Pipe s -> Pipe.to_list s >>| fun l -> let body = `Strings l in let len = B.length body in (body, len) let transfer_encoding = function | #B.t as t -> B.transfer_encoding t | `Pipe _ -> Cohttp.Transfer.Chunked let of_string_list strings = `Strings strings let map t ~f = match t with | #B.t as t -> (B.map f t :> t) | `Pipe p -> `Pipe (Pipe.map p ~f) let as_pipe t ~f = `Pipe (t |> to_pipe |> f) let to_form t = to_string t >>| Uri.query_of_encoded let of_form ?scheme f = Uri.encoded_of_query ?scheme f |> of_string let write_body write_body (body : t) writer = match body with | `Empty -> return () | `String s -> write_body writer s | `Strings sl -> Deferred.List.iter ~how:`Sequential sl ~f:(write_body writer) | `Pipe p -> Pipe.iter p ~f:(write_body writer) let pipe_of_body read_chunk ic = Pipe.create_reader ~close_on_exception:false (fun writer -> Deferred.repeat_until_finished () (fun () -> read_chunk ic >>= function | Cohttp.Transfer.Chunk buf -> (* Even if [writer] has been closed, the loop must continue reading * from the input channel to ensure that it is left in a proper state * for the next request to be processed (in the case of keep-alive). * * The only case where [writer] will be closed is when * [Pipe.close_read] has been called on its read end. This could be * done by a request handler to signal that it does not need to * inspect the remainder of the body to fulfill the request. *) Pipe.write_when_ready writer ~f:(fun write -> write buf) >>| fun _ -> `Repeat () | Final_chunk buf -> Pipe.write_when_ready writer ~f:(fun write -> write buf) >>| fun _ -> `Finished () | Done -> return (`Finished ()))) module Private = struct let write_body = write_body let pipe_of_body = pipe_of_body let disable_chunked_encoding = disable_chunked_encoding let drain = drain end
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
mli
cohttp-6.2.1/cohttp-async/src/body.mli
open! Base open! Async_kernel type t = [ Cohttp.Body.t | `Pipe of string Pipe.Reader.t ] [@@deriving sexp_of] include Cohttp.S.Body with type t := t val to_string : t -> string Deferred.t val to_string_list : t -> string list Deferred.t val to_pipe : t -> string Pipe.Reader.t val of_pipe : string Pipe.Reader.t -> t val map : t -> f:(string -> string) -> t val as_pipe : t -> f:(string Pipe.Reader.t -> string Pipe.Reader.t) -> t val to_form : t -> (string * string list) list Deferred.t val is_empty : t -> [ `True | `False | `Unknown ] module Private : sig val write_body : ('a -> string -> unit Deferred.t) -> t -> 'a -> unit Deferred.t val pipe_of_body : ('a -> Cohttp.Transfer.chunk Deferred.t) -> 'a -> string Pipe.Reader.t val disable_chunked_encoding : t -> (t * int64) Deferred.t val drain : t -> unit Deferred.t end
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-async/src/client.ml
open Base open Async_kernel open Async_unix module Net = struct let lookup uri = let host = Uri.host_with_default ~default:"localhost" uri in match Uri_services.tcp_port_of_uri ~default:"http" uri with | None -> Deferred.Or_error.error_string "Net.lookup: failed to get TCP port form Uri" | Some port -> ( let open Unix in Addr_info.get ~host [ Addr_info.AI_FAMILY PF_INET; Addr_info.AI_SOCKTYPE SOCK_STREAM ] >>| function | { Addr_info.ai_addr = ADDR_INET (addr, _); _ } :: _ -> Or_error.return (host, Ipaddr_unix.of_inet_addr addr, port) | _ -> Or_error.error "Failed to resolve Uri" uri Uri_sexp.sexp_of_t) let connect_uri ?interrupt ?ssl_config uri = (match Uri.scheme uri with | Some "httpunix" -> let host = Uri.host_with_default ~default:"localhost" uri in return @@ `Unix_domain_socket host | _ -> ( lookup uri |> Deferred.Or_error.ok_exn >>= fun (host, addr, port) -> return @@ match (Uri.scheme uri, ssl_config) with | Some "https", Some config -> `OpenSSL (addr, port, config) | Some "https", None -> let config = Conduit_async.V2.Ssl.Config.create ~hostname:host () in `OpenSSL (addr, port, config) | _ -> `TCP (addr, port))) >>= fun mode -> Conduit_async.V2.connect ?interrupt mode >>| fun (r, w) -> (Input_channel.create r, w) end let read_response ic = Io.Response.read ic >>| function | `Eof -> failwith "Connection closed by remote host" | `Invalid reason -> failwith reason | `Ok res -> ( match Cohttp.Response.has_body res with | `Yes | `Unknown -> (* Build a response pipe for the body *) let reader = Io.Response.make_body_reader res ic in let pipe = Body.Private.pipe_of_body Io.Response.read_body_chunk reader in (res, pipe) | `No -> let pipe = Pipe.of_list [] in (res, pipe)) let request ?interrupt ?ssl_config ?uri ?(body = `Empty) req = (* Connect to the remote side *) let uri = match uri with Some t -> t | None -> Cohttp.Request.uri req in Net.connect_uri ?interrupt ?ssl_config uri >>= fun (ic, oc) -> try_with (fun () -> Io.Request.write ~flush:false (fun writer -> Body.Private.write_body Io.Request.write_body body writer) req oc >>= fun () -> read_response ic >>| fun (resp, body) -> don't_wait_for ( Pipe.closed body >>= fun () -> Deferred.all_unit [ Input_channel.close ic; Writer.close oc ] ); (resp, `Pipe body)) >>= function | Ok res -> return res | Error e -> don't_wait_for (Input_channel.close ic); don't_wait_for (Writer.close oc); raise e module Connection = struct type t' = { ic : Input_channel.t; oc : Writer.t } (* we can't send concurrent requests over HTTP/1 *) type t = t' Sequencer.t let connect ?interrupt ?ssl_config uri = Net.connect_uri ?interrupt ?ssl_config uri >>| fun (ic, oc) -> let t = { ic; oc } |> Sequencer.create ~continue_on_error:false in Throttle.at_kill t (fun { ic; oc } -> Deferred.both (Writer.close oc) (Input_channel.close ic) >>| fun ((), ()) -> ()); Deferred.any [ Writer.consumer_left oc; Input_channel.close_finished ic ] >>| (fun () -> Throttle.kill t) |> don't_wait_for; t let close t = Throttle.kill t; Throttle.cleaned t let close_finished t = Throttle.cleaned t let is_closed t = Throttle.is_dead t let request ?(body = Body.empty) t req = let res = Ivar.create () in Throttle.enqueue t (fun { ic; oc } -> Io.Request.write ~flush:false (fun writer -> Body.Private.write_body Io.Request.write_body body writer) req oc >>= fun () -> read_response ic >>= fun (resp, body) -> Ivar.fill_exn res (resp, `Pipe body); (* block starting any more requests until the consumer has finished reading this request *) Pipe.closed body) |> don't_wait_for; Ivar.read res end let callv ?interrupt ?ssl_config uri reqs = Connection.connect ?interrupt ?ssl_config uri >>| fun connection -> let responses = Pipe.map' ~max_queue_length:1 reqs ~f:(fun reqs -> Deferred.Queue.map ~how:`Sequential reqs ~f:(fun (req, body) -> Connection.request ~body connection req)) in Pipe.closed responses >>= (fun () -> Connection.close connection) |> don't_wait_for; responses let call ?interrupt ?ssl_config ?headers ?(chunked = false) ?(body = `Empty) meth uri = (* Create a request, then make the request. Figure out an appropriate transfer encoding *) (match chunked with | false -> Body.Private.disable_chunked_encoding body >>| fun (body, body_length) -> ( Cohttp.Request.make_for_client ?headers ~chunked ~body_length meth uri, body ) | true -> Deferred.return (match Body.is_empty body with | `True -> (* Don't used chunked encoding with an empty body *) ( Cohttp.Request.make_for_client ?headers ~chunked:false ~body_length:0L meth uri, body ) | `Unknown | `False -> (* Use chunked encoding if there is a body *) ( Cohttp.Request.make_for_client ?headers ~chunked:true meth uri, body ))) >>= fun (req, body) -> request ?interrupt ?ssl_config ~body ~uri req let get ?interrupt ?ssl_config ?headers uri = call ?interrupt ?ssl_config ?headers ~chunked:false `GET uri let head ?interrupt ?ssl_config ?headers uri = call ?interrupt ?ssl_config ?headers ~chunked:false `HEAD uri >>| fun (res, body) -> (match body with `Pipe p -> Pipe.close_read p | _ -> ()); res let post ?interrupt ?ssl_config ?headers ?(chunked = false) ?body uri = call ?interrupt ?ssl_config ?headers ~chunked ?body `POST uri let post_form ?interrupt ?ssl_config ?headers ~params uri = let headers = Cohttp.Header.add_opt_unless_exists headers "content-type" "application/x-www-form-urlencoded" in let body = Body.of_string (Uri.encoded_of_query params) in post ?interrupt ?ssl_config ~headers ~chunked:false ~body uri let put ?interrupt ?ssl_config ?headers ?(chunked = false) ?body uri = call ?interrupt ?ssl_config ?headers ~chunked ?body `PUT uri let patch ?interrupt ?ssl_config ?headers ?(chunked = false) ?body uri = call ?interrupt ?ssl_config ?headers ~chunked ?body `PATCH uri let delete ?interrupt ?ssl_config ?headers ?(chunked = false) ?body uri = call ?interrupt ?ssl_config ?headers ~chunked ?body `DELETE uri
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
mli
cohttp-6.2.1/cohttp-async/src/client.mli
val request : ?interrupt:unit Async_kernel.Deferred.t -> ?ssl_config:Conduit_async.V2.Ssl.Config.t -> ?uri:Uri.t -> ?body:Body.t -> Http.Request.t -> (Http.Response.t * Body.t) Async_kernel.Deferred.t (** Send an HTTP request with an arbitrary body The request is sent as-is. *) val call : ?interrupt:unit Async_kernel.Deferred.t -> ?ssl_config:Conduit_async.V2.Ssl.Config.t -> ?headers:Http.Header.t -> ?chunked:bool -> ?body:Body.t -> Http.Method.t -> Uri.t -> (Http.Response.t * Body.t) Async_kernel.Deferred.t (** Send an HTTP request with arbitrary method and a body Infers the transfer encoding. Depending on the given [uri], we choose a way to start a communication such as: - If the scheme is [https], we try to initiate an SSL connection with the given [ssl_ctx] or a default one on the default port ([*:443]) or the specified one. - If the scheme is [httpunix], we use a UNIX domain socket. - If the scheme ie [http], we try an usual TCP/IP connection on the default port ([*:80]) or the specified one. *) module Connection : sig type t val connect : ?interrupt:unit Async_kernel.Deferred.t -> ?ssl_config:Conduit_async.V2.Ssl.Config.t -> Uri.t -> t Async_kernel.Deferred.t val close : t -> unit Async_kernel.Deferred.t val close_finished : t -> unit Async_kernel.Deferred.t val is_closed : t -> bool val request : ?body:Body.t -> t -> Http.Request.t -> (Http.Response.t * Body.t) Async_kernel.Deferred.t end val callv : ?interrupt:unit Async_kernel.Deferred.t -> ?ssl_config:Conduit_async.V2.Ssl.Config.t -> Uri.t -> (Http.Request.t * Body.t) Async_kernel.Pipe.Reader.t -> (Http.Response.t * Body.t) Async_kernel.Pipe.Reader.t Async_kernel.Deferred.t val get : ?interrupt:unit Async_kernel.Deferred.t -> ?ssl_config:Conduit_async.V2.Ssl.Config.t -> ?headers:Http.Header.t -> Uri.t -> (Http.Response.t * Body.t) Async_kernel.Deferred.t (** Send an HTTP GET request *) val head : ?interrupt:unit Async_kernel.Deferred.t -> ?ssl_config:Conduit_async.V2.Ssl.Config.t -> ?headers:Http.Header.t -> Uri.t -> Http.Response.t Async_kernel.Deferred.t (** Send an HTTP HEAD request *) val delete : ?interrupt:unit Async_kernel.Deferred.t -> ?ssl_config:Conduit_async.V2.Ssl.Config.t -> ?headers:Http.Header.t -> ?chunked:bool -> ?body:Body.t -> Uri.t -> (Http.Response.t * Body.t) Async_kernel.Deferred.t (** Send an HTTP DELETE request *) val post : ?interrupt:unit Async_kernel.Deferred.t -> ?ssl_config:Conduit_async.V2.Ssl.Config.t -> ?headers:Http.Header.t -> ?chunked:bool -> ?body:Body.t -> Uri.t -> (Http.Response.t * Body.t) Async_kernel.Deferred.t (** Send an HTTP POST request. [chunked] encoding is off by default as not many servers support it *) val put : ?interrupt:unit Async_kernel.Deferred.t -> ?ssl_config:Conduit_async.V2.Ssl.Config.t -> ?headers:Http.Header.t -> ?chunked:bool -> ?body:Body.t -> Uri.t -> (Http.Response.t * Body.t) Async_kernel.Deferred.t (** Send an HTTP PUT request. [chunked] encoding is off by default as not many servers support it *) val patch : ?interrupt:unit Async_kernel.Deferred.t -> ?ssl_config:Conduit_async.V2.Ssl.Config.t -> ?headers:Http.Header.t -> ?chunked:bool -> ?body:Body.t -> Uri.t -> (Http.Response.t * Body.t) Async_kernel.Deferred.t (** Send an HTTP PATCH request. [chunked] encoding is off by default as not many servers support it *) val post_form : ?interrupt:unit Async_kernel.Deferred.t -> ?ssl_config:Conduit_async.V2.Ssl.Config.t -> ?headers:Http.Header.t -> params:(string * string list) list -> Uri.t -> (Http.Response.t * Body.t) Async_kernel.Deferred.t (** Send an HTTP POST request in form format *)
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-async/src/cohttp_async.ml
module Body = Body module Body_raw = Body [@@deprecated "Use Body"] module Client = Client module Io = Io [@@deprecated "This module is not for public consumption"] module Request = Cohttp.Request [@@deprecated "Use Cohttp.Request directly"] module Response = Cohttp.Response [@@deprecated "Use Cohttp.Response directly"] module Server = Server
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
dune
cohttp-6.2.1/cohttp-async/src/dune
(library (name cohttp_async) (synopsis "Async backend") (public_name cohttp-async) (libraries logs.fmt base fmt async_unix async_kernel uri uri.services uri-sexp ipaddr.unix conduit-async magic-mime http http_bytebuffer cohttp) (preprocess (pps ppx_sexp_conv)))
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-async/src/input_channel.ml
open! Core open! Async module Bytebuffer = struct module Bytebuffer = Http_bytebuffer.Bytebuffer include Bytebuffer include Bytebuffer.Make (Deferred) (struct type src = Reader.t let refill reader buf ~pos ~len = Reader.read reader ~pos ~len buf end) end type t = { buf : Bytebuffer.t; reader : Reader.t } let create ?(buf_len = 0x4000) reader = { buf = Bytebuffer.create buf_len; reader } let read_line_opt t = Bytebuffer.read_line t.buf t.reader let read t count = Bytebuffer.read t.buf t.reader count let refill t = Bytebuffer.refill t.buf t.reader let with_input_buffer t ~f = let buf = Bytebuffer.unsafe_buf t.buf in let pos = Bytebuffer.pos t.buf in let len = Bytebuffer.length t.buf in let res, consumed = f (Bytes.unsafe_to_string ~no_mutation_while_string_reachable:buf) ~pos ~len in Bytebuffer.drop t.buf consumed; res let is_closed t = Reader.is_closed t.reader let close t = Reader.close t.reader let close_finished t = Reader.close_finished t.reader let transfer t writer = let finished = Ivar.create () in upon (Pipe.closed writer) (fun () -> Ivar.fill_if_empty finished ()); let rec loop () = refill t >>> function | `Eof -> Ivar.fill_if_empty finished () | `Ok -> let payload = with_input_buffer t ~f:(fun buf ~pos ~len -> (String.sub buf ~pos ~len, len)) in Pipe.write writer payload >>> fun () -> loop () in loop (); Ivar.read finished let to_reader info ic = let reader, writer = Pipe.create () in ( transfer ic writer >>> fun () -> close ic >>> fun () -> Pipe.close writer ); Reader.of_pipe info reader
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
mli
cohttp-6.2.1/cohttp-async/src/input_channel.mli
open Async type t val create : ?buf_len:int -> Reader.t -> t val read_line_opt : t -> string option Deferred.t val read : t -> int -> string Deferred.t val refill : t -> [ `Eof | `Ok ] Deferred.t val with_input_buffer : t -> f:(string -> pos:int -> len:int -> 'a * int) -> 'a val is_closed : t -> bool val close : t -> unit Deferred.t val close_finished : t -> unit Deferred.t val to_reader : Base.Info.t -> t -> Reader.t Deferred.t
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-async/src/io.ml
(*{{{ Copyright (c) 2012-2013 Anil Madhavapeddy <anil@recoil.org> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * }}}*) open Base open Async_kernel module IO = struct module Writer = Async_unix.Writer module Reader = Async_unix.Reader module Format = Stdlib.Format let log_src_name = "cohttp.async.io" let src = Logs.Src.create log_src_name ~doc:"Cohttp Async IO module" module Log = (val Logs.src_log src : Logs.LOG) let default_reporter () = let fmtr, fmtr_flush = let b = Buffer.create 512 in ( Fmt.with_buffer ~like:Fmt.stderr b, fun () -> let m = Buffer.contents b in Buffer.reset b; m ) in let report src _level ~over k msgf = let k _ = if String.equal (Logs.Src.name src) log_src_name then Writer.write (Lazy.force Writer.stderr) (fmtr_flush ()); over (); k () in msgf @@ fun ?header:_ ?tags:_ fmt -> Format.kfprintf k fmtr Stdlib.("@[" ^^ fmt ^^ "@]@.") in { Logs.report } let set_log = lazy ((* If no reporter has been set by the application, set default one that prints to stderr. This way a user will see logs when the debug flag is set without adding a reporter. *) if phys_equal (Logs.reporter ()) Logs.nop_reporter then Logs.set_level @@ Some Logs.Debug; Logs.set_reporter (default_reporter ())) let check_debug norm_fn debug_fn = match Stdlib.Sys.getenv "COHTTP_DEBUG" with | _ -> Lazy.force set_log; debug_fn | exception Stdlib.Not_found -> norm_fn type 'a t = 'a Deferred.t let ( >>= ) = Deferred.( >>= ) let return = Deferred.return type ic = Input_channel.t type oc = Writer.t type conn = unit let read_line = check_debug (fun ic -> Input_channel.read_line_opt ic) (fun ic -> Input_channel.read_line_opt ic >>| function | Some s -> Log.debug (fun fmt -> fmt "<<< %s" s); Some s | None -> Log.debug (fun fmt -> fmt "<<<EOF"); None) let read ic len = Input_channel.read ic len let write = check_debug (fun oc buf -> Writer.write oc buf; return ()) (fun oc buf -> Log.debug (fun fmt -> fmt "%4d >>> %s" (Unix.getpid ()) buf); Writer.write oc buf; return ()) let refill ic = Input_channel.refill ic let with_input_buffer ic = Input_channel.with_input_buffer ic let flush = Writer.flushed end module Request = Cohttp.Request.Private.Make (IO) module Response = Cohttp.Response.Private.Make (IO)
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
mli
cohttp-6.2.1/cohttp-async/src/io.mli
(*{{{ Copyright (c) 2013 Anil Madhavapeddy <anil@recoil.org> * * Permission to use, copy, modify, and distribute this software for * any purpose with or without fee is hereby granted, provided that the * above copyright notice and this permission notice appear in all * copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA * OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. }}}*) module IO : Cohttp.S.IO with type 'a t = 'a Async_kernel.Deferred.t and type ic = Input_channel.t and type oc = Async_unix.Writer.t module Request : Cohttp.S.Http_io with type t := Http.Request.t and module IO := IO module Response : Cohttp.S.Http_io with type t := Http.Response.t and module IO := IO
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-async/src/server.ml
open Base open Async_kernel open Async_unix type ('address, 'listening_on) t = { server : ('address, 'listening_on) Tcp.Server.t; [@sexp.opaque] } [@@deriving sexp_of] let num_connections t = Tcp.Server.num_connections t.server type response = Cohttp.Response.t * Body.t [@@deriving sexp_of] type response_action = [ `Expert of Http.Response.t * (Reader.t -> Writer.t -> unit Deferred.t) | `Response of response ] type 'r respond_t = ?headers:Http.Header.t -> ?body:Body.t -> Http.Status.t -> 'r Deferred.t let close t = Tcp.Server.close t.server let close_finished t = Tcp.Server.close_finished t.server let is_closed t = Tcp.Server.is_closed t.server let listening_on t = Tcp.Server.listening_on t.server let read_body req rd = match Http.Request.has_body req with (* TODO maybe attempt to read body *) | `No | `Unknown -> `Empty | `Yes -> (* Create a Pipe for the body *) let reader = Io.Request.make_body_reader req rd in let pipe = Body.Private.pipe_of_body Io.Request.read_body_chunk reader in `Pipe pipe let collect_errors writer ~f = let monitor = Writer.monitor writer in (* don't propagate errors up, we handle them here *) Monitor.detach_and_get_error_stream monitor |> (ignore : exn Stream.t -> unit); choose [ choice (Monitor.get_next_error monitor) (fun e -> Error (Exn.Reraised ("Cohttp_async.Server.collect_errors", e))); choice (try_with ~name:"Cohttp_async.Server.collect_errors" f) Fn.id; ] let reader_info = Info.of_string "Cohttp_async.Server.Expert: Create reader" let handle_client handle_request sock rd wr = collect_errors wr ~f:(fun () -> let rd = Input_channel.create rd in let rec loop rd wr sock handle_request = if Input_channel.is_closed rd then Deferred.unit else Io.Request.read rd >>= function | `Eof | `Invalid _ -> Deferred.unit | `Ok req -> ( let req_body = read_body req rd in handle_request ~body:req_body sock req >>= function | `Expert (res, handler) -> Io.Response.write_header res wr >>= fun () -> Input_channel.to_reader reader_info rd >>= fun reader -> handler reader wr | `Response (res, res_body) -> (* There are scenarios if a client leaves before consuming the full response, we might have a reference to an async Pipe that doesn't get drained. Not draining or closing a pipe can lead to issues if its holding a resource like a file handle as those resources will never be closed, leading to a leak. Async writers have a promise that's fulfilled whenever they are closed, so we can use it to schedule a close operation on the stream to ensure that we don't leave a stream open if the underlying channels are closed. *) (match res_body with | `Empty | `String _ | `Strings _ -> () | `Pipe stream -> Deferred.any_unit [ Writer.close_finished wr; Writer.consumer_left wr ] >>> fun () -> Pipe.close_read stream); let keep_alive = Http.Request.is_keep_alive req && Http.Response.is_keep_alive res in let res = let headers = Http.Header.add_unless_exists (Http.Response.headers res) "connection" (if keep_alive then "keep-alive" else "close") in { res with Http.Response.headers } in Io.Response.write ~flush:false (Body.Private.write_body Io.Response.write_body res_body) res wr >>= fun () -> Body.Private.drain req_body >>= fun () -> if keep_alive then loop rd wr sock handle_request else Deferred.unit) in loop rd wr sock handle_request) >>| Result.ok_exn let respond ?(headers = Http.Header.init ()) ?(body = `Empty) status : response Deferred.t = let encoding = Body.transfer_encoding body in let resp = Cohttp.Response.make ~status ~encoding ~headers () in return (resp, body) let respond_with_pipe ?headers ?(code = `OK) body = respond ?headers ~body:(`Pipe body) code let respond_string ?headers ?(status = `OK) body = respond ?headers ~body:(`String body) status let respond_with_redirect ?headers uri = let headers = Http.Header.add_opt_unless_exists headers "location" (Uri.to_string uri) in respond ~headers `Found let resolve_local_file ~docroot ~uri = Cohttp.Path.resolve_local_file ~docroot ~uri let error_body_default = "<html><body><h1>404 Not Found</h1></body></html>" let respond_with_file ?headers ?(error_body = error_body_default) filename = Monitor.try_with ~run:`Now (fun () -> Reader.open_file filename >>= fun rd -> let body = `Pipe (Reader.pipe rd) in let mime_type = Magic_mime.lookup filename in let headers = Http.Header.add_opt_unless_exists headers "content-type" mime_type in respond ~headers ~body `OK) >>= function | Ok res -> return res | Error _exn -> respond_string ~status:`Not_found error_body type mode = Conduit_async.server let create_raw ?max_connections ?backlog ?buffer_age_limit ?(mode = `TCP) ~on_handler_error where_to_listen handle_request = Conduit_async.serve ?max_connections ?backlog ?buffer_age_limit ~on_handler_error mode where_to_listen (handle_client handle_request) >>| fun server -> { server } let create_expert ?max_connections ?backlog ?buffer_age_limit ?(mode = `TCP) ~on_handler_error where_to_listen handle_request = create_raw ?max_connections ?backlog ?buffer_age_limit ~on_handler_error ~mode where_to_listen handle_request let create ?max_connections ?backlog ?buffer_age_limit ?(mode = `TCP) ~on_handler_error where_to_listen handle_request = let handle_request ~body address request = handle_request ~body address request >>| fun r -> `Response r in create_raw ?max_connections ?backlog ?buffer_age_limit ~on_handler_error ~mode where_to_listen handle_request module Expert = struct let create handle_request addr reader writer = let handle_request ~body addr request = handle_request ~body addr request >>| fun r -> `Response r in handle_client handle_request addr reader writer let create_with_response_action handle_request addr reader writer = handle_client handle_request addr reader writer end
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
mli
cohttp-6.2.1/cohttp-async/src/server.mli
type ('address, 'listening_on) t constraint 'address = [< Async_unix.Socket.Address.t ] [@@deriving sexp_of] val close : (_, _) t -> unit Async_kernel.Deferred.t val close_finished : (_, _) t -> unit Async_kernel.Deferred.t val is_closed : (_, _) t -> bool val listening_on : (_, 'listening_on) t -> 'listening_on val num_connections : (_, _) t -> int type response = Http.Response.t * Body.t [@@deriving sexp_of] type 'r respond_t = ?headers:Http.Header.t -> ?body:Body.t -> Http.Status.t -> 'r Async_kernel.Deferred.t type response_action = [ `Expert of Http.Response.t * (Async_unix.Reader.t -> Async_unix.Writer.t -> unit Async_kernel.Deferred.t) | `Response of response ] (** A request handler can respond in two ways: - Using [`Response], with a {!Http.Response.t} and a {!Body.t}. - Using [`Expert], with a {!Http.Response.t} and an IO function that is expected to write the response body. The IO function has access to the underlying {!Async_unix.Reader.t} and {!Async_unix.Writer.t}, which allows writing a response body more efficiently, stream a response or to switch protocols entirely (e.g. websockets). Processing of pipelined requests continue after the [unit Async_kernel.Deferred.t] is resolved. The connection can be closed by closing the {!Async_unix.Reader.t}. *) val respond : response respond_t val resolve_local_file : docroot:string -> uri:Uri.t -> string [@@deprecated "Please use Cohttp.Path.resolve_local_file. "] (** Resolve a URI and a docroot into a concrete local filename. *) val respond_with_pipe : ?headers:Http.Header.t -> ?code:Http.Status.t -> string Async_kernel.Pipe.Reader.t -> response Async_kernel.Deferred.t (** Respond with a [string] Pipe that provides the response string Pipe.Reader.t. @param code Default is HTTP 200 `OK *) val respond_string : ?headers:Http.Header.t -> ?status:Http.Status.t -> string -> response Async_kernel.Deferred.t val respond_with_redirect : ?headers:Http.Header.t -> Uri.t -> response Async_kernel.Deferred.t (** Respond with a redirect to an absolute [uri] @param uri Absolute URI to redirect the client to *) val respond_with_file : ?headers:Http.Header.t -> ?error_body:string -> string -> response Async_kernel.Deferred.t (** Respond with file contents, and [error_string Pipe.Async_unix.Reader.t] if the file isn't found *) type mode = Conduit_async.server val create_expert : ?max_connections:int -> ?backlog:int -> ?buffer_age_limit:Async_unix.Writer.buffer_age_limit -> ?mode:mode -> on_handler_error:[ `Call of 'address -> exn -> unit | `Ignore | `Raise ] -> ('address, 'listening_on) Async.Tcp.Where_to_listen.t -> (body:Body.t -> 'address -> Http.Request.t -> response_action Async_kernel.Deferred.t) -> ('address, 'listening_on) t Async_kernel.Deferred.t (** Build a HTTP server and expose the [IO.ic] and [IO.oc]s, based on the [Tcp.Server] interface. *) val create : ?max_connections:int -> ?backlog:int -> ?buffer_age_limit:Async_unix.Writer.buffer_age_limit -> ?mode:Conduit_async.server -> on_handler_error:[ `Call of 'address -> exn -> unit | `Ignore | `Raise ] -> ('address, 'listening_on) Async.Tcp.Where_to_listen.t -> (body:Body.t -> 'address -> Http.Request.t -> response Async_kernel.Deferred.t) -> ('address, 'listening_on) t Async_kernel.Deferred.t (** Build a HTTP server, based on the [Tcp.Server] interface *) module Expert : sig val create : (body:Body.t -> 'addr -> Http.Request.t -> response Async_kernel.Deferred.t) -> 'addr -> Async_unix.Reader.t -> Async_unix.Writer.t -> unit Async_kernel.Deferred.t (** [create] accepts a user provided cohttp handler, and creates a server callback that works with user provided socket address, [Async_unix.Reader.t] and [Async_unix.Writer.t]. This can be useful if there is a need for more control over how the Reader and Writer get created. *) val create_with_response_action : (body:Body.t -> 'addr -> Http.Request.t -> response_action Async_kernel.Deferred.t) -> 'addr -> Async_unix.Reader.t -> Async_unix.Writer.t -> unit Async_kernel.Deferred.t (** [create_with_response_action] is similar to [create] but the user provided handler can use [Cohttp_async.Server.response_action], and has access to using the Expert mode response that can access the underlying reader/writer pair from within the http handler. *) end
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-async/test/cohttp_async_test/src/cohttp_async_test.ml
open Base open Async_kernel open OUnit module Server = Cohttp_async.Server module Body = Cohttp_async.Body type 'a io = 'a Deferred.t type ic = Async_unix.Reader.t type oc = Async_unix.Writer.t type body = Body.t type response_action = [ `Expert of Http.Response.t * (ic -> oc -> unit io) | `Response of Http.Response.t * body ] type spec = Http.Request.t -> body -> response_action io type async_test = unit -> unit io let response rsp = `Response rsp let expert ?(rsp = Cohttp.Response.make ()) f _req _body = return (`Expert (rsp, f)) let const rsp _req _body = rsp >>| response let response_sequence = Cohttp_test.response_sequence failwith let get_port = let port = ref 10_080 in fun () -> let v = !port in Int.incr port; v let temp_server ?port spec callback = let port = match port with None -> get_port () | Some p -> p in let uri = Uri.of_string ("http://0.0.0.0:" ^ Int.to_string port) in let server = Server.create_expert ~on_handler_error:`Raise (Async.Tcp.Where_to_listen.of_port port) (fun ~body _sock req -> spec req body) in server >>= fun server -> callback uri >>= fun res -> Server.close server >>| fun () -> res let test_server_s ?port ?(name = "Cohttp Server Test") spec f = temp_server ?port spec (fun uri -> Logs.info (fun m -> m "Test %s running on %s" name (Uri.to_string uri)); let tests = f uri in let results = tests |> Deferred.List.map ~how:`Sequential ~f:(fun (name, test) -> Logs.debug (fun m -> m "Running %s" name); let res = try_with test >>| function | Ok () -> `Ok | Error exn -> `Exn exn in res >>| fun res -> (name, res)) in results >>| fun results -> let ounit_tests = results |> List.map ~f:(fun (name, res) -> name >:: fun () -> match res with `Ok -> () | `Exn x -> raise x) in name >::: ounit_tests) let run_async_tests test = (* enable logging to stdout *) Fmt_tty.setup_std_outputs (); Logs.set_level @@ Some Logs.Debug; Logs.set_reporter (Logs_fmt.reporter ()); test >>| fun a -> a |> OUnit.run_test_tt_main
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
mli
cohttp-6.2.1/cohttp-async/test/cohttp_async_test/src/cohttp_async_test.mli
open Async_kernel include Cohttp_test.S with type 'a io = 'a Deferred.t and type body = Cohttp_async.Body.t and type ic = Async_unix.Reader.t and type oc = Async_unix.Writer.t val run_async_tests : OUnit.test io -> OUnit.test_result list Deferred.t
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
dune
cohttp-6.2.1/cohttp-async/test/cohttp_async_test/src/dune
(library (name cohttp_async_test) (libraries fmt.tty uri.services async_kernel cohttp_test cohttp-async))
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
dune
cohttp-6.2.1/cohttp-async/test/dune
(executable (name test_async_integration) (libraries cohttp_async_test async_unix base core async_kernel ounit2 cohttp-async)) (rule (alias runtest) (package cohttp-async) (action (run ./test_async_integration.exe)))
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-async/test/test_async_integration.ml
open Base open Async_kernel open OUnit open Cohttp open Cohttp_async_test module Server = Cohttp_async.Server module Client = Cohttp_async.Client module Body = Cohttp_async.Body let chunk_body = [ "one"; ""; " "; "bar"; "" ] let large_string = String.make (Int.pow 2 16) 'A' let response_bodies = [ "Testing"; "Foo bar" ] let ok s = Server.respond `OK ~body:(Body.of_string s) let chunk size = String.init ~f:(Fn.const 'X') size let chunk_size = 33_000 let chunks = 3 let server = [ (* empty_chunk *) const @@ Server.respond `OK ~body:(Body.of_string_list chunk_body); (* large response *) const @@ Server.respond_string large_string; (* large request *) (fun _ body -> body |> Body.to_string >>| String.length >>= fun len -> Server.respond_string (Int.to_string len) >>| response); ] (* pipelined_chunk *) @ (response_bodies |> List.map ~f:(Fn.compose const ok)) (* large response chunked *) @ [ (fun _ _ -> let body = let r, w = Pipe.create () in let chunk = chunk chunk_size in for _ = 0 to chunks - 1 do Pipe.write_without_pushback w chunk done; Pipe.close w; r in Server.respond_with_pipe ~code:`OK body >>| response); (* pipelined_expert *) expert (fun _ic oc -> Async_unix.Writer.write oc "8\r\nexpert 1\r\n0\r\n\r\n"; Async_unix.Writer.flushed oc); expert (fun ic oc -> Async_unix.Writer.write oc "8\r\nexpert 2\r\n0\r\n\r\n"; Async_unix.Writer.flushed oc >>= fun () -> Async_unix.Reader.close ic); ] |> response_sequence let ts = test_server_s server (fun uri -> let headers = Header.init_with "connection" "close" in let empty_chunk () = Client.get ~headers uri >>= fun (_, body) -> body |> Body.to_string >>| fun body -> assert_equal body (String.concat ~sep:"" chunk_body) in let large_response () = Client.get ~headers uri >>= fun (_, body) -> body |> Body.to_string >>| fun body -> assert_equal body large_string in let large_request () = Client.post ~headers ~body:(Body.of_string large_string) uri >>= fun (_, body) -> body |> Body.to_string >>| fun s -> assert_equal (String.length large_string) (Int.of_string s) in let pipelined_chunk () = let printer x = x in let reqs = [ (Request.make ~meth:`POST uri, Body.of_string "foo"); (Request.make ~meth:`POST uri, Body.of_string "bar"); ] in let body_q = response_bodies |> Queue.of_list in reqs |> Pipe.of_list |> Client.callv uri >>= fun responses -> responses |> Pipe.to_list >>= fun resps -> resps |> Deferred.List.iter ~how:`Sequential ~f:(fun (_resp, body) -> let expected_body = body_q |> Queue.dequeue_exn in body |> Body.to_string >>| fun body -> assert_equal ~printer expected_body body) in let large_chunked_response () = Client.get ~headers uri >>= fun (resp, body) -> assert_equal Cohttp.Transfer.Chunked (Response.encoding resp); body |> Body.to_string >>| String.length >>| fun len -> assert_equal ~printer:Int.to_string (chunk_size * chunks) len in let expert_pipelined () = let printer x = x in Client.get uri >>= fun (_rsp, body) -> Body.to_string body >>= fun body -> assert_equal ~printer "expert 1" body; Client.get ~headers uri >>= fun (_rsp, body) -> Body.to_string body >>| fun body -> assert_equal ~printer "expert 2" body in [ ("empty chunk test", empty_chunk); ("large response", large_response); ("large request", large_request); ("pipelined chunk test", pipelined_chunk); ("large chunked response", large_chunked_response); ("expert response", expert_pipelined); ]) let () = ts |> run_async_tests >>= (fun _ -> Async_unix.Shutdown.exit 0) |> don't_wait_for; Core.never_returns (Async_unix.Scheduler.go ())
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
opam
cohttp-6.2.1/cohttp-bench.opam
version: "6.2.1" # This file is generated by dune, edit dune-project instead opam-version: "2.0" synopsis: "Benchmarks binaries for Cohttp" description: """ This package contains some benchmarks for http and cohttp. The benchmarks for the server latency will require wrk2 (https://github.com/giltene/wrk2) to run. The latency graphs can then be generated with HdrHistogram plotter, also available online at https://hdrhistogram.github.io/HdrHistogram/plotFiles.html.""" maintainer: ["Anil Madhavapeddy <anil@recoil.org>"] authors: [ "Anil Madhavapeddy" "Stefano Zacchiroli" "David Sheets" "Thomas Gazagnaire" "David Scott" "Rudi Grinberg" "Andy Ray" "Anurag Soni" ] license: "ISC" homepage: "https://github.com/mirage/ocaml-cohttp" doc: "https://mirage.github.io/ocaml-cohttp/" bug-reports: "https://github.com/mirage/ocaml-cohttp/issues" depends: [ "dune" {>= "3.8"} "core" {>= "v0.13.0"} "core_bench" "eio" {>= "0.12"} "eio_main" "http" {= version} "cohttp" {= version} "cohttp-eio" {= version} "cohttp-lwt-unix" {= version} "cohttp-server-lwt-unix" {= version} "cohttp-async" {= version} "odoc" {with-doc} ] dev-repo: "git+https://github.com/mirage/ocaml-cohttp.git" build: [ ["dune" "subst"] {dev} [ "dune" "build" "-p" name "-j" jobs "@install" "@cohttp-bench/runtest" {with-test} "@doc" {with-doc} ] ] x-maintenance-intent: [ "(latest)" ]
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-bench/async_server.ml
open Core open Async module Server = Cohttp_async.Server let length = 2053 let text = String.make length 'a' let headers = Cohttp.Header.of_list [ ("content-length", Int.to_string length) ] let handler ~body:_ _sock _req = Server.respond_string ~headers text let start_server port () = Cohttp_async.Server.create ~on_handler_error:`Raise (Tcp.Where_to_listen.of_port port) handler >>= fun server -> Deferred.forever () (fun () -> after Time_float.Span.(of_sec 0.5) >>| fun () -> Log.Global.printf "Active connections: %d" (Server.num_connections server)); Deferred.never () let () = let module Command = Async_command in Command.async_spec ~summary:"Start a hello world Async server" Command.Spec.( empty +> flag "-p" (optional_with_default 8080 int) ~doc:"int Source port to listen on") start_server |> Command_unix.run
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-bench/bench.ml
module Command = Core.Command module Staged = Core.Staged open Core_bench let header_names = [ "Accept"; "Accept-Encoding"; "Accept-Language"; "Cache-Control"; "Connection"; "Host"; "If-Modified-Since"; "If-None-Match"; "Origin"; "Referer"; "Sec-Fetch-Dest"; "Sec-Fetch-Mode"; "Sec-Fetch-Site"; ] let header = header_names |> List.map (fun s -> (s, "value")) |> Http.Header.of_list let bench_header_mem = Bench.Test.create ~name:"Header.mem" (fun () -> List.iter (fun key -> assert (Http.Header.mem header key)) header_names) let () = Command_unix.run @@ Bench.make_command [ bench_header_mem ]
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
dune
cohttp-6.2.1/cohttp-bench/dune
(executable (name bench) (modules bench) (libraries http core core_unix.command_unix core_bench)) (executable (name lwt_unix_server) (modules lwt_unix_server) (libraries cohttp-lwt-unix logs.fmt fmt.tty)) (executable (name async_server) (modules async_server) (libraries cohttp-async core_unix.command_unix logs.fmt fmt.tty)) (executable (name eio_server) (modules eio_server) (libraries cohttp-eio eio_main)) (rule (alias bench) (package cohttp-bench) (enabled_if %{arch_sixtyfour}) (action (run ./bench.exe time cycles))) (rule (alias latency) (deps lwt_unix_server.exe async_server.exe) (package cohttp-bench) (action (run ./latency.sh))) (executable (name lwt_unix_server_new) (modules lwt_unix_server_new) (libraries cohttp_server_lwt_unix lwt.unix lwt http unix))
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-bench/eio_server.ml
open Cohttp_eio let length = 2053 let text = String.make length 'a' let headers = Cohttp.Header.of_list [ ("content-length", Int.to_string length) ] let server_callback _conn _req _body = Server.respond_string ~headers ~status:`OK ~body:text () let () = let port = ref 8080 in Arg.parse [ ("-p", Arg.Set_int port, " Listening port number(8080 by default)") ] ignore "An HTTP/1.1 server"; Eio_main.run @@ fun env -> Eio.Switch.run @@ fun sw -> let socket = Eio.Net.listen env#net ~sw ~backlog:11_000 ~reuse_addr:true (`Tcp (Eio.Net.Ipaddr.V4.loopback, !port)) and server = Cohttp_eio.Server.make ~callback:server_callback () in Cohttp_eio.Server.run socket server ~on_error:raise
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-bench/lwt_unix_server.ml
module Server = Cohttp_lwt_unix.Server let length = 2053 let text = String.make length 'a' let headers = Cohttp.Header.of_list [ ("content-length", Int.to_string length) ] let server_callback _conn _req _body = Server.respond_string ~headers ~status:`OK ~body:text () let main () = Server.create ~backlog:11_000 (Server.make ~callback:server_callback ()) let () = Printexc.record_backtrace true; Logs.set_level (Some Info); Logs.set_reporter (Logs_fmt.reporter ()); ignore (Lwt_main.run (main ()))
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-bench/lwt_unix_server_new.ml
open Lwt.Syntax module Context = Cohttp_server_lwt_unix.Context module Body = Cohttp_server_lwt_unix.Body let text = String.make 2053 'a' let server_callback ctx = Lwt.join [ Context.discard_body ctx; Context.respond ctx (Http.Response.make ()) (Body.string text); ] let main () = let* _server = let listen_address = Unix.(ADDR_INET (inet_addr_loopback, 8080)) in let server = Cohttp_server_lwt_unix.create ~on_exn:(fun exn -> Format.eprintf "unexpected:@.%s@." (Printexc.to_string exn)) server_callback in Lwt_io.establish_server_with_client_address ~backlog:10_000 listen_address (fun _addr ch -> Cohttp_server_lwt_unix.handle_connection server ch) in let forever, _ = Lwt.wait () in forever let () = Printexc.record_backtrace true; ignore (Lwt_main.run (main ()))
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
mli
cohttp-6.2.1/cohttp-bench/lwt_unix_server_new.mli
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
opam
cohttp-6.2.1/cohttp-curl-async.opam
version: "6.2.1" # This file is generated by dune, edit dune-project instead opam-version: "2.0" synopsis: "Cohttp client using Curl & Async as the backend" description: """ An HTTP client that relies on Curl + Async for the backend. Does not require conduit for SSL.""" maintainer: ["Anil Madhavapeddy <anil@recoil.org>"] authors: [ "Anil Madhavapeddy" "Stefano Zacchiroli" "David Sheets" "Thomas Gazagnaire" "David Scott" "Rudi Grinberg" "Andy Ray" "Anurag Soni" ] license: "ISC" homepage: "https://github.com/mirage/ocaml-cohttp" doc: "https://mirage.github.io/ocaml-cohttp/" bug-reports: "https://github.com/mirage/ocaml-cohttp/issues" depends: [ "dune" {>= "3.8"} "ocurl" {>= "0.9.2"} "http" {= version} "stringext" "cohttp-curl" {= version} "core" {>= "v0.16.0"} "core_unix" {>= "v0.14.0"} "core_kernel" {with-test} "async_kernel" {with-test & >= "v0.17.0"} "async_unix" {with-test} "cohttp-async" {with-test & = version} "uri" {with-test & >= "4.2.0"} "fmt" {with-test} "ounit2" {with-test} "alcotest" {with-test & >= "1.7.0"} "odoc" {with-doc} ] dev-repo: "git+https://github.com/mirage/ocaml-cohttp.git" build: [ ["dune" "subst"] {dev} [ "dune" "build" "-p" name "-j" jobs "@install" "@cohttp-curl-async/runtest" {with-test} "@doc" {with-doc} ] ] x-maintenance-intent: [ "(latest)" ]
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-curl-async/bin/curl.ml
open Cohttp module Curl = Cohttp_curl_async module Sexp = Sexplib0.Sexp open Async_kernel module Writer = Async_unix.Writer module Time = Core.Time_float let ( let* ) x f = Deferred.bind x ~f let client uri meth' () = let meth = Cohttp.Code.method_of_string meth' in let reply = let context = Curl.Context.create () in let request = Curl.Request.create ~timeout:(Time.Span.of_ms 5000.) meth ~uri ~input:Curl.Source.empty ~output:Curl.Sink.string in Curl.submit context request in let* resp, response_body = Deferred.both (Curl.Response.response reply) (Curl.Response.body reply) >>| function | Ok r, Ok b -> (r, b) | _, Error e | Error e, _ -> Format.eprintf "error: %s@.%!" (Curl.Error.message e); exit 1 in Format.eprintf "response:%a@.%!" Sexp.pp_hum (Response.sexp_of_t resp); let status = Response.status resp in (match Code.is_success (Code.code_of_status status) with | false -> prerr_endline (Code.string_of_status status) | true -> ()); let output_body c = Writer.write c response_body; Writer.flushed c in output_body (Lazy.force Writer.stdout) let _ = let open Async_command in async_spec ~summary:"Fetch URL and print it" Spec.( empty +> anon ("url" %: string) +> flag "-X" (optional_with_default "GET" string) ~doc:" Set HTTP method") client |> Command_unix.run
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
dune
cohttp-6.2.1/cohttp-curl-async/bin/dune
(executable (name curl) (libraries sexplib0 cohttp cohttp_curl_async core_kernel async_unix async_kernel async.async_command core_unix.command_unix))
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-curl-async/src/cohttp_curl_async.ml
open Async_kernel module Time = Core.Time_float module Fd = Async_unix.Fd module Clock = Async_unix.Clock let ( let+ ) x f = Deferred.map x ~f module Cohttp_curl = Cohttp_curl.Private module Sink = Cohttp_curl.Sink module Source = Cohttp_curl.Source module Error = Cohttp_curl.Error module Context = struct type fd_events = { fd : Fd.t; mutable read : unit Ivar.t option; mutable write : unit Ivar.t option; } type t = { mt : Curl.Multi.mt; wakeners : (Curl.t, Curl.curlCode Ivar.t) Hashtbl.t; all_events : (Unix.file_descr, fd_events) Hashtbl.t; mutable timeout : (unit, unit) Clock.Event.t option; } let create () = let t = { mt = Curl.Multi.create (); wakeners = Hashtbl.create 32; all_events = Hashtbl.create 32; timeout = None; } in let rec finished () = match Curl.Multi.remove_finished t.mt with | None -> () | Some (h, code) -> (match Hashtbl.find_opt t.wakeners h with | None -> () | Some w -> Hashtbl.remove t.wakeners h; Ivar.fill_exn w code); finished () in let on_readable fd = let (_ : int) = Curl.Multi.action t.mt (Fd.file_descr_exn fd) EV_IN in finished () in let on_writable fd = let (_ : int) = Curl.Multi.action t.mt (Fd.file_descr_exn fd) EV_OUT in finished () in let on_timer () = Curl.Multi.action_timeout t.mt; finished () in Curl.Multi.set_timer_function t.mt (fun timeout -> (match t.timeout with | None -> () | Some event -> Clock.Event.abort_if_possible event ()); let duration = Time.Span.of_ms (float_of_int timeout) in t.timeout <- Some (Clock.Event.run_after duration on_timer ())); let socket_function fd (what : Curl.Multi.poll) = let create_event fd what = let interrupt = Ivar.create () in let f () = match what with `Read -> on_readable fd | `Write -> on_writable fd in let event = Fd.interruptible_every_ready_to fd what ~interrupt:(Ivar.read interrupt) (fun () -> f ()) () |> Deferred.map ~f:(function | `Bad_fd | `Closed -> assert false | `Unsupported -> assert false | `Interrupted -> ()) |> Deferred.ignore_m in don't_wait_for event; interrupt in let needs_read = what = POLL_IN || what = POLL_INOUT in let needs_write = what = POLL_OUT || what = POLL_INOUT in let+ current = match Hashtbl.find_opt t.all_events fd with | Some fd -> Deferred.return fd | None -> Deferred.return { fd = Fd.create (Fd.Kind.Socket `Active) fd (Base.Info.createf "curl"); read = None; write = None; } in let update fd set_event set needs what = match (set, needs) with | None, false -> () | Some _, true -> () | None, true -> set_event (Some (create_event fd what)) | Some ivar, false -> Ivar.fill_exn ivar (); set_event None in update current.fd (fun ivar -> current.read <- ivar) current.read needs_read `Read; update current.fd (fun ivar -> current.write <- ivar) current.write needs_write `Write; Hashtbl.replace t.all_events fd current in Curl.Multi.set_socket_function t.mt (fun fd what -> don't_wait_for (socket_function fd what)); t let unregister t curl = Curl.Multi.remove t.mt curl; Hashtbl.remove t.wakeners curl let register t curl wk = Hashtbl.add t.wakeners curl wk; Curl.Multi.add t.mt curl end module Method = Http.Method module Header = Http.Header module Response = struct type 'a t = { curl : Curl.t; response : (Http.Response.t, Error.t) result Deferred.t; body : ('a, Error.t) result Deferred.t; context : Context.t; } let response t = t.response let body t = t.body let cancel t = Context.unregister t.context t.curl module Expert = struct let curl t = t.curl end end module Request = struct type 'a t = { body_ready : Curl.curlCode Ivar.t; response_ready : (Http.Response.t, Error.t) result Ivar.t; base : 'a Cohttp_curl.Request.t; } module Expert = struct let curl t = Cohttp_curl.Request.curl t.base end let create (type a) ?timeout ?headers method_ ~uri ~(input : Source.t) ~(output : a Sink.t) : a t = let response_ready = Ivar.create () in let body_ready = Ivar.create () in let base = let timeout_ms = Option.map (fun timeout -> Time.Span.to_ms timeout |> int_of_float) timeout in Cohttp_curl.Request.create ?timeout_ms ?headers method_ ~uri ~input ~output ~on_response:(fun response -> Ivar.fill_exn response_ready (Ok response)) in { base; response_ready; body_ready } end let submit (type a) context (request : a Request.t) : a Response.t = let curl = Cohttp_curl.Request.curl request.base in Context.register context curl request.body_ready; let body = Ivar.read request.body_ready >>| function | Curl.CURLE_OK -> Ok (Cohttp_curl.Request.body request.base : a) | code -> let error = Error (Error.create code) in Ivar.fill_exn request.response_ready error; error in { Response.body; context; response = Ivar.read request.response_ready; curl }
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
mli
cohttp-6.2.1/cohttp-curl-async/src/cohttp_curl_async.mli
(** Curl & Async based client *) module Sink : sig (** A sink defines where the response body may be written *) type 'a t val string : string t val discard : unit t end module Source : sig (** A source defines where the request body is read from *) type t val empty : t val string : string -> t end module Context : sig (** A context shares the curl event handling logic for all curl requests associated to it *) type t val create : unit -> t end module Error : sig type t val message : t -> string val is_timeout : t -> bool end module Response : sig (** Response for the http requests *) type 'a t (** ['a t] represents a response for a request. ['a] determines how the response body is handled *) val response : _ t -> (Http.Response.t, Error.t) result Async_kernel.Deferred.t val body : 'a t -> ('a, Error.t) result Async_kernel.Deferred.t val cancel : _ t -> unit module Expert : sig val curl : _ t -> Curl.t end end module Request : sig (** Http requests *) type 'a t (** ['a t] represents an http request ['a] determines how the response body is handled. *) val create : ?timeout:Core.Time_float.Span.t (** timeout for the request *) -> ?headers:Http.Header.t (** http headers *) -> Http.Method.t (** http method *) -> uri:string (** uri *) -> input:Source.t (** request body *) -> output:'a Sink.t (** response body *) -> 'a t module Expert : sig val curl : _ t -> Curl.t end end val submit : Context.t -> 'a Request.t -> 'a Response.t (** [submit ctx request] submits a request and returns the response. Once a request is submitted, it may not be submitted again. *)
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
dune
cohttp-6.2.1/cohttp-curl-async/src/dune
(library (name cohttp_curl_async) (libraries http cohttp-curl core curl stringext async_kernel async_unix))
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-curl-async/test/cohttp_curl_async_tests.ml
module Server = Cohttp_async.Server module Body = Cohttp_async.Body module Deferred = Async_kernel.Deferred open Async_kernel let ( let+ ) x f = Deferred.map x ~f let ( let* ) x f = Deferred.bind x ~f let server = List.map Cohttp_async_test.const [ (let body : Body.t = Body.of_string "hello curl" in Server.respond `OK ~body); ] |> Cohttp_async_test.response_sequence let test = Cohttp_async_test.test_server_s ~port:25_290 server (fun uri -> [ ( "simple request", fun () -> let uri = Uri.to_string uri in let input = Cohttp_curl_async.Source.empty in let output = Cohttp_curl_async.Sink.string in let ctx = Cohttp_curl_async.Context.create () in let req = Cohttp_curl_async.Request.create `GET ~uri ~input ~output in let resp = Cohttp_curl_async.submit ctx req in let+ body = Cohttp_curl_async.Response.body resp >>| function | Ok s -> s | Error _ -> assert false in Alcotest.check Alcotest.string "test 1" body "hello curl" ); ]) let _ = let run = let* _ = Cohttp_async_test.run_async_tests test in Async_unix.Shutdown.exit 0 in Deferred.don't_wait_for run; Core.never_returns (Async_unix.Scheduler.go ())
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
dune
cohttp-6.2.1/cohttp-curl-async/test/dune
(test (name cohttp_curl_async_tests) (libraries http core_kernel async_unix uri async_kernel alcotest cohttp_async_test cohttp_curl_async) (package cohttp-curl-async))
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
opam
cohttp-6.2.1/cohttp-curl-lwt.opam
version: "6.2.1" # This file is generated by dune, edit dune-project instead opam-version: "2.0" synopsis: "Cohttp client using Curl & Lwt as the backend" description: """ An HTTP client that relies on Curl + Lwt for the backend. Does not require conduit for SSL.""" maintainer: ["Anil Madhavapeddy <anil@recoil.org>"] authors: [ "Anil Madhavapeddy" "Stefano Zacchiroli" "David Sheets" "Thomas Gazagnaire" "David Scott" "Rudi Grinberg" "Andy Ray" "Anurag Soni" ] license: "ISC" homepage: "https://github.com/mirage/ocaml-cohttp" doc: "https://mirage.github.io/ocaml-cohttp/" bug-reports: "https://github.com/mirage/ocaml-cohttp/issues" depends: [ "dune" {>= "3.8"} "ocaml" {>= "4.08"} "ocurl" {>= "0.9.2"} "http" {= version} "cohttp-curl" {= version} "stringext" "lwt" {>= "5.3.0"} "cmdliner" {with-dev-setup & >= "2.0.0"} "uri" {with-test & >= "4.2.0"} "alcotest" {with-test & >= "1.7.0"} "cohttp-lwt-unix" {with-test & = version} "cohttp" {with-test & = version} "cohttp-lwt" {with-test & = version} "conduit-lwt" {with-test} "ounit2" {with-test} "odoc" {with-doc} ] dev-repo: "git+https://github.com/mirage/ocaml-cohttp.git" build: [ ["dune" "subst"] {dev} [ "dune" "build" "-p" name "-j" jobs "@install" "@cohttp-curl-lwt/runtest" {with-test} "@doc" {with-doc} ] ] x-maintenance-intent: [ "(latest)" ]
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-curl-lwt/bin/curl.ml
open Lwt.Syntax open Cohttp module Curl = Cohttp_curl_lwt module Sexp = Sexplib0.Sexp let src = Logs.Src.create "cohttp.lwt.curl" ~doc:"Cohttp Lwt curl implementation" module Log = (val Logs.src_log src : Logs.LOG) let client uri ofile meth' = Log.debug (fun d -> d "Client with URI %s" (Uri.to_string uri)); let meth = Cohttp.Code.method_of_string meth' in Log.debug (fun d -> d "Client %s issued" meth'); let reply = let context = Curl.Context.create () in let request = Curl.Request.create ~timeout_ms:5000 meth ~uri:(Uri.to_string uri) ~input:Curl.Source.empty ~output:Curl.Sink.string in Curl.submit context request in let* resp, response_body = Lwt.both (Curl.Response.response reply) (Curl.Response.body reply) in let resp, response_body = match (resp, response_body) with | Ok _, Error _ | Error _, Ok _ -> assert false | Ok x, Ok y -> (x, y) | Error _, Error e -> Format.eprintf "error: %s@.%!" (Curl.Error.message e); exit 1 in Format.eprintf "response:%a@.%!" Sexp.pp_hum (Response.sexp_of_t resp); let status = Response.status resp in Log.debug (fun d -> d "Client %s returned: %s" meth' (Code.string_of_status status)); (match Code.is_success (Code.code_of_status status) with | false -> prerr_endline (Code.string_of_status status) | true -> ()); let len = String.length response_body in Log.debug (fun d -> d "Client body length: %d" len); let output_body c = Lwt_io.write c response_body in match ofile with | None -> output_body Lwt_io.stdout | Some fname -> Lwt_io.with_file ~mode:Lwt_io.output fname output_body let debug = match Sys.getenv_opt "COHTTP_CURL_DEBUG" with None -> false | Some _ -> true let run_client level ofile uri meth = if debug then ( Fmt_tty.setup_std_outputs (); Logs.set_level ~all:true level); Lwt_main.run (client uri ofile meth) open Cmdliner let uri = let loc = let parser s = match Uri.of_string s with | uri -> Ok uri | exception Failure _ -> Error "unable to parse URI" in let pp ppf u = Format.fprintf ppf "%s" (Uri.to_string u) in Cmdliner.Arg.Conv.make ~parser ~pp ~docv:"URI" () in Arg.( required & pos 0 (some loc) None & info [] ~docv:"URI" ~doc:"string of the remote address (e.g. https://google.com)") let meth = let doc = "Set http method" in Arg.(value & opt string "GET" & info [ "X"; "request" ] ~doc) let verb = Logs_cli.level () let ofile = let doc = "Output filename to store the URI into." in Arg.(value & opt (some string) None & info [ "o" ] ~docv:"FILE" ~doc) let cmd = let info = let version = Cohttp.Conf.version in let doc = "retrieve a remote URI contents" in let man = [ `S "DESCRIPTION"; `P "$(tname) fetches the remote $(i,URI) and prints it to standard \ output. The output file can also be specified with the $(b,-o) \ option, and more verbose debugging out obtained via the $(b,-v) \ option."; `S "BUGS"; `P "Report them via e-mail to <mirageos-devel@lists.xenproject.org>, or \ on the issue tracker at \ <https://github.com/mirage/ocaml-cohttp/issues>"; `S "SEE ALSO"; `P "$(b,curl)(1), $(b,wget)(1)"; ] in Cmd.info "cohttp-curl" ~version ~doc ~man in let term = Term.(const run_client $ verb $ ofile $ uri $ meth) in Cmd.v info term let () = exit @@ Cmd.eval cmd
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
mli
cohttp-6.2.1/cohttp-curl-lwt/bin/curl.mli
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
dune
cohttp-6.2.1/cohttp-curl-lwt/bin/dune
(executable (name curl) (libraries sexplib0 cohttp cohttp_curl_lwt lwt.unix lwt logs logs.cli uri fmt.tty cmdliner))
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-curl-lwt/src/cohttp_curl_lwt.ml
(* {[ Copyright (c) 2003, Lars Nilsson, <lars@quantumchamaeleon.com> Copyright (c) 2009, ygrek, <ygrek@autistici.org> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]} *) module Cohttp_curl = Cohttp_curl.Private module Sink = Cohttp_curl.Sink module Source = Cohttp_curl.Source module Error = Cohttp_curl.Error open Lwt.Infix module Context = struct type t = { mt : Curl.Multi.mt; wakeners : (Curl.t, Curl.curlCode Lwt.u) Hashtbl.t; all_events : (Unix.file_descr, Lwt_engine.event list) Hashtbl.t; by_fd : (Unix.file_descr, Curl.t list) Hashtbl.t; mutable timer_event : Lwt_engine.event; } let unregister t curl = Curl.get_activesocket curl |> Option.iter (fun fd -> match Hashtbl.find_opt t.by_fd fd with | None -> () | Some curls -> Hashtbl.replace t.by_fd fd (List.filter (fun c -> c = curl) curls)); Curl.Multi.remove t.mt curl; Hashtbl.remove t.wakeners curl let create () = (* Most of this is taken from https://github.com/ygrek/ocurl/blob/master/curl_lwt.ml *) let t = { mt = Curl.Multi.create (); wakeners = Hashtbl.create 32; all_events = Hashtbl.create 32; by_fd = Hashtbl.create 32; timer_event = Lwt_engine.fake_event; } in let rec finished () = match Curl.Multi.remove_finished t.mt with | None -> () | Some (h, code) -> (match Hashtbl.find_opt t.wakeners h with | None -> () | Some w -> Hashtbl.remove t.wakeners h; Lwt.wakeup w code); finished () in let handle fd f = match f () with | (_ : int) -> finished () | exception exn -> ( match Hashtbl.find_opt t.by_fd fd with | None -> () | Some curls -> Hashtbl.remove t.by_fd fd; List.iter (fun curl -> match Hashtbl.find_opt t.wakeners curl with | None -> () | Some w -> Lwt.wakeup_exn w exn) curls) in let on_readable fd _ = handle fd (fun () -> Curl.Multi.action t.mt fd EV_IN) in let on_writable fd _ = handle fd (fun () -> Curl.Multi.action t.mt fd EV_OUT) in let on_timer _ = Lwt_engine.stop_event t.timer_event; (try Curl.Multi.action_timeout t.mt with exn -> (* I'm not sure where to report this error *) !Lwt.async_exception_hook exn); finished () in Curl.Multi.set_timer_function t.mt (fun timeout -> Lwt_engine.stop_event t.timer_event; t.timer_event <- Lwt_engine.on_timer (float_of_int timeout /. 1000.) false on_timer); Curl.Multi.set_socket_function t.mt (fun fd what -> (match Hashtbl.find_opt t.all_events fd with | None -> () | Some events -> List.iter Lwt_engine.stop_event events; Hashtbl.remove t.all_events fd); let events = match what with | POLL_REMOVE | POLL_NONE -> [] | POLL_IN -> [ Lwt_engine.on_readable fd (on_readable fd) ] | POLL_OUT -> [ Lwt_engine.on_writable fd (on_writable fd) ] | POLL_INOUT -> [ Lwt_engine.on_readable fd (on_readable fd); Lwt_engine.on_writable fd (on_writable fd); ] in match events with [] -> () | _ -> Hashtbl.add t.all_events fd events); t let register t curl wk = Hashtbl.add t.wakeners curl wk; Curl.Multi.add t.mt curl; match Curl.get_activesocket curl with | None -> assert false | Some fd -> ( match Hashtbl.find_opt t.by_fd fd with | None -> Hashtbl.replace t.by_fd fd [ curl ] | Some curls -> Hashtbl.replace t.by_fd fd (curl :: curls)) end module Method = Http.Method module Header = Http.Header module Response = struct type 'a t = { curl : Curl.t; response : (Http.Response.t, Error.t) result Lwt.t; body : ('a, Error.t) result Lwt.t; } let response t = t.response let body t = t.body module Expert = struct let curl t = t.curl end end module Request = struct type 'a t = { wk_body : Curl.curlCode Lwt.u; wt_body : Curl.curlCode Lwt.t; wt_response : (Http.Response.t, Error.t) result Lwt.t; wk_response : (Http.Response.t, Error.t) result Lwt.u; base : 'a Cohttp_curl.Request.t; } module Expert = struct let curl t = Cohttp_curl.Request.curl t.base end let create (type a) ?timeout_ms ?headers method_ ~uri ~input ~(output : a Sink.t) : a t = let wt_response, wk_response = Lwt.wait () in let wt_body, wk_body = Lwt.wait () in let wt_response = Lwt.protected wt_response in let wt_body = Lwt.protected wt_body in let base = Cohttp_curl.Request.create ?timeout_ms ?headers method_ ~uri ~input ~output ~on_response:(fun resp -> Lwt.wakeup wk_response (Ok resp)) in { base; wt_response; wk_body; wt_body; wk_response } end let submit (type a) context (request : a Request.t) : a Response.t = let curl = Cohttp_curl.Request.curl request.base in let cancel = lazy (Context.unregister context curl) in Lwt.on_cancel request.wt_response (fun () -> Lazy.force cancel); Lwt.on_cancel request.wt_body (fun () -> Lazy.force cancel); Context.register context curl request.wk_body; let body = request.wt_body >|= function | Curl.CURLE_OK -> Ok (Cohttp_curl.Request.body request.base : a) | code -> let error = Error (Error.create code) in Lwt.wakeup_later request.wk_response error; error in { Response.body; response = request.wt_response; curl }
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
mli
cohttp-6.2.1/cohttp-curl-lwt/src/cohttp_curl_lwt.mli
(** Curl based client *) module Sink : sig (** A sink defines where the response body may be written *) type 'a t val string : string t val discard : unit t end module Source : sig (** A source defines where the request body is read from *) type t val empty : t val string : string -> t end module Context : sig (** A context shares the curl event handling logic for all curl requests associated to it *) type t val create : unit -> t end module Error : sig type t val message : t -> string val is_timeout : t -> bool end module Response : sig (** Response for the http requests *) type 'a t (** ['a t] represents a response for a request. ['a] determines how the response body is handled *) val response : _ t -> (Http.Response.t, Error.t) result Lwt.t val body : 'a t -> ('a, Error.t) result Lwt.t module Expert : sig val curl : _ t -> Curl.t end end module Request : sig (** Http requests *) type 'a t (** ['a t] represents an http request ['a] determines how the response body is handled. *) val create : ?timeout_ms:int (** timeout for the request in milliseconds *) -> ?headers:Http.Header.t (** http headers *) -> Http.Method.t (** http method *) -> uri:string (** uri *) -> input:Source.t (** request body *) -> output:'a Sink.t (** response body *) -> 'a t module Expert : sig val curl : _ t -> Curl.t end end val submit : Context.t -> 'a Request.t -> 'a Response.t (** [submit ctx request] submits a request and returns the response. Once a request is submitted, it may not be submitted again. *)
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
dune
cohttp-6.2.1/cohttp-curl-lwt/src/dune
(library (name cohttp_curl_lwt) (public_name cohttp-curl-lwt) (libraries http cohttp-curl stringext lwt lwt.unix curl))
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-curl-lwt/test/cohttp_curl_lwt_tests.ml
module Server = Cohttp_lwt_unix.Server module Body = Cohttp_lwt.Body open Lwt.Syntax open Lwt.Infix let server = List.map Cohttp_lwt_unix_test.const [ (let body : Body.t = Body.of_string "hello curl" in Server.respond ~status:`OK ~body ()); ] |> Cohttp_lwt_unix_test.response_sequence let check_error = function Ok _ -> failwith "expected error" | Error _ -> () let without_error = function | Ok s -> s | Error e -> failwith (Cohttp_curl_lwt.Error.message e) let test = Cohttp_lwt_unix_test.test_server_s ~port:25_190 server (fun uri -> [ ( "simple request", fun () -> let uri = Uri.to_string uri in let input = Cohttp_curl_lwt.Source.empty in let output = Cohttp_curl_lwt.Sink.string in let ctx = Cohttp_curl_lwt.Context.create () in let req = Cohttp_curl_lwt.Request.create `GET ~uri ~input ~output in let resp = Cohttp_curl_lwt.submit ctx req in let+ body = Cohttp_curl_lwt.Response.body resp >|= without_error in Alcotest.check Alcotest.string "test 1" body "hello curl" ); ( "failing request", fun () -> let uri = "0.0.0.0:45_120" in let input = Cohttp_curl_lwt.Source.empty in let output = Cohttp_curl_lwt.Sink.string in let ctx = Cohttp_curl_lwt.Context.create () in let req = Cohttp_curl_lwt.Request.create `GET ~uri ~input ~output in let resp = Cohttp_curl_lwt.submit ctx req in let* http_resp = Cohttp_curl_lwt.Response.response resp in check_error http_resp; let+ body = Cohttp_curl_lwt.Response.body resp in check_error body ); ]) let _ = test |> Cohttp_lwt_unix_test.run_async_tests |> Lwt_main.run
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
dune
cohttp-6.2.1/cohttp-curl-lwt/test/dune
(test (name cohttp_curl_lwt_tests) (libraries http alcotest uri cohttp_lwt_unix_test cohttp_curl_lwt) (package cohttp-curl-lwt))
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
opam
cohttp-6.2.1/cohttp-curl.opam
version: "6.2.1" # This file is generated by dune, edit dune-project instead opam-version: "2.0" synopsis: "Shared code between the individual cohttp-curl clients" description: "Use cohttp-curl-lwt or cohttp-curl-async" maintainer: ["Anil Madhavapeddy <anil@recoil.org>"] authors: [ "Anil Madhavapeddy" "Stefano Zacchiroli" "David Sheets" "Thomas Gazagnaire" "David Scott" "Rudi Grinberg" "Andy Ray" "Anurag Soni" ] license: "ISC" homepage: "https://github.com/mirage/ocaml-cohttp" doc: "https://mirage.github.io/ocaml-cohttp/" bug-reports: "https://github.com/mirage/ocaml-cohttp/issues" depends: [ "dune" {>= "3.8"} "ocaml" {>= "4.08"} "ocurl" {>= "0.9.2"} "http" {= version} "stringext" "odoc" {with-doc} ] dev-repo: "git+https://github.com/mirage/ocaml-cohttp.git" build: [ ["dune" "subst"] {dev} [ "dune" "build" "-p" name "-j" jobs "@install" "@cohttp-curl/runtest" {with-test} "@doc" {with-doc} ] ] x-maintenance-intent: [ "(latest)" ]
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-curl/src/cohttp_curl.ml
module Sink = struct type _ t = String : string t | Discard : unit t let string = String let discard = Discard end module Error = struct type t = Curl.curlCode let create x = x let is_timeout (t : t) = match t with Curl.CURLE_OPERATION_TIMEOUTED -> true | _ -> false let message t = Curl.strerror t end module Source = struct type t = Empty | String of string let empty = Empty let string s = String s let to_curl_callback t = match t with | Empty -> fun _ -> "" | String s -> let len = String.length s in let pos = ref 0 in fun max_asked -> if !pos >= len then "" else let chunk_len = min (len - !pos) max_asked in let res = String.sub s !pos chunk_len in pos := !pos + chunk_len; res end module Request = struct type 'a t = { curl : Curl.t; body : 'a Sink.t; mutable body_buffer : Buffer.t option; } let curl t = t.curl let body (type a) (t : a t) : a = match t.body with | Discard -> assert (t.body_buffer = None); () | String -> let res = Buffer.contents (match t.body_buffer with None -> assert false | Some s -> s) in t.body_buffer <- None; res let create (type a) ?timeout_ms ?headers method_ ~uri ~(input : Source.t) ~(output : a Sink.t) ~on_response : a t = let response_header_acc = ref [] in let response_body = ref None in let h = Curl.init () in Curl.setopt h (CURLOPT_URL uri); Curl.setopt h (CURLOPT_CUSTOMREQUEST (Http.Method.to_string method_)); let () = match headers with | None -> () | Some headers -> let buf = Buffer.create 128 in let headers = Http.Header.fold (fun key value acc -> Buffer.clear buf; Buffer.add_string buf key; Buffer.add_string buf ": "; Buffer.add_string buf value; Buffer.contents buf :: acc) headers [] |> List.rev in Curl.setopt h (CURLOPT_HTTPHEADER headers) in Curl.setopt h (CURLOPT_HEADERFUNCTION (let status_code_ready = ref false in let response_http_version = ref None in fun header -> (match !status_code_ready with | false -> (match String.split_on_char ' ' header with | v :: _ -> response_http_version := Some (Http.Version.of_string v) | _ -> (* TODO *) invalid_arg "invalid request"); status_code_ready := true | true -> ( match header with | "\r\n" -> let response = let headers = Http.Header.of_list_rev !response_header_acc in response_header_acc := []; let status = match Curl.getinfo h CURLINFO_HTTP_CODE with | CURLINFO_Long l -> Http.Status.of_int l | _ -> assert false in let version = match !response_http_version with | None -> assert false | Some v -> v in Http.Response.make ~version ~status ~headers () in on_response response | _ -> let k, v = match Stringext.cut header ~on:":" with | None -> invalid_arg "proper abort needed" | Some (k, v) -> (String.trim k, String.trim v) in response_header_acc := (k, v) :: !response_header_acc)); String.length header)); Curl.setopt h (CURLOPT_READFUNCTION (Source.to_curl_callback input)); Curl.setopt h (CURLOPT_WRITEFUNCTION (match output with | Discard -> fun s -> String.length s | String -> let buf = Buffer.create 128 in response_body := Some buf; fun s -> Buffer.add_string buf s; String.length s)); (match timeout_ms with | None -> () | Some tms -> Curl.setopt h (CURLOPT_TIMEOUTMS tms)); { curl = h; body = output; body_buffer = !response_body } end module Private = struct module Error = Error module Sink = Sink module Source = Source module Request = Request end
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
mli
cohttp-6.2.1/cohttp-curl/src/cohttp_curl.mli
module Private : sig module Error : sig type t val create : Curl.curlCode -> t val message : t -> string val is_timeout : t -> bool end module Sink : sig type 'a t val string : string t val discard : unit t end module Source : sig type t val empty : t val string : string -> t end module Request : sig type 'a t val curl : _ t -> Curl.t val body : 'a t -> 'a (** [body t] this must be called after curl completes the requests. it can only be called once *) val create : ?timeout_ms:int -> ?headers:Http.Header.t -> Http.Method.t -> uri:string -> input:Source.t -> output:'a Sink.t -> on_response:(Http.Response.t -> unit) -> 'a t end end
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
dune
cohttp-6.2.1/cohttp-curl/src/dune
(library (name cohttp_curl) (public_name cohttp-curl) (libraries http curl stringext))
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
opam
cohttp-6.2.1/cohttp-eio.opam
version: "6.2.1" # This file is generated by dune, edit dune-project instead opam-version: "2.0" synopsis: "CoHTTP implementation with eio backend" description: "A CoHTTP server and client implementation based on `eio` library. `cohttp-eio`features a multicore capable HTTP 1.1 server. The library promotes and is built with direct style of coding as opposed to a monadic." maintainer: ["Anil Madhavapeddy <anil@recoil.org>"] authors: [ "Anil Madhavapeddy" "Stefano Zacchiroli" "David Sheets" "Thomas Gazagnaire" "David Scott" "Rudi Grinberg" "Andy Ray" "Anurag Soni" ] license: "ISC" homepage: "https://github.com/mirage/ocaml-cohttp" doc: "https://mirage.github.io/ocaml-cohttp/" bug-reports: "https://github.com/mirage/ocaml-cohttp/issues" depends: [ "dune" {>= "3.8"} "alcotest" {with-test & >= "1.7.0"} "base-domains" "cohttp" {= version} "eio" {>= "0.12"} "eio_main" {with-test} "mdx" {with-test} "ipaddr" {>= "5.6.0"} "logs" "uri" "tls-eio" {with-test & >= "1.0.0"} "mirage-crypto-rng" {with-test & >= "1.2.0"} "ca-certs" {with-test & >= "1.0.0"} "fmt" "ptime" "http" {= version} "ppx_here" {with-test} "odoc" {with-doc} ] dev-repo: "git+https://github.com/mirage/ocaml-cohttp.git" build: [ ["dune" "subst"] {dev} [ "dune" "build" "-p" name "-j" jobs "@install" "@cohttp-eio/runtest" {with-test} "@doc" {with-doc} ] ] x-maintenance-intent: [ "(latest)" ]
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-eio/examples/client1.ml
open Cohttp_eio let () = Logs.set_reporter (Logs_fmt.reporter ()) and () = (* The eio backend does not leverage domains yet, but might in the near future *) Logs_threaded.enable () and () = Logs.Src.set_level Cohttp_eio.src (Some Debug) let () = Eio_main.run @@ fun env -> let client = Client.make ~https:None env#net in Eio.Switch.run @@ fun sw -> let resp, body = Client.get ~sw client (Uri.of_string "http://example.com") in if Http.Status.compare resp.status `OK = 0 then print_string @@ Eio.Buf_read.(parse_exn take_all) body ~max_size:max_int else Fmt.epr "Unexpected HTTP status: %a" Http.Status.pp resp.status
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-eio/examples/client_proxy.ml
open Cohttp_eio let authenticator = match Ca_certs.authenticator () with | Ok x -> x | Error (`Msg m) -> Fmt.failwith "Failed to create system store X509 authenticator: %s" m let () = Logs.set_reporter (Logs_fmt.reporter ()); Logs_threaded.enable (); Logs.Src.set_level Cohttp_eio.src (Some Debug) let https ~authenticator = let tls_config = match Tls.Config.client ~authenticator () with | Error (`Msg msg) -> failwith ("tls configuration problem: " ^ msg) | Ok tls_config -> tls_config in fun uri socket -> let host = Option.bind (Uri.host uri) (fun x -> Domain_name.(host (of_string_exn x)) |> Result.to_option) in Tls_eio.client_of_flow ?host tls_config socket let get_request_exn ~sw client url = let resp, body = Client.get ~sw client url in match resp.status with | `OK -> Eio.traceln "%s" @@ Eio.Buf_read.(parse_exn take_all) body ~max_size:max_int | otherwise -> Fmt.epr "Unexpected HTTP status: %a\n" Http.Status.pp otherwise let run_client url cacert all_proxy no_proxy http_proxy https_proxy proxy_auth = let scheme_proxy = List.filter_map Fun.id [ Option.map (fun p -> ("http", p)) http_proxy; Option.map (fun p -> ("https", p)) https_proxy; ] in let proxy_headers = Option.map (fun credential -> Http.Header.init_with "Proxy-Authorization" (Cohttp.Auth.string_of_credential credential)) proxy_auth in Eio_main.run @@ fun env -> Mirage_crypto_rng_unix.use_default (); let net = env#net in let authenticator = match cacert with | None -> authenticator | Some pem -> (* Load a custom cacert from a file *) let fs = Eio.Stdenv.fs env in X509_eio.authenticator (`Ca_file Eio.Path.(fs / pem)) in Client.set_proxies ?proxy_headers ?default_proxy:all_proxy ?no_proxy_patterns:no_proxy ~scheme_proxies:scheme_proxy (); let client = Client.make ~https:(Some (https ~authenticator)) net in Eio.traceln ">>> Make calls in sequence"; Eio.Switch.run (fun sw -> get_request_exn ~sw client url; get_request_exn ~sw client url; get_request_exn ~sw client url); Eio.traceln ">>> Make calls concurrently"; Eio.Switch.run (fun sw -> for _ = 0 to 5 do Eio.Fiber.fork ~sw (fun () -> get_request_exn ~sw client url) done); Eio.traceln ">>> Make calls in parallel"; let dm = Eio.Stdenv.domain_mgr env in Eio.Fiber.all [ (fun () -> Eio.Domain_manager.run dm (fun () -> Eio.Switch.run (fun sw -> get_request_exn ~sw client url))); (fun () -> Eio.Domain_manager.run dm (fun () -> Eio.Switch.run (fun sw -> get_request_exn ~sw client url))); (fun () -> Eio.Domain_manager.run dm (fun () -> Eio.Switch.run (fun sw -> get_request_exn ~sw client url))); (fun () -> Eio.Domain_manager.run dm (fun () -> Eio.Switch.run (fun sw -> get_request_exn ~sw client url))); (fun () -> Eio.Domain_manager.run dm (fun () -> Eio.Switch.run (fun sw -> get_request_exn ~sw client url))); ] (* CLI Interface *) let uri_conv = let parser s = match Uri.of_string s with | uri -> Ok uri | exception Failure _ -> Error "unable to parse URI" in let pp ppf u = Fmt.pf ppf "%s" (Uri.to_string u) in Cmdliner.Arg.Conv.make ~parser ~pp ~docv:"URI" () let credential_conv = let parser s = match Base64.encode s with | Ok s -> s |> Fmt.str "Basic %s" |> Cohttp.Auth.credential_of_string |> Result.ok | Error (`Msg m) -> Error m in let pp ppf c = Fmt.pf ppf "%s" (Cohttp.Auth.string_of_credential c) in Cmdliner.Arg.Conv.make ~parser ~pp ~docv:"CREDENTIAL" () let uri = Cmdliner.Arg.( required & pos 0 (some uri_conv) None & info [] ~docv:"URI" ~doc:"string of the remote address (e.g. https://ocaml.org)") let all_proxy = let env = Cmdliner.Cmd.Env.info "ALL_PROXY" in Cmdliner.Arg.( value & opt (some uri_conv) None & info [ "all-proxy" ] ~env ~docv:"ALL_PROXY" ~doc:"Default proxy server") let no_proxy = let env = Cmdliner.Cmd.Env.info "NO_PROXY" in Cmdliner.Arg.( value & opt (some string) None & info [ "no-proxy" ] ~env ~docv:"NO_PROXY" ~doc:"Exclude matching hosts from proxying") let http_proxy = let env = Cmdliner.Cmd.Env.info "HTTP_PROXY" in Cmdliner.Arg.( value & opt (some uri_conv) None & info [ "http-proxy" ] ~env ~docv:"HTTP_PROXY" ~doc:"Proxy to use for requests using http") let https_proxy = let env = Cmdliner.Cmd.Env.info "HTTPS_PROXY" in Cmdliner.Arg.( value & opt (some uri_conv) None & info [ "https-proxy" ] ~env ~docv:"HTTPS_PROXY" ~doc:"Proxy to use for requests using https") let proxy_auth = Cmdliner.Arg.( value & opt (some credential_conv) None & info [ "proxy-auth" ] ~docv:"CREDENTIAL" ~doc:"Proxy credentials") let cacert = Cmdliner.Arg.( value & opt (some string) None & info [ "cacert" ] ~docv:"PEM_FILE" ~doc:"Custom cert file for https authentication") let cmd = let info = let version = Cohttp.Conf.version in let doc = "retrieve a remote URI contents" in Cmdliner.Cmd.info "client_proxy" ~version ~doc in let term = Cmdliner.Term.( const run_client $ uri $ cacert $ all_proxy $ no_proxy $ http_proxy $ https_proxy $ proxy_auth) in Cmdliner.Cmd.v info term let () = exit @@ Cmdliner.Cmd.eval cmd
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-eio/examples/client_timeout.ml
open Cohttp_eio let () = Eio_main.run @@ fun env -> let client = Client.make ~https:None env#net in (* Increment/decrement this value to see success/failure. *) let timeout_s = 0.01 in Eio.Time.with_timeout env#clock timeout_s (fun () -> Eio.Switch.run @@ fun sw -> let _, body = Client.get client ~sw (Uri.of_string "http://www.example.org") in Eio.Buf_read.(of_flow ~max_size:max_int body |> take_all) |> Result.ok) |> function | Ok s -> print_string s | Error (`Fatal e) -> Fmt.epr "fatal error: %s@." e | Error `Timeout -> Fmt.epr "Connection timed out@."
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-eio/examples/client_tls.ml
open Cohttp_eio let authenticator = match Ca_certs.authenticator () with | Ok x -> x | Error (`Msg m) -> Fmt.failwith "Failed to create system store X509 authenticator: %s" m let () = Logs.set_reporter (Logs_fmt.reporter ()); Logs_threaded.enable (); Logs.Src.set_level Cohttp_eio.src (Some Debug) let https ~authenticator = let tls_config = match Tls.Config.client ~authenticator () with | Error (`Msg msg) -> failwith ("tls configuration problem: " ^ msg) | Ok tls_config -> tls_config in fun uri raw -> let host = Uri.host uri |> Option.map (fun x -> Domain_name.(host_exn (of_string_exn x))) in Tls_eio.client_of_flow ?host tls_config raw let () = Eio_main.run @@ fun env -> Mirage_crypto_rng_unix.use_default (); let client = Client.make ~https:(Some (https ~authenticator)) env#net in Eio.Switch.run @@ fun sw -> let resp, body = Client.get ~sw client (Uri.of_string "https://example.com") in if Http.Status.compare resp.status `OK = 0 then print_string @@ Eio.Buf_read.(parse_exn take_all) body ~max_size:max_int else Fmt.epr "Unexpected HTTP status: %a" Http.Status.pp resp.status
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-eio/examples/docker_client.ml
module Switch = Eio.Switch module Net = Eio.Net module Stdenv = Eio.Stdenv module Client = Cohttp_eio.Client module Response = Http.Response module Status = Http.Status let () = Logs.set_reporter (Logs_fmt.reporter ()) and () = Logs.Src.set_level Cohttp_eio.src (Some Debug) let () = Eio_main.run @@ fun env -> let client = Client.make ~https:None env#net in Eio.Switch.run @@ fun sw -> let response, body = Client.get client ~sw @@ Uri.make ~scheme:"httpunix" ~host:"/var/run/docker.sock" ~path:"/version" () in let code = response |> Response.status |> Status.to_int in Printf.printf "Response code: %d\n" code; Printf.printf "Headers: %s\n" (response |> Response.headers |> Http.Header.to_string); let body = Eio.Buf_read.(of_flow ~max_size:max_int body |> take_all) in Printf.printf "Body of length: %d\n" (String.length body); print_endline ("Received body\n" ^ body)
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
dune
cohttp-6.2.1/cohttp-eio/examples/dune
(executables (names server1 server2 client1 docker_client client_timeout client_tls client_proxy) (libraries cohttp-eio cmdliner eio_main eio.unix fmt unix logs.fmt logs.threaded tls-eio ca-certs mirage-crypto-rng.unix)) (alias (name runtest) (package cohttp-eio) (deps server1.exe))
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-eio/examples/server1.ml
let text = "CHAPTER I. Down the Rabbit-Hole Alice was beginning to get very tired of \ sitting by her sister on the bank, and of having nothing to do: once or \ twice she had peeped into the book her sister was reading, but it had no \ pictures or conversations in it, <and what is the use of a book,> thought \ Alice <without pictures or conversations?> So she was considering in her \ own mind (as well as she could, for the hot day made her feel very sleepy \ and stupid), whether the pleasure of making a daisy-chain would be worth \ the trouble of getting up and picking the daisies, when suddenly a White \ Rabbit with pink eyes ran close by her. There was nothing so very \ remarkable in that; nor did Alice think it so very much out of the way to \ hear the Rabbit say to itself, <Oh dear! Oh dear! I shall be late!> (when \ she thought it over afterwards, it occurred to her that she ought to have \ wondered at this, but at the time it all seemed quite natural); but when \ the Rabbit actually took a watch out of its waistcoat-pocket, and looked at \ it, and then hurried on, Alice started to her feet, for it flashed across \ her mind that she had never before seen a rabbit with either a \ waistcoat-pocket, or a watch to take out of it, and burning with curiosity, \ she ran across the field after it, and fortunately was just in time to see \ it pop down a large rabbit-hole under the hedge. In another moment down \ went Alice after it, never once considering how in the world she was to get \ out again. The rabbit-hole went straight on like a tunnel for some way, and \ then dipped suddenly down, so suddenly that Alice had not a moment to think \ about stopping herself before she found herself falling down a very deep \ well. Either the well was very deep, or she fell very slowly, for she had \ plenty of time as she went down to look about her and to wonder what was \ going to happen next. First, she tried to look down and make out what she \ was coming to, but it was too dark to see anything; then she looked at the \ sides of the well, and noticed that they were filled with cupboards......" let () = Logs.set_reporter (Logs_fmt.reporter ()) and () = Logs.Src.set_level Cohttp_eio.src (Some Debug) let handler _socket request _body = match Http.Request.resource request with | "/" -> Cohttp_eio.Server.respond_string ~status:`OK ~body:text () | "/html" -> (* Use a plain flow to test chunked encoding *) let body = Eio.Flow.string_source text in Cohttp_eio.Server.respond () ~status:`OK ~headers:(Http.Header.of_list [ ("content-type", "text/html") ]) ~body | _ -> Cohttp_eio.Server.respond_string ~status:`Not_found ~body:"" () let log_warning ex = Logs.warn (fun f -> f "%a" Eio.Exn.pp ex) let () = let port = ref 8080 in Arg.parse [ ("-p", Arg.Set_int port, " Listening port number(8080 by default)") ] ignore "An HTTP/1.1 server"; Eio_main.run @@ fun env -> Eio.Switch.run @@ fun sw -> let socket = Eio.Net.listen env#net ~sw ~backlog:128 ~reuse_addr:true (`Tcp (Eio.Net.Ipaddr.V4.loopback, !port)) and server = Cohttp_eio.Server.make ~callback:handler () in Cohttp_eio.Server.run socket server ~on_error:log_warning
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-eio/examples/server2.ml
let () = Logs.set_reporter (Logs_fmt.reporter ()) and () = Logs.Src.set_level Cohttp_eio.src (Some Debug) let ( / ) = Eio.Path.( / ) (* To stream a file, we take the extra [writer] argument explicitly. This means that we stream the response while the function is still running and the file is still open. *) let handler dir _socket request _body writer = let path = Http.Request.resource request |> String.split_on_char '/' |> List.filter (( <> ) "") |> String.concat "/" in let path = if path = "" then "index.html" else path in Eio.Path.with_open_in (dir / path) @@ fun flow -> Cohttp_eio.Server.respond () ~status:`OK ~headers:(Http.Header.of_list [ ("content-type", "text/html") ]) ~body:flow writer let log_warning ex = Logs.warn (fun f -> f "%a" Eio.Exn.pp ex) let () = let port = ref 8080 in Arg.parse [ ("-p", Arg.Set_int port, " Listening port number(8080 by default)") ] ignore "An HTTP/1.1 server"; Eio_main.run @@ fun env -> Eio.Switch.run @@ fun sw -> (* Restrict to current directory: *) let htdocs = Eio.Stdenv.cwd env in let socket = Eio.Net.listen env#net ~sw ~backlog:128 ~reuse_addr:true (`Tcp (Eio.Net.Ipaddr.V4.loopback, !port)) and server = Cohttp_eio.Server.make ~callback:(handler htdocs) () in Cohttp_eio.Server.run socket server ~on_error:log_warning
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-eio/src/body.ml
type t = Eio.Flow.source_ty Eio.Resource.t type 't Eio.Flow.read_method += String of ('t -> string) module String_source = struct type t = { s : string; mutable offset : int } let single_read t dst = if t.offset = String.length t.s then raise End_of_file; let len = min (Cstruct.length dst) (String.length t.s - t.offset) in Cstruct.blit_from_string t.s t.offset dst 0 len; t.offset <- t.offset + len; len let original_string t = t.s let read_methods = [ String original_string ] let create s = { s; offset = 0 } end let of_string = let ops = Eio.Flow.Pi.source (module String_source) in fun s -> Eio.Resource.T (String_source.create s, ops)
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-eio/src/client.ml
open Eio.Std open Utils module Proxy = Cohttp.Proxy.Forward type connection = [ Eio.Flow.two_way_ty | Eio.Resource.close_ty ] r type t = sw:Switch.t -> Uri.t -> connection type proxies = (Uri.t, Uri.t) Proxy.servers let proxies : (Http.Header.t option * proxies) option Atomic.t = Atomic.make None let set_proxies ?no_proxy_patterns ?default_proxy ?(scheme_proxies = []) ?proxy_headers () = let servers = Proxy.make_servers ~no_proxy_patterns ~default_proxy ~scheme_proxies ~direct:Fun.id ~tunnel:Fun.id in Atomic.set proxies (Some (proxy_headers, servers)) let get_proxy uri = match Atomic.get proxies with | None -> None | Some (headers, proxies) -> ( match Proxy.get proxies uri with | None -> None | Some (Proxy.Direct _) as proxy -> proxy | Some (Proxy.Tunnel p) -> Some (Proxy.Tunnel (headers, p))) let call_on_socket ~sw ?headers ?body ?(chunked = false) meth uri socket = let body_length = if chunked then None else match body with | None -> Some 0L | Some (Eio.Resource.T (body, ops)) -> let module X = (val Eio.Resource.get ops Eio.Flow.Pi.Source) in List.find_map (function | Body.String m -> Some (String.length (m body) |> Int64.of_int) | _ -> None) X.read_methods in let request = Cohttp.Request.make_for_client ?headers ~chunked:(Option.is_none body_length) ?body_length meth uri in Eio.Buf_write.with_flow socket @@ fun output -> let () = Eio.Fiber.fork ~sw @@ fun () -> Io.Request.write ~flush:false (fun writer -> match body with | None -> () | Some body -> flow_to_writer body writer Io.Request.write_body) request output in let input = Eio.Buf_read.of_flow ~max_size:max_int socket in match Io.Response.read input with | `Eof -> failwith "connection closed by peer" | `Invalid reason -> failwith reason | `Ok response -> ( match Cohttp.Response.has_body response with | `No -> (response, Eio.Flow.string_source "") | `Yes | `Unknown -> let body = let reader = Io.Response.make_body_reader response input in flow_of_reader (fun () -> Io.Response.read_body_chunk reader) in (response, body)) include Cohttp.Generic.Client.Make (struct type 'a io = 'a type body = Body.t type 'a with_context = t -> sw:Eio.Switch.t -> 'a let map_context v f t ~sw = f (v t ~sw) let call (t : t) ~sw ?headers ?body ?(chunked = false) meth uri = let socket = t ~sw uri in call_on_socket ~sw ?headers ?body ~chunked meth uri socket end) (Io.IO) let make_generic fn = (fn :> t) let unix_address uri = match Uri.host uri with | Some path -> `Unix path | None -> Fmt.failwith "no host specified (in %a)" Uri.pp uri let tcp_address ~net uri = let service = match Uri.port uri with | Some port -> Int.to_string port | _ -> Uri.scheme uri |> Option.value ~default:"http" in match Eio.Net.getaddrinfo_stream ~service net (Uri.host_with_default ~default:"localhost" uri) with | ip :: _ -> ip | [] -> failwith "failed to resolve hostname" (* Create a socket for the uri, and signal whether it requires https *) let scheme_conn_of_uri ~sw net uri = match Uri.scheme uri with | Some "httpunix" -> (* FIXME: while there is no standard, http+unix seems more widespread *) `Plain (Eio.Net.connect ~sw net (unix_address uri) :> connection) | Some "http" -> `Plain (Eio.Net.connect ~sw net (tcp_address ~net uri) :> connection) | Some "https" -> `Https (Eio.Net.connect ~sw net (tcp_address ~net uri) :> connection) | x -> Fmt.failwith "Unknown scheme %a" Fmt.(option ~none:(any "None") Dump.string) x (* Create a tunnel to the proxy at [proxy_uri] *) let make_tunnel ~sw ~headers proxy_uri socket = let resp, _ = call_on_socket ~sw ?headers `CONNECT proxy_uri socket in match Http.Response.status resp with | #Http.Status.success -> Ok () | _ -> Error (Http.Response.status resp) (* Apply the https wrapper, if provided, or else fail with an error *) let apply_https https uri conn = match https with | None -> Fmt.failwith "HTTPS not enabled (for %a)" Uri.pp uri | Some wrap -> (wrap uri conn :> connection) let make ~https net : t = fun ~sw uri -> let scheme_conn = match get_proxy uri with | None -> scheme_conn_of_uri ~sw net uri | Some (Proxy.Direct proxy_uri) -> scheme_conn_of_uri ~sw net proxy_uri | Some (Proxy.Tunnel (proxy_headers, proxy_uri)) -> ( let conn = match scheme_conn_of_uri ~sw net proxy_uri with | `Plain socket -> socket | `Https socket -> apply_https https proxy_uri socket in match make_tunnel ~sw ~headers:proxy_headers uri conn with | Ok () -> (* we know its an https connection, because we have selected a tunnelling proxy *) `Https conn | Error status -> Fmt.failwith "Proxy could not form tunnel to %a for host %a; status %a" Uri.pp proxy_uri Uri.pp uri Http.Status.pp status) in match scheme_conn with | `Plain conn -> conn | `Https conn -> apply_https https uri conn
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
mli
cohttp-6.2.1/cohttp-eio/src/client.mli
open Eio.Std type t include Cohttp.Generic.Client.S with type 'a with_context = t -> sw:Switch.t -> 'a and type 'a io = 'a and type body = Body.t val make : https: (Uri.t -> [ Eio.Flow.two_way_ty | Eio.Resource.close_ty ] Eio.Std.r -> [> Eio.Resource.close_ty ] Eio.Flow.two_way) option -> _ Eio.Net.t -> t (** [make ~https net] is a convenience wrapper around {!make_generic} that uses [net] to make connections. - URIs of the form "http://host:port/..." connect to the given TCP host and port. - URIs of the form "https://host:port/..." connect to the given TCP host and port, and are then wrapped by [https] (or rejected if that is [None]). - URIs of the form "httpunix://unix-path/http-path" connect to the given Unix path. *) val make_generic : (sw:Switch.t -> Uri.t -> [> Eio.Resource.close_ty ] Eio.Flow.two_way) -> t (** [make_generic connect] is an HTTP client that uses [connect] to get the connection to use for a given URI. *) val set_proxies : ?no_proxy_patterns:string -> ?default_proxy:Uri.t -> ?scheme_proxies:(string * Uri.t) list -> ?proxy_headers:Http.Header.t -> unit -> unit (** [set_proxies ~default_proxy ()] configures the proxies used by clients created via {!val:make}. See {!val:Cohttp.Proxy.Forward.make_servers} for the meaning of the parameters. *)
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-eio/src/cohttp_eio.ml
module Body = Body module Client = Client module Server = Server module Private = struct module IO = Io.IO end let src = Utils.src
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
dune
cohttp-6.2.1/cohttp-eio/src/dune
(library (name cohttp_eio) (public_name cohttp-eio) (libraries cohttp eio fmt http logs ptime uri uri.services ipaddr))
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-eio/src/io.ml
let src = Logs.Src.create "cohttp.eio.io" ~doc:"Cohttp Eio IO module" module Logs = (val Logs.src_log src : Logs.LOG) module IO = struct type 'a t = 'a let ( >>= ) v f = f v let return v = v type ic = Eio.Buf_read.t type oc = Eio.Buf_write.t type conn = Eio.Switch.t * Eio.Net.Sockaddr.stream let refill ic = try let () = Eio.Buf_read.(ensure ic (buffered_bytes ic + 1)) in `Ok with End_of_file -> `Eof let with_input_buffer ic ~f = let contents = Eio.Buf_read.peek ic in let res, consumed = f (Cstruct.to_string contents) ~pos:0 ~len:(Cstruct.length contents) in let () = Eio.Buf_read.consume ic consumed in res let read_line ic = try let line = Eio.Buf_read.line ic in let () = Logs.debug (fun f -> f "<<< %s" line) in Some line with End_of_file -> let () = Logs.debug (fun f -> f "<<< EOF") in None let read ic len = match Eio.Buf_read.ensure ic 1 with | exception End_of_file -> let () = Logs.debug (fun f -> f "<<< EOF") in "" | () -> let len = Int.min len (Eio.Buf_read.buffered_bytes ic) in let read = Eio.Buf_read.take len ic in let () = Logs.debug (fun f -> f "<<< %s" read) in read let write oc string = let () = Logs.debug (fun f -> f ">>> %s" (String.trim string)) in Eio.Buf_write.string oc string let flush = Eio.Buf_write.flush end module Request = Cohttp.Request.Private.Make (IO) module Response = Cohttp.Response.Private.Make (IO) module Transfer = Cohttp.Private.Transfer_io.Make (IO)
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
mli
cohttp-6.2.1/cohttp-eio/src/io.mli
module IO : Cohttp.S.IO with type 'a t = 'a and type conn = Eio.Switch.t * Eio.Net.Sockaddr.stream and type ic = Eio.Buf_read.t and type oc = Eio.Buf_write.t module Request : Cohttp.S.Http_io with type t := Http.Request.t and module IO := IO module Response : Cohttp.S.Http_io with type t := Http.Response.t and module IO := IO (* module Transfer : module type of Cohttp.Private.Transfer_io.Make (IO) *)
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-eio/src/server.ml
open Utils module IO = Io.IO type body = Body.t type conn = IO.conn * Cohttp.Connection.t [@@warning "-3"] type writer = Http.Request.t * IO.oc type response = writer -> unit type response_action = [ `Expert of Http.Response.t * (IO.ic -> IO.oc -> unit) | `Response of response ] type t = { conn_closed : conn -> unit; handler : conn -> Http.Request.t -> body -> IO.ic -> IO.oc -> unit; } let make_response_action ?(conn_closed = fun _ -> ()) ~callback () = { conn_closed; handler = (fun conn request body ic oc -> match callback conn request body with | `Expert (response, handler) -> Io.Response.write_header response oc; handler ic oc | `Response fn -> fn (request, oc)); } let make_expert ?conn_closed ~callback () = make_response_action ?conn_closed ~callback:(fun conn request body -> let expert = callback conn request body in `Expert expert) () let make ?(conn_closed = fun _ -> ()) ~callback () = { conn_closed; handler = (fun conn request body _ic oc -> callback conn request body (request, oc)); } let read input = match Io.Request.read input with | (`Eof | `Invalid _) as e -> e | `Ok request -> ( match Http.Request.has_body request with | `No -> `Ok (request, Eio.Flow.string_source "") | _ -> let body = let reader = Io.Request.make_body_reader request input in flow_of_reader (fun () -> Io.Request.read_body_chunk reader) in `Ok (request, body)) let write output (response : Cohttp.Response.t) body = let response = let content_length = let (Eio.Resource.T (body, ops)) = body in let module X = (val Eio.Resource.get ops Eio.Flow.Pi.Source) in List.find_map (function | Body.String get -> Some (String.length (get body)) | _ -> None) X.read_methods in (* encoding field might be deprecated but it is still used to compute headers and encode the body*) match (Cohttp.Header.get_transfer_encoding response.headers, content_length) with | Unknown, None -> let headers = Cohttp.Header.add_transfer_encoding response.headers Chunked in { response with headers } | Unknown, Some size -> let headers = Cohttp.Header.add_transfer_encoding response.headers (Fixed (Int64.of_int size)) in { response with headers } | _, _ -> response in let () = Logs.debug (fun m -> m "send headers") in let () = Io.Response.write ~flush:false (fun writer -> let () = Logs.debug (fun m -> m "send body (%a)" Cohttp.Transfer.pp_encoding (Cohttp.Header.get_transfer_encoding response.headers)) in flow_to_writer body writer Io.Response.write_body) response output in Eio.Buf_write.flush output let respond ?encoding ?(headers = Cohttp.Header.init ()) ~status ~body () (request, oc) = let keep_alive = Http.Request.is_keep_alive request in let headers = match Cohttp.Header.connection headers with | Some _ -> headers | None -> Http.Header.add headers "connection" (if keep_alive then "keep-alive" else "close") in let response = Cohttp.Response.make ?encoding ~headers ~status () in write oc response body let respond_string ?headers ~status ~body () = respond ~encoding:(Fixed (String.length body |> Int64.of_int)) ?headers ~status ~body:(Body.of_string body) () let respond ?headers ~status ~body () response = respond ?encoding:None ?headers ~status ~body () response let callback { conn_closed; handler } ((_, peer_address) as conn) input output = let id = (Cohttp.Connection.create () [@ocaml.warning "-3"]) in let rec handle () = match read input with | `Eof -> let () = Logs.info (fun m -> m "%a: disconnected" Eio.Net.Sockaddr.pp peer_address) in conn_closed (conn, id) | exception Eio.Io (Eio.Net.E (Connection_reset _), _) -> let () = Logs.info (fun m -> m "%a: connection reset" Eio.Net.Sockaddr.pp peer_address) in () | `Invalid e -> write output (Http.Response.make ~status:`Bad_request ()) (Body.of_string e) | `Ok (request, body) -> let () = try handler (conn, id) request body input output with Eio.Io (Eio.Net.E (Connection_reset _), _) -> Logs.info (fun m -> m "%a: connection reset" Eio.Net.Sockaddr.pp peer_address) in if Cohttp.Request.is_keep_alive request then handle () in handle () let run ?max_connections ?additional_domains ?stop ~on_error socket server = Eio.Net.run_server socket ?max_connections ?additional_domains ?stop ~on_error (fun socket peer_address -> Eio.Switch.run @@ fun sw -> let () = Logs.info (fun m -> m "%a: accept connection" Eio.Net.Sockaddr.pp peer_address) and input = Eio.Buf_read.of_flow ~max_size:max_int socket in try Eio.Buf_write.with_flow socket @@ fun output -> callback server (sw, peer_address) input output with Eio.Io (Eio.Net.E (Connection_reset _), _) -> Logs.info (fun m -> m "%a: connection reset" Eio.Net.Sockaddr.pp peer_address))
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
mli
cohttp-6.2.1/cohttp-eio/src/server.mli
type writer include Cohttp.Generic.Server.S with module IO = Io.IO and type body = Body.t and type response = writer -> unit val respond : ?headers:Http.Header.t -> status:Http.Status.t -> body:_ Eio.Flow.source -> unit -> response IO.t val run : ?max_connections:int -> ?additional_domains:_ Eio__Domain_manager.t * int -> ?stop:'a Eio.Promise.t -> on_error:(exn -> unit) -> _ Eio.Net.listening_socket -> t -> 'a
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-eio/src/utils.ml
let src = Logs.Src.create "cohttp.eio" ~doc:"Cohttp Eio backend" module Logs = (val Logs.src_log src) module Reader_flow = struct type t = { read_body_chunk : unit -> Cohttp.Transfer.chunk; mutable buffered : (string * int) option; } let v read_body_chunk = { read_body_chunk; buffered = None } let single_read t output = let output_length = Cstruct.length output in let send buffer pos = let available = String.length buffer - pos in if output_length >= available then let () = Cstruct.blit_from_string buffer pos output 0 available and () = t.buffered <- None in available else let () = Cstruct.blit_from_string buffer 0 output 0 output_length and () = t.buffered <- Some (buffer, pos + output_length) in output_length in match t.buffered with | Some (buffer, pos) -> send buffer pos | None -> ( match t.read_body_chunk () with | Cohttp.Transfer.Done -> let () = Logs.debug (fun m -> m "end of inbound body") in raise End_of_file | Chunk data | Final_chunk data -> let () = Logs.debug (fun m -> m "received %d bytes of body" (String.length data)) in send data 0) let read_methods = [] end let flow_of_reader = let handler = Eio.Flow.Pi.source (module Reader_flow) in fun read_body_chunk -> Eio.Resource.T (Reader_flow.v read_body_chunk, handler) let flow_to_writer flow writer write_body = let input = Eio.Buf_read.of_flow ~max_size:max_int flow in let rec loop () = let () = let () = Eio.Buf_read.ensure input 1 in let contents = Eio.Buf_read.(take (buffered_bytes input) input) in let () = Logs.debug (fun m -> m "send %d bytes of body" (String.length contents)) in write_body writer contents in loop () in try loop () with End_of_file -> let () = Logs.debug (fun m -> m "end of outbound body") in ()
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
dune
cohttp-6.2.1/cohttp-eio/tests/dune
(test (name test) (modules test) (libraries alcotest cohttp-eio eio eio.mock eio_main logs.fmt) (package cohttp-eio) (preprocess (pps ppx_here))) (test (name test_forward_proxy) (modules test_forward_proxy) (libraries alcotest cohttp-eio eio eio.mock eio_main logs.fmt) (package cohttp-eio))
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-eio/tests/test.ml
let () = Logs.set_level ~all:true @@ Some Logs.Debug; Logs.set_reporter (Logs_fmt.reporter ()) let handler _conn request body = match Http.Request.resource request with | "/" -> Cohttp_eio.Server.respond_string ~status:`OK ~body:"root" () | "/stream" -> let body = Eio_mock.Flow.make "streaming body" in let () = Eio_mock.Flow.on_read body [ `Return "Hello"; `Yield_then (`Return "World") ] in Cohttp_eio.Server.respond ~status:`OK ~body () | "/post" -> Cohttp_eio.Server.respond ~status:`OK ~body () | _ -> Cohttp_eio.Server.respond_string ~status:`Not_found ~body:"" () let () = Eio_main.run @@ fun env -> Eio.Switch.run @@ fun sw -> let () = let socket = Eio.Net.listen env#net ~sw ~backlog:128 ~reuse_addr:true ~reuse_port:true (`Tcp (Eio.Net.Ipaddr.V4.loopback, 4242)) and server = Cohttp_eio.Server.make ~callback:handler () in Eio.Fiber.fork_daemon ~sw @@ fun () -> let () = Cohttp_eio.Server.run socket server ~on_error:raise in `Stop_daemon in let test_case name f = let f () = let socket = Eio.Net.connect ~sw env#net (`Tcp (Eio.Net.Ipaddr.V4.loopback, 4242)) in f socket in Alcotest.test_case name `Quick f in let root socket = let () = Eio.Flow.write socket [ Cstruct.of_string "GET / HTTP/1.1\r\nconnection: close\r\n\r\n" ] in Alcotest.(check ~here:[%here] string) "response" "HTTP/1.1 200 OK\r\nconnection: close\r\ncontent-length: 4\r\n\r\nroot" Eio.Buf_read.(of_flow ~max_size:max_int socket |> take_all) and missing socket = let () = Eio.Flow.write socket [ Cstruct.of_string "GET /missing HTTP/1.1\r\nconnection: close\r\n\r\n"; ] in Alcotest.(check ~here:[%here] string) "response" "HTTP/1.1 404 Not Found\r\nconnection: close\r\ncontent-length: 0\r\n\r\n" Eio.Buf_read.(of_flow ~max_size:max_int socket |> take_all) and streaming_response socket = let () = Eio.Flow.write socket [ Cstruct.of_string "GET /stream HTTP/1.1\r\nconnection: close\r\n\r\n"; ] in Alcotest.(check ~here:[%here] string) "response" "HTTP/1.1 200 OK\r\n\ connection: close\r\n\ transfer-encoding: chunked\r\n\ \r\n\ 5\r\n\ Hello\r\n\ 5\r\n\ World\r\n\ 0\r\n\ \r\n" Eio.Buf_read.(of_flow ~max_size:max_int socket |> take_all) and request_body socket = let () = Eio.Flow.write socket [ Cstruct.of_string "POST /post HTTP/1.1\r\n\ connection: close\r\n\ content-length:12\r\n\ \r\n\ hello world!"; ] in Alcotest.(check ~here:[%here] string) "response" "HTTP/1.1 200 OK\r\n\ connection: close\r\n\ transfer-encoding: chunked\r\n\ \r\n\ c\r\n\ hello world!\r\n\ 0\r\n\ \r\n" Eio.Buf_read.(of_flow ~max_size:max_int socket |> take_all) in Alcotest.run "cohttp-eio" [ ( "cohttp-eio server", [ test_case "root" root; test_case "missing" missing; test_case "streaming response" streaming_response; test_case "request body" request_body; ] ); ]
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-eio/tests/test_forward_proxy.ml
(* Tests the core behaviour if the forward proxy *) let () = Logs.set_level ~all:true @@ Some Logs.Debug; Logs.set_reporter (Logs_fmt.reporter ()) (* Used to pass data out of the server *) module Req_data = struct let side_channel : Http.Request.t Eio.Stream.t = Eio.Stream.create 1 let send t = Eio.Stream.add side_channel t let get () = if Eio.Stream.is_empty side_channel then failwith "no requests pending"; Eio.Stream.take side_channel end let t_meth : Http.Method.t Alcotest.testable = Alcotest.testable Http.Method.pp (fun a b -> Http.Method.compare a b = 0) (* The proxy server sends every request to the `Req_data` side channel and always responds with 200. *) let run_proxy_server server_port net sw = let handler ~sw _conn request body = let _ = Eio.Buf_read.(of_flow ~max_size:max_int body |> take_all) in Eio.Fiber.fork ~sw (fun () -> Req_data.send request); Cohttp_eio.Server.respond_string ~status:`OK ~body:"" () in let socket = Eio.Net.listen net ~sw ~backlog:128 ~reuse_addr:true ~reuse_port:true (`Tcp (Eio.Net.Ipaddr.V4.loopback, server_port)) and server = Cohttp_eio.Server.make ~callback:(handler ~sw) () in Eio.Fiber.fork_daemon ~sw @@ fun () -> let () = Cohttp_eio.Server.run socket server ~on_error:raise in `Stop_daemon let () = (* Different tests run in parallel, so the port should be unique among tests *) let server_port = 4243 in let () = Cohttp_eio.Client.set_proxies ~default_proxy: (Uri.of_string @@ Printf.sprintf "http://127.0.0.1:%d" server_port) () in Eio_main.run @@ fun env -> Eio.Switch.run @@ fun sw -> let () = run_proxy_server server_port env#net sw in let client = let noop_https_wrapper = Some (fun _ f -> f) in Cohttp_eio.Client.make ~https:noop_https_wrapper env#net in let get_success uri = let resp, _ = Cohttp_eio.Client.get ~sw client uri in match Http.Response.status resp with | `OK -> () | unexpected -> Alcotest.failf "unexpected response from test_forward_proxy server %a" Http.Status.pp unexpected in (* TESTS CASES *) let direct_proxied_request () = (* When the remote host is over HTTP *) let uri = Uri.of_string "http://foo.org" in get_success uri; let req = Req_data.get () in let meth = Http.Request.meth req in Alcotest.(check' t_meth) ~msg:"should be a GET request" ~actual:meth ~expected:`GET; let host = let headers = Http.Request.headers req in Http.Header.get headers "host" in Alcotest.(check' (option string)) ~msg:"should request from remote host" ~actual:host ~expected:(Some "foo.org") and tunnelled_proxied_request () = (* When the remote host is over HTTPS *) let uri = Uri.of_string "https://foo.org" in get_success uri; let req = Req_data.get () in let meth = Http.Request.meth req in Alcotest.(check' t_meth) ~msg:"should first initiate a CONNECT request" ~actual:meth ~expected:`CONNECT; let host = let headers = Http.Request.headers req in Http.Header.get headers "host" in Alcotest.(check' (option string)) ~msg:"should request from remote host (with port)" ~actual:host ~expected:(Some "foo.org:443"); let req' = Req_data.get () in let meth' = Http.Request.meth req' in Alcotest.(check' t_meth) ~msg:"should then send a GET request" ~actual:meth' ~expected:`GET; let host = let headers = Http.Request.headers req in Http.Header.get headers "host" in Alcotest.(check' (option string)) ~msg:"should request from remote host (with port)" ~actual:host ~expected:(Some "foo.org:443") and unset_proxy () = let () = Cohttp_eio.Client.set_proxies ?default_proxy:None () in (* .invalid domains are guaranteed to not have hosts: https://www.rfc-editor.org/rfc/rfc2606 *) let uri = Uri.of_string "http://foo.invalid" in match Cohttp_eio.Client.get ~sw client uri with | exception Failure _ -> (* This should fail, since we are not using the proxy *) () | unexepcted_resp, _ -> Alcotest.failf "Resolution of uri should have failed, but succeeded with %a" Http.Response.pp unexepcted_resp in Alcotest.run "cohttp-eio client" [ ( "cohttp-eio forward proxy", [ ("direct get", `Quick, direct_proxied_request); ("tunnelled proxied request", `Quick, tunnelled_proxied_request); ("unessting the proxy config", `Quick, unset_proxy); ] ); ]
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
opam
cohttp-6.2.1/cohttp-lwt-jsoo.opam
version: "6.2.1" # This file is generated by dune, edit dune-project instead opam-version: "2.0" synopsis: "CoHTTP implementation for the Js_of_ocaml JavaScript compiler" description: """ An implementation of an HTTP client for JavaScript, but using the CoHTTP types. This lets you build HTTP clients that can compile natively (using one of the other Cohttp backends such as `cohttp-lwt-unix`) and also to native JavaScript via js_of_ocaml. """ maintainer: ["Anil Madhavapeddy <anil@recoil.org>"] authors: [ "Anil Madhavapeddy" "Stefano Zacchiroli" "David Sheets" "Thomas Gazagnaire" "David Scott" "Rudi Grinberg" "Andy Ray" "Anurag Soni" ] license: "ISC" homepage: "https://github.com/mirage/ocaml-cohttp" doc: "https://mirage.github.io/ocaml-cohttp/" bug-reports: "https://github.com/mirage/ocaml-cohttp/issues" depends: [ "dune" {>= "3.8"} "ocaml" {>= "4.08"} "http" {= version} "cohttp" {= version} "cohttp-lwt" {= version} "logs" "lwt" {>= "5.7.0"} "lwt_ppx" {with-test} "conf-npm" {with-test} "js_of_ocaml" {>= "3.3.0"} "js_of_ocaml-ppx" {>= "3.3.0"} "js_of_ocaml-lwt" {>= "3.5.0"} "odoc" {with-doc} ] dev-repo: "git+https://github.com/mirage/ocaml-cohttp.git" build: [ ["dune" "subst"] {dev} [ "dune" "build" "-p" name "-j" jobs "@install" "@cohttp-lwt-jsoo/runtest" {with-test} "@doc" {with-doc} ] ] x-maintenance-intent: [ "(latest)" ]
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-lwt-jsoo/src/cohttp_lwt_jsoo.ml
(*{{{ Copyright (c) 2014 Andy Ray * Copyright (c) 2014 Anil Madhavapeddy <anil@recoil.org> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * }}}*) open Js_of_ocaml module C = Cohttp module CLB = Cohttp_lwt.Body let ( >>= ) = Lwt.( >>= ) let ( >|= ) = Lwt.( >|= ) module type Params = sig val chunked_response : bool val chunk_size : int val convert_body_string : Js.js_string Js.t -> string val with_credentials : bool end let xhr_response_supported = (* from http://stackoverflow.com/questions/8926505/how-to-feature-detect-if-xmlhttprequest-supports-responsetype-arraybuffer *) lazy (let xhr = XmlHttpRequest.create () in let rt = xhr##.responseType in Js.to_string (Js.typeof rt) = "string") let binary_string str = let len = String.length str in let a = new%js Typed_array.uint8Array len in for i = 0 to len - 1 do Typed_array.set a i (Char.code str.[i]) done; a let string_of_uint8array u8a offset len = String.init len (fun i -> Char.chr (Typed_array.unsafe_get u8a (offset + i))) module String_io = Cohttp.Private.String_io module IO = struct include Cohttp_lwt.Private.String_io type error = | let catch f = Lwt.map (fun v -> Result.Ok v) @@ f () let pp_error _ (e : error) = match e with _ -> . end module Header_io = Cohttp.Private.Header_io.Make (IO) module Body_builder (P : Params) = struct let src = Logs.Src.create "cohttp.lwt.jsoo" ~doc:"Cohttp Lwt JSOO module" module Log = (val Logs.src_log src : Logs.LOG) (* perform the body transfer in chunks from string. *) let chunked_body_str text = let body_len = text##.length in let pos = ref 0 in let chunkerizer () = if !pos = body_len then Lwt.return C.Transfer.Done else if !pos + P.chunk_size >= body_len then ( let str = text##(substring_toEnd !pos) in pos := body_len; Lwt.return (C.Transfer.Final_chunk (P.convert_body_string str))) else let str = text##(substring !pos (!pos + P.chunk_size)) in pos := !pos + P.chunk_size; Lwt.return (C.Transfer.Chunk (P.convert_body_string str)) in if body_len = 0 then CLB.empty else CLB.of_stream (CLB.create_stream chunkerizer ()) (* perform the body transfer in chunks from arrayBuffer. *) let chunked_body_binary (ab : Typed_array.arrayBuffer Js.t) = let body_len = ab##.byteLength in let u8a = new%js Typed_array.uint8Array_fromBuffer ab in let pos = ref 0 in let chunkerizer () = if !pos = body_len then Lwt.return C.Transfer.Done else if !pos + P.chunk_size >= body_len then ( let str = string_of_uint8array u8a !pos (body_len - !pos) in pos := body_len; Lwt.return (C.Transfer.Final_chunk str)) else let str = string_of_uint8array u8a !pos P.chunk_size in pos := !pos + P.chunk_size; Lwt.return (C.Transfer.Chunk str) in if body_len = 0 then CLB.empty else CLB.of_stream (CLB.create_stream chunkerizer ()) (* choose between chunked and direct transfer *) let get = function | `String js_str -> if P.chunked_response then chunked_body_str js_str else CLB.of_string (P.convert_body_string js_str) | `ArrayBuffer ab -> if P.chunked_response then chunked_body_binary ab else let u8a = new%js Typed_array.uint8Array_fromBuffer ab in CLB.of_string (string_of_uint8array u8a 0 ab##.byteLength) let construct_body xml = (* construct body *) let b = let respText () = Js.Opt.case xml##.responseText (fun () -> `String (Js.string "")) (fun s -> `String s) in match Lazy.force xhr_response_supported with | true when Js.Opt.return xml##.response == Js.null -> Log.warn (fun m -> m "XHR Response is null; using empty string"); `String (Js.string "") | true -> Js.Opt.case (File.CoerceTo.arrayBuffer xml##.response) (fun () -> Log.warn (fun m -> m "XHR Response is not an arrayBuffer; using responseText"); respText ()) (fun ab -> `ArrayBuffer ab) | false -> respText () in get b end module Make_api (X : sig module Request : Cohttp.S.Request module Response : Cohttp.S.Response val call : ?headers:Http.Header.t -> ?body:Cohttp_lwt.Body.t -> Http.Method.t -> Uri.t -> (Response.t * Cohttp_lwt.Body.t) Lwt.t end) = struct module IO = IO module Request = X.Request module Response = X.Response type 'a io = 'a Lwt.t type body = Cohttp_lwt.Body.t type ctx = unit type 'a with_context = ?ctx:ctx -> 'a let map_context v f ?ctx = f (v ?ctx) let call ?ctx:_ ?headers ?body ?chunked:_ meth uri = X.call ?headers ?body meth uri (* The HEAD should not have a response body *) let head ?ctx ?headers uri = let open Lwt in call ?ctx ?headers ~chunked:false `HEAD uri >|= fst let get ?ctx ?headers uri = call ?ctx ?headers ~chunked:false `GET uri let delete ?ctx ?body ?chunked ?headers uri = call ?ctx ?headers ?body ?chunked `DELETE uri let post ?ctx ?body ?chunked ?headers uri = call ?ctx ?headers ?body ?chunked `POST uri let put ?ctx ?body ?chunked ?headers uri = call ?ctx ?headers ?body ?chunked `PUT uri let patch ?ctx ?body ?chunked ?headers uri = call ?ctx ?headers ?body ?chunked `PATCH uri let post_form ?ctx ?headers ~params uri = let headers = C.Header.add_opt headers "content-type" "application/x-www-form-urlencoded" in let body = Cohttp_lwt.Body.of_string (Uri.encoded_of_query params) in post ?ctx ~chunked:false ~headers ~body uri exception Cohttp_lwt_xhr_set_cache_not_implemented let set_cache _ = raise Cohttp_lwt_xhr_set_cache_not_implemented (* No implementation (can it be done?). What should the failure exception be? *) exception Cohttp_lwt_xhr_callv_not_implemented let callv ?ctx:_ _uri _reqs = raise Cohttp_lwt_xhr_callv_not_implemented (* ??? *) end module Make_client_async (P : Params) = Make_api (struct module Response = Cohttp.Response module Request = Cohttp.Request module Bb = Body_builder (P) let call ?headers ?body meth uri = let xml = XmlHttpRequest.create () in xml##.withCredentials := Js.bool P.with_credentials; if Lazy.force xhr_response_supported then xml##.responseType := Js.string "arraybuffer"; let (res : (Http.Response.t Lwt.t * CLB.t) Lwt.t), wake = Lwt.task () in let () = xml##(_open (Js.string (C.Code.string_of_method meth)) (Js.string (Uri.to_string uri)) Js._true) (* asynchronous call *) in (* set request headers *) let () = match headers with | None -> () | Some headers -> C.Header.iter (fun k v -> (* some headers lead to errors in the javascript console, should we filter then out here? *) xml##(setRequestHeader (Js.string k) (Js.string v))) headers in xml##.onreadystatechange := Js.wrap_callback (fun _ -> match xml##.readyState with | XmlHttpRequest.DONE -> ( try let body = Bb.construct_body xml in (* Note; a type checker subversion seems to be possible here (4.01.0). * Remove the type constraint on Lwt.task above and return any old * guff here. It'll compile and crash in the browser! *) (* (re-)construct the response *) let resp_headers = Js.to_string xml##getAllResponseHeaders in let channel = String_io.open_in resp_headers in let response = Lwt.( Header_io.parse channel >|= fun resp_headers -> Cohttp.Response.make ~version:`HTTP_1_1 ~status:(C.Code.status_of_code xml##.status) ~encoding:(CLB.transfer_encoding body) ~headers:resp_headers ()) in Lwt.wakeup wake (response, body) with | e (* If we exhaust the stack, it is possible that Lwt.wakeup just above marks the promise as completed, but raises Stack_overflow while running the promise callbacks. In this case waking calling wakeup_exn on the already completed promise would raise an Invalid_arg exception, so although the promise is in a really bad state we may as well let the actual Stack_overflow exception go through. *) when Lwt.state res = Lwt.Sleep -> Lwt.wakeup_exn wake e) | _ -> ()); (* perform call *) (match body with | None -> Lwt.return xml##(send Js.null) | Some body -> CLB.to_string body >>= fun body -> let bs = binary_string body in (*Js.Opt.case (File.CoerceTo.blob (Obj.magic blob)) (fun () -> failwith "could not coerce to blob") (fun blob -> Lwt.return (xml##(send_blob blob)))*) (*Lwt.return (xml##send (Js.Opt.return bs)) *) Lwt.return (xml##send (Js.Opt.return (Obj.magic bs)))) >>= fun () -> Lwt.on_cancel res (fun () -> xml##abort); (* unwrap the response *) Lwt.( res >>= fun (r, b) -> r >>= fun r -> Lwt.return (r, b)) end) module Make_client_sync (P : Params) = Make_api (struct module Response = Cohttp.Response module Request = Cohttp.Request module Bb = Body_builder (P) let call ?headers ?body meth uri = let xml = XmlHttpRequest.create () in xml##.withCredentials := Js.bool P.with_credentials; if Lazy.force xhr_response_supported then xml##.responseType := Js.string "arraybuffer"; let () = xml##(_open (Js.string (C.Code.string_of_method meth)) (Js.string (Uri.to_string uri)) Js._false) (* synchronous call *) in (* set request headers *) let () = match headers with | None -> () | Some headers -> C.Header.iter (fun k v -> (* some headers lead to errors in the javascript console, should we filter then out here? *) xml##(setRequestHeader (Js.string k) (Js.string v))) headers in (* perform call *) (match body with | None -> Lwt.return xml##(send Js.null) | Some body -> CLB.to_string body >|= fun body -> let bs = binary_string body in xml##(send (Js.Opt.return (Obj.magic bs)))) >>= fun _body -> let body = Bb.construct_body xml in (* (re-)construct the response *) let resp_headers = Js.to_string xml##getAllResponseHeaders in Header_io.parse (String_io.open_in resp_headers) >>= fun resp_headers -> let response = Response.make ~version:`HTTP_1_1 ~status:(Cohttp.Code.status_of_code xml##.status) ~encoding:(CLB.transfer_encoding body) ~headers:resp_headers () in Lwt.return (response, body) end) module Client = Make_client_async (struct let chunked_response = true let chunk_size = 128 * 1024 let convert_body_string = Js.to_bytestring let with_credentials = false end) module Client_sync = Make_client_sync (struct let chunked_response = false let chunk_size = 0 let convert_body_string = Js.to_bytestring let with_credentials = false end)
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
mli
cohttp-6.2.1/cohttp-lwt-jsoo/src/cohttp_lwt_jsoo.mli
(*{{{ Copyright (c) 2014 Andy Ray <andy.ray@ujamjar.com> * Copyright (c) 2012-2013 Anil Madhavapeddy <anil@recoil.org> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * }}}*) (** {1 HTTP client for JavaScript using XMLHttpRequest.} The {!Logs} source name for this module's logger is ["cohttp.lwt.jsoo"]. To log the current warnings using the browser's console log, you can write a custom reporter or use: {[ let reporter = Logs_browser.console_reporter () in Logs.set_reporter reporter ]} *) (** Configuration parameters for the XmlHttpRequest engines *) module type Params = sig val chunked_response : bool (** Should the response body data be chunked? *) val chunk_size : int (** Size of chunks *) val convert_body_string : Js_of_ocaml.Js.js_string Js_of_ocaml.Js.t -> string (** JavaScript string to OCaml conversion. [Js.to_bytestring] or [Js.to_string] *) val with_credentials : bool (** Whether withCredentials property of XHR is set. *) end (** Build an asynchronous engine with chunked/unchucked response data treated as raw bytes or UTF *) module Make_client_async (_ : Params) : Cohttp_lwt.S.Client (** Build a synchronous engine with chunked/unchucked response data treated as raw bytes or UTF *) module Make_client_sync (_ : Params) : Cohttp_lwt.S.Client module Client : Cohttp_lwt.S.Client (** The [Client] module implements an HTTP client interface using asynchronous XmlHttpRequests. The response body is returned in chucked form with 128Kb / chunk. Body data is treated as raw bytes. withCredentials property of XHR is set to false. *) module Client_sync : Cohttp_lwt.S.Client (** The [Client_sync] module implements an HTTP client interface using synchronous XmlHttpRequests. The response is not chunked and treated as raw bytes. withCredentials property of XHR is set to false. *)
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
dune
cohttp-6.2.1/cohttp-lwt-jsoo/src/dune
(library (name cohttp_lwt_jsoo) (public_name cohttp-lwt-jsoo) (synopsis "XHR/Lwt based http client") (preprocess (pps js_of_ocaml-ppx)) (libraries js_of_ocaml cohttp-lwt logs))
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
ml
cohttp-6.2.1/cohttp-lwt-jsoo/test/src/cohttp_lwt_jsoo_test.ml
module Client = Cohttp_lwt_jsoo.Client module Js = Js_of_ocaml.Js let _Promise = Js.Unsafe.global##._Promise let ( let* ) = Lwt.( >>= ) let ( let+ ) = Lwt.( >|= ) let promise_of_lwt lwt = new%js _Promise (Js.wrap_callback (fun resolve reject -> try%lwt let+ res = lwt () in Js.Unsafe.fun_call resolve [| Js.Unsafe.inject res |] with e -> let msg = Printexc.to_string e in Js.Unsafe.fun_call reject [| Js.Unsafe.inject (new%js Js.error_constr (Js.string msg)) |])) let () = Js.export_all (object%js method request uri = let f () = let uri = Uri.of_string (Js.to_string uri) in let* response, body = Client.get uri in let+ body = Cohttp_lwt.Body.to_string body in let status = Http.Response.status response |> Cohttp.Code.code_of_status in Js.array [| Js.Unsafe.inject status; Js.Unsafe.inject @@ Js.string body |] in promise_of_lwt f end)
cohttp-top
6.2.1
ISC
https://github.com/mirage/ocaml-cohttp
git+https://github.com/mirage/ocaml-cohttp.git
dune
cohttp-6.2.1/cohttp-lwt-jsoo/test/src/dune
(executable (name cohttp_lwt_jsoo_test) (modes js) (libraries http cohttp cohttp-lwt cohttp-lwt-jsoo lwt js_of_ocaml-lwt) (preprocess (pps lwt_ppx js_of_ocaml-ppx))) (rule (alias runjstest) (deps test.js cohttp_lwt_jsoo_test.bc.js) (action (setenv NODE_PATH "%{project_root}/cohttp-lwt-jsoo/test/node_modules" (run ./test.js))))