text
stringlengths 12
786k
|
---|
let scheme uri = get_decoded_opt uri . scheme |
let with_scheme uri = function | Some scheme -> { uri with scheme = Some ( Pct . cast_decoded scheme ) } | None -> { uri with scheme = None } |
let host uri = get_decoded_opt uri . host |
let with_host uri = function | Some host -> { uri with host = Some ( Pct . cast_decoded host ) } | None -> { uri with host = None } |
let host_with_default ( ? default " = localhost " ) uri = match host uri with | None -> default | Some h -> h |
let userinfo uri = match uri . userinfo with | None -> None | Some userinfo -> Some ( Pct . uncast_encoded ( match uri . scheme with | None -> encoded_of_userinfo userinfo | Some s -> encoded_of_userinfo ~ scheme ( : Pct . uncast_decoded s ) userinfo ) ) |
let with_userinfo uri userinfo = let userinfo = match userinfo with | Some u -> Some ( userinfo_of_encoded u ) | None -> None in match host uri with | None -> { uri with host = Some ( Pct . cast_decoded " " ) ; userinfo = userinfo } | Some _ -> { uri with userinfo = userinfo } |
let user uri = match uri . userinfo with | None -> None | Some ( user , _ ) -> Some user |
let password uri = match uri . userinfo with | None | Some ( _ , None ) -> None | Some ( _ , Some pass ) -> Some pass |
let with_password uri password = let result userinfo = match host uri with | None -> { uri with host = Some ( Pct . cast_decoded " " ) ; userinfo = userinfo } | Some _ -> { uri with userinfo = userinfo } in match uri . userinfo , password with | None , None -> uri | None , Some _ -> result ( Some ( " " , password ) ) | Some ( user , _ ) , _ -> result ( Some ( user , password ) ) |
let port uri = uri . port |
let with_port uri port = match host uri with | Some _ -> { uri with port = port } | None -> begin match port with | None -> { uri with host = None ; port = None } | Some _ -> { uri with host = Some ( Pct . cast_decoded " " ) ; port = port } end |
let path uri = Pct . uncast_encoded ( match uri . scheme with | None -> encoded_of_path uri . path | Some s -> encoded_of_path ~ scheme ( : Pct . uncast_decoded s ) uri . path ) |
let with_path uri path = let path = path_of_encoded path in match host uri , path with | None , _ | Some _ , " " /:: _ | Some _ , [ ] -> { uri with path = path } | Some _ , _ -> { uri with path " " =/:: path } |
let fragment uri = get_decoded_opt uri . fragment |
let with_fragment uri = function | None -> { uri with fragment = None } | Some frag -> { uri with fragment = Some ( Pct . cast_decoded frag ) } |
let query uri = Query . kv uri . query |
let verbatim_query uri = Query . ( match uri . query with | Raw ( qs , _ ) -> qs | KV [ ] -> None | KV kv -> Some ( encoded_of_query ? scheme ( : scheme uri ) kv ) ) |
let get_query_param ' uri k = Query . ( find ( kv uri . query ) k ) |
let get_query_param uri k = match get_query_param ' uri k with | None -> None | Some v -> Some ( String . concat " , " v ) |
let with_query uri query = { uri with query = Query . KV query } |
let q_s q = List . map ( fun ( k , v ) -> k , [ v ] ) q |
let with_query ' uri query = with_query uri ( q_s query ) |
let add_query_param uri p = Query . ( { uri with query = KV ( p ( :: kv uri . query ) ) } ) |
let add_query_param ' uri ( k , v ) = Query . ( { uri with query = KV ( ( k , [ v ] ) ( :: kv uri . query ) ) } ) |
let add_query_params uri ps = Query . ( { uri with query = KV ( ps ( @ kv uri . query ) ) } ) |
let add_query_params ' uri ps = Query . ( { uri with query = KV ( ( q_s ps ) ( @ kv uri . query ) ) } ) |
let remove_query_param uri k = Query . ( { uri with query = KV ( List . filter ( fun ( k ' , _ ) -> k <> k ' ) ( kv uri . query ) ) } ) |
let with_uri ? scheme ? userinfo ? host ? port ? path ? query ? fragment uri = let with_path_opt u o = match o with | None -> with_path u " " | Some p -> with_path u p in let with_query_opt u o = match o with | None -> with_query u [ ] | Some q -> with_query u q in let with_ f o u = match o with | None -> u | Some x -> f u x in with_ with_scheme scheme uri |> with_ with_userinfo userinfo |> with_ with_host host |> with_ with_port port |> with_ with_path_opt path |> with_ with_query_opt query |> with_ with_fragment fragment |
let path_and_query uri = match ( path uri ) , ( query uri ) with " " , | [ ] -> " " / " " , | q -> let scheme = uncast_opt uri . scheme in Printf . sprintf " /?% s " ( encoded_of_query ? scheme q ) | p , [ ] -> p | p , q -> let scheme = uncast_opt uri . scheme in Printf . sprintf " % s ?% s " p ( encoded_of_query ? scheme q ) |
let resolve schem base uri = let schem = Some ( Pct . cast_decoded ( match scheme base with | None -> schem | Some scheme -> scheme ) ) in normalize schem Path . ( match scheme uri , userinfo uri , host uri with | Some _ , _ , _ -> { uri with path = remove_dot_segments uri . path } | None , Some _ , _ | None , _ , Some _ -> { uri with scheme = base . scheme ; path = remove_dot_segments uri . path } | None , None , None -> let uri = { uri with scheme = base . scheme ; userinfo = base . userinfo ; host = base . host ; port = base . port } in let path_str = path uri in if path_str " " = then { uri with path = base . path ; query = match uri . query with | Query . Raw ( None , _ ) | Query . KV [ ] -> base . query | _ -> uri . query } else if path_str . [ 0 ] ' ' =/ then { uri with path = remove_dot_segments uri . path } else { uri with path = remove_dot_segments ( merge base . host base . path uri . path ) ; } ) |
let canonicalize uri = let uri = resolve " " empty uri in let module Scheme = ( val ( module_of_scheme ( uncast_opt uri . scheme ) ) : Scheme ) in { uri with port = Scheme . canonicalize_port uri . port ; path = Scheme . canonicalize_path uri . path ; } |
let pp ppf uri = Format . pp_print_string ppf ( to_string uri ) |
let pp_hum ppf uri = Format . pp_print_string ppf ( to_string uri ) |
open Re module Raw = struct let ( ) + a b = seq [ a ; b ] let ( ) / a b = alt [ a ; b ] let sub_delims = Posix . re " [ ' ( ) , ; ] " !$&*+= let c_at = char ' ' @ let c_colon = char ' ' : let c_dot = char ' . ' let unreserved = Posix . re " [ A - Za - z0 - 9 . - _ ] " ~ let hexdig = Posix . re " [ 0 - 9A - Fa - f ] " let pct_encoded = ( char ' ' ) % + hexdig + hexdig let dec_octet = Posix . re " 25 [ 0 - 5 ] | 2 [ 0 - 4 ] [ 0 - 9 ] [ | 01 ] [ ? 0 - 9 ] [ 0 - 9 ] " ? let ipv4_address = ( repn ( dec_octet + c_dot ) 3 ( Some 3 ) ) + dec_octet let zone_id = unreserved / pct_encoded let ipv6_address = let ( ) =| n a = repn a n ( Some n ) in let ( ) <| n a = repn a 0 ( Some n ) in let h16 = repn hexdig 1 ( Some 4 ) in let h16c = h16 + c_colon in let cc = c_colon + c_colon in let ls32 = ( h16c + h16 ) / ipv4_address in ( char ' [ ' + ( ( ( 6 =| h16c ) + ls32 ) / ( cc + ( 5 =| h16c ) + ls32 ) / ( ( 1 <| h16 ) + cc + ( 4 =| h16c ) + ls32 ) / ( ( 1 ( ( <| 1 <| h16c ) + h16 ) ) + cc + ( 3 =| h16c ) + ls32 ) / ( ( 1 ( ( <| 2 <| h16c ) + h16 ) ) + cc + ( 2 =| h16c ) + ls32 ) / ( ( 1 ( ( <| 3 <| h16c ) + h16 ) ) + cc + h16c + ls32 ) / ( ( 1 ( ( <| 4 <| h16c ) + h16 ) ) + cc + ls32 ) / ( ( 1 ( ( <| 5 <| h16c ) + h16 ) ) + cc + h16 ) / ( ( 1 ( ( <| 6 <| h16c ) + h16 ) ) + cc ) ) + ( opt ( Posix . re " % 25 " + rep1 zone_id ) ) + char ' ] ' ) let reg_name = rep ( unreserved / pct_encoded / sub_delims ) let host = ipv6_address / ipv4_address / reg_name let userinfo = rep ( unreserved / pct_encoded / sub_delims / c_colon ) let port = Posix . re " [ 0 - 9 ] " * let authority = ( opt ( ( group userinfo ) + c_at ) ) + ( group host ) + ( opt ( c_colon + ( group port ) ) ) let uri_reference = Posix . re " ( ( [ ] ) ) ( ( [ ] ) ) ( [ ] ) ( ( [ ] ) ) ( ( . ) ) " ^^:/?#+:?//^/?#*?^?#*\\?^#*?#*? end let ipv4_address = Posix . compile Raw . ipv4_address let ipv6_address = Posix . compile Raw . ipv6_address let uri_reference = Posix . compile Raw . uri_reference let authority = Posix . compile Raw . authority let host = Posix . compile Raw . host |
let search_string keys k = let rec loop keys k low high = if low > high then ( - 1 ) else begin let mid = ( high + low ) / 2 in let diff = String . compare k keys . ( mid ) in if diff < 0 then loop keys k low ( mid - 1 ) else if diff > 0 then loop keys k ( mid + 1 ) high else mid end in loop keys k 0 ( Array . length keys - 1 ) |
let search_int keys k = let rec loop keys k low high = if low > high then ( - 1 ) else begin let mid = ( high + low ) / 2 in let diff = k - keys . ( mid ) in if diff < 0 then loop keys k low ( mid - 1 ) else if diff > 0 then loop keys k ( mid + 1 ) high else mid end in loop keys k 0 ( Array . length keys - 1 ) |
let lookup search ( keys , values ) k = let i = search keys k in if i < 0 then [ ] else values . ( i ) |
let service_of_tcp_port p = lookup search_int service_of_tcp_port_tables p |
let service_of_udp_port p = lookup search_int service_of_udp_port_tables p |
let tcp_port_of_service s = lookup search_string tcp_port_of_service_tables s |
let udp_port_of_service s = lookup search_string udp_port_of_service_tables s |
let port_of_uri ? default lookupfn uri = match Uri . port uri with | Some _port as x -> x | None -> begin match Uri . scheme uri , default with | None , None -> None | None , Some scheme | Some scheme , _ -> begin match lookupfn scheme with [ ] | -> None | hd :: _ -> Some hd end end |
let tcp_port_of_uri ? default uri = port_of_uri ? default tcp_port_of_service uri |
let udp_port_of_uri ? default uri = port_of_uri ? default udp_port_of_service uri |
module Derived = struct | ` Generic | ` Custom of ( component * string * string ) scheme : string option [ @ default None ] [ @ sexp_drop_default . sexp ] ; userinfo : string option [ @ default None ] [ @ sexp_drop_default . sexp ] ; host : string option [ @ default None ] [ @ sexp_drop_default . sexp ] ; port : int option [ @ default None ] [ @ sexp_drop_default . sexp ] ; path : string [ @ default " " ] [ @ sexp_drop_default . sexp ] ; query : ( string * string list ) list [ @ sexp . list ] ; fragment : string option [ @ default None ] [ @ sexp_drop_default . sexp ] end |
let t_of_sexp sexp = Uri . make ? scheme : t . scheme ? userinfo : t . userinfo ? host : t . host ? port : t . port ~ path : t . path ~ query : t . query ? fragment : t . fragment ( ) |
let sexp_of_t t = } |
let compare a b = Uri . compare a b |
let equal a b = Uri . equal a b |
let resolve url_to_string directories reference = let resolver = Resolver . create ~ important_digests : false ~ directories ~ open_modules [ ] : in let reference = let open Odoc_model in let warnings_options = { Error . warn_error = true ; print_warnings = true } in Semantics . parse_reference reference |> Error . handle_errors_and_warnings ~ warnings_options in match reference with | Error e -> Error e | Ok reference -> ( let environment = Resolver . build_env_for_reference resolver in let resolved_reference = Odoc_xref2 . Ref_tools . resolve_reference environment reference |> Odoc_model . Error . raise_warnings in match resolved_reference with | Error e -> let error = Format . asprintf " % a " Odoc_xref2 . Errors . Tools_error . pp_reference_lookup_error e in Error ( ` Msg error ) | Ok resolved_reference -> ( let identifier = Odoc_model . Paths . Reference . Resolved . identifier resolved_reference in let url = Odoc_document . Url . from_identifier ~ stop_before : false identifier in match url with | Error e -> Error ( ` Msg ( Odoc_document . Url . Error . to_string e ) ) | Ok url -> let href = url_to_string url in print_endline href ; Ok ( ) ) ) |
let reference_to_url_html root_url = let url_to_string url = let base = match root_url with | None | Some " " -> " " | Some base -> if base . [ String . length base - 1 ] = ' ' / then base else base ^ " " / in Odoc_html . Link . ( href ~ resolve ( : Base base ) url ) in resolve url_to_string |
let reference_to_url_latex = let url_to_string url = Odoc_latex . Generator . Link . label url in resolve url_to_string |
let rec map_html_hrefs f html = List . ( rev ( rev_map ( map_html_element_hrefs f ) html ) ) | Nethtml . Data _ as d -> d | Nethtml . Element ( ( " a " | " link " ) as e , args , sub ) -> let href , args = List . partition ( fun ( a , _ ) -> a = " href " ) args in begin match href with | [ ] -> Nethtml . Element ( e , args , sub ) | ( _ , url ) :: _ -> let args = ( " href " , f url ) :: args in Nethtml . Element ( e , args , map_html_hrefs f sub ) end | Nethtml . Element ( ( " img " | " script " ) as e , args , sub ) -> let src , args = List . partition ( fun ( a , _ ) -> a = " src " ) args in begin match src with | [ ] -> Nethtml . Element ( e , args , sub ) | ( _ , url ) :: _ -> let args = ( " src " , f url ) :: args in Nethtml . Element ( e , args , sub ) end | Nethtml . Element ( e , args , sub ) -> Nethtml . Element ( e , args , map_html_hrefs f sub ) |
let map_html_file f in_file out_file = let fh = open_in in_file in let html = Nethtml . parse_document ( Lexing . from_channel fh ) ~ dtd : Utils . relaxed_html40_dtd in close_in fh ; let html = map_html_hrefs f html in let fh = open_out out_file in let out = new Netchannels . output_channel fh in out # output_string " <! DOCTYPE HTML >\ n " ; Nethtml . write out html ; out # close_out ( ) |
let map_css_file f in_file out_file = let fh = open_in in_file in let ch = new Netchannels . input_channel fh in let css = Netchannels . string_of_in_obj_channel ch in close_in fh ; let url_re = Str . regexp " url ( ( [ ( ) ] ) ) " \\^*\\ in let css = Str . global_substitute url_re ( fun css -> Printf . sprintf " url ( % s ) " ( f ( Str . matched_group 1 css ) ) ) css in let out = new Netchannels . output_channel ( open_out out_file ) in out # output_string css ; out # close_out ( ) |
let map_file f in_file out_file = if Filename . check_suffix in_file " . html " || Filename . check_suffix in_file " . xhtml " then map_html_file f in_file out_file else if Filename . check_suffix in_file " . css " then map_css_file f in_file out_file else raise ( Unknown_file_type in_file ) |
let rec remove_common_prefix p1 p2 = match p1 , p2 with | d1 :: p1 , d2 :: p2 when d1 = d2 -> remove_common_prefix p1 p2 | _ -> p1 , p2 |
let revert_path = let rec revert filename = match filename with | [ ] | [ _ ] -> [ ] | _ :: tl -> " . . " :: revert tl in fun to_base filename -> let filename = Neturl . norm_path ( Neturl . split_path filename ) in let to_base , filename = remove_common_prefix to_base filename in revert filename @ to_base |
match xs with | [ ] -> ys | x :: xs -> x :: append xs ys } ] | | [ ] -> [ ] | xs :: xss -> append xs ( flatten xss ) ^^^^^^^^^^^^^^^^^^^^^^^ } ] | | [ ] -> [ ] | xs :: xss -> let [ @ tail_mod_cons ] rec append_flatten xs xss = match xs with | [ ] -> flatten xss | x :: xs -> x :: append_flatten xs xss in append_flatten xs xss } ] | | [ ] -> [ ] | xs :: xss -> let rec append_flatten xs xss = match xs with | [ ] -> flatten xss | x :: xs -> x :: append_flatten xs xss in append_flatten xs xss ^^^^^^^^^^^^^^^^^^^^^ 1 | . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . function 2 | | [ ] -> [ ] 3 | | xs :: xss -> 4 | let rec append_flatten xs xss = 5 | match xs with 6 | | [ ] -> flatten xss 7 | | x :: xs -> 8 | 9 | x :: append_flatten xs xss } ] | |
let rec flatten = function | [ ] -> [ ] | xs :: xss -> let [ @ tail_mod_cons ] rec append_flatten xs xss = match xs with | [ ] -> flatten xss | x :: xs -> x :: append_flatten xs xss in append_flatten xs xss ^^^^^^^^^^^ } ] | |
module Tail_calls_to_non_specialized_functions = struct let list_id = function | [ ] -> [ ] | x :: xs -> x :: xs let [ @ tail_mod_cons ] rec filter_1 f li = match li with | [ ] -> [ ] | x :: xs -> if f x then x :: filter_1 f xs else list_id ( filter_1 f xs ) let [ @ tail_mod_cons ] rec filter_2 f li = match li with | [ ] -> [ ] | x :: xs -> if f x then x :: filter_2 f xs else ( list_id [ @ tailcall false ] ) ( filter_2 f xs ) end |
module Tail_calls_to_non_specialized_functions : sig val list_id : ' a list -> ' a list val filter_1 : ( ' a -> bool ) -> ' a list -> ' a list val filter_2 : ( ' a -> bool ) -> ' a list -> ' a list end } ] | |
module All_annotations_correctly_used = struct type ' a t = | N of ' a | Graft of int | Tau of ' a t | C of ' a t * ' a t let [ @ inline never ] rec graft n = graft n let [ @ tail_mod_cons ] rec map f l = match l with | N v -> N ( f v ) | Graft n -> if n >= 0 then ( graft [ @ tailcall false ] ) n else Tau ( ( graft [ @ tailcall false ] ) n ) | Tau t -> ( map [ @ tailcall ] ) f t | C ( a , b ) -> let [ @ tail_mod_cons ] map ' l = map f l in C ( map ' a , ( map ' [ @ tailcall ] ) b ) end |
module All_annotations_correctly_used : sig type ' a t = N of ' a | Graft of int | Tau of ' a t | C of ' a t * ' a t val graft : ' a -> ' b val map : ( ' a -> ' b ) -> ' a t -> ' b t end } ] | |
module All_annotations_flipped = struct type ' a t = | N of ' a | Graft of int | Tau of ' a t | C of ' a t * ' a t let [ @ inline never ] rec graft n = graft n let [ @ tail_mod_cons ] rec map_wrong f l = match l with | N v -> N ( f v ) | Graft n -> if n >= 0 then ( graft [ @ tailcall ] ) n else Tau ( ( graft [ @ tailcall ] ) n ) | Tau t -> ( map_wrong [ @ tailcall false ] ) f t | C ( a , b ) -> let [ @ tail_mod_cons ] map ' l = map_wrong f l in C ( map ' a , ( map ' [ @ tailcall false ] ) b ) end ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
module All_annotations_flipped : sig type ' a t = N of ' a | Graft of int | Tau of ' a t | C of ' a t * ' a t val graft : ' a -> ' b val map_wrong : ( ' a -> ' b ) -> ' a t -> ' b t end } ] | |
module Uint8 = struct type t = int let pp ppf t = Format . fprintf ppf " 0x % 02X " t let of_int i = if i < 0 then invalid_arg " out of range " else if i > 255 then invalid_arg " out of range " else i external add : t -> t -> t * bool = " caml__uint8_add_overflow " external mul : t -> t -> t * bool = " caml__uint8_mul_overflow " external sub : t -> t -> t * bool = " caml__uint8_sub_overflow " let pred t = sub t 1 let succ t = add t 1 let ( + ) = add let ( - ) = sub let ( * ) = mul let compare a b = match sub a b with | _ , true -> - 1 | 0 , _ -> 0 | _ , false -> 1 let ( < ) a b = compare a b < 0 let ( <= ) a b = compare a b <= 0 let ( > ) a b = compare a b > 0 let ( >= ) a b = compare a b >= 0 end |
module Uint16 = struct type t = int let pp ppf t = Format . fprintf ppf " 0x % 04X " t let of_int i = if i < 0 then invalid_arg " out of range " else if i > 65535 then invalid_arg " out of range " else i external add : t -> t -> t * bool = " caml__uint16_add_overflow " external mul : t -> t -> t * bool = " caml__uint16_mul_overflow " external sub : t -> t -> t * bool = " caml__uint16_sub_overflow " let pred t = sub t 1 let succ t = add t 1 let ( + ) = add let ( - ) = sub let ( * ) = mul let compare a b = match sub a b with | _ , true -> - 1 | 0 , _ -> 0 | _ , false -> 1 let ( < ) a b = compare a b < 0 let ( <= ) a b = compare a b <= 0 let ( > ) a b = compare a b > 0 let ( >= ) a b = compare a b >= 0 end |
module Uint32 = struct type t = int32 let pp ppf t = Format . fprintf ppf " 0x % 08lX " t let of_int i = if i < 0 then invalid_arg " out of range " else if i > 2 * Int32 . ( to_int max_int ) + 1 then invalid_arg " out of range " else Int32 . of_int i let to_int t = if Sys . word_size <= 32 && t < 0l then None else if t < 0l then Some Int32 . ( to_int ( add t min_int ) + to_int max_int + 1 ) else Some ( Int32 . to_int t ) external add : t -> t -> t * bool = " caml_uint32_add_overflow " external mul : t -> t -> t * bool = " caml_uint32_mul_overflow " external sub : t -> t -> t * bool = " caml_uint32_sub_overflow " let pred t = sub t 1l let succ t = add t 1l let ( + ) = add let ( - ) = sub let ( * ) = mul let compare a b = match sub a b with | _ , true -> - 1 | 0l , _ -> 0 | _ , false -> 1 let ( < ) a b = compare a b < 0 let ( <= ) a b = compare a b <= 0 let ( > ) a b = compare a b > 0 let ( >= ) a b = compare a b >= 0 end |
module Uint64 = struct type t = int64 let pp ppf t = Format . fprintf ppf " 0x % 016LX " t let of_int i = if i < 0 then invalid_arg " out of range " else Int64 . of_int i let to_int t = if Sys . word_size <= 64 && t < 0L then None else if t < 0L then Some Int64 . ( to_int ( add t min_int ) + to_int max_int + 1 ) else Some ( Int64 . to_int t ) external add : t -> t -> t * bool = " caml_uint64_add_overflow " external mul : t -> t -> t * bool = " caml_uint64_mul_overflow " external sub : t -> t -> t * bool = " caml_uint64_sub_overflow " let pred t = sub t 1L let succ t = add t 1L let ( + ) = add let ( - ) = sub let ( * ) = mul let compare a b = match sub a b with | _ , true -> - 1 | 0L , _ -> 0 | _ , false -> 1 let ( < ) a b = compare a b < 0 let ( <= ) a b = compare a b <= 0 let ( > ) a b = compare a b > 0 let ( >= ) a b = compare a b >= 0 end |
module Logging = struct type log_opts = { log_conns : bool ; log_async_exn : bool ; log_plugged_inout : bool ; log_everything_else : bool } bool let ( conn_section , async_exn , plugged_inout , everything_else ) everything_else = Lwt_log . Section . make " connections " , Lwt_log . Section . make " async_exceptions " , Lwt_log . Section . make " plugged_inout " , Lwt_log . Section . make " everything_else " let logging_opts = ref { log_conns = false ; log_async_exn = false ; log_plugged_inout = false ; log_everything_else = false } false let ( ) = Lwt_log . add_rule " " * Lwt_log . Info let log ( event : [ ` exn of exn | ` misc | ` plugged_inout | ` tunnel ] tunnel ) tunnel message = Lwt_log ( . match event with | ` exn exn -> if ! logging_opts . log_async_exn then ign_info ~ exn ~ section : async_exn message | ` misc -> if ! logging_opts . log_everything_else then ign_info ~ section : everything_else message | ` plugged_inout -> if ! logging_opts . log_plugged_inout then ign_info ~ section : plugged_inout message | ` tunnel -> if ! logging_opts . log_conns then ign_info ~ section : conn_section message ) end |
let byte_swap_16 value = ( ( value land 0xFF ) 0xFF lsl 8 ) 8 lor ( ( value lsr 8 ) 8 land 0xFF ) 0xFF |
module Protocol = struct type msg_version_t = Binary | Plist type conn_code = Success | Device_requested_not_connected | Port_requested_not_available | Malformed_request type event = Attached of device_t | Detached of int and device_t = { serial_number : string ; connection_speed : int ; connection_type : string ; product_id : int ; location_id : int ; device_id : int ; } type msg_t = Result of conn_code | Event of event type exn += Unknown_reply of string let ( header_length , usbmuxd_address ) usbmuxd_address = 16 , Unix . ADDR_UNIX " / var / run / usbmuxd " let listen_message = Plist ( . Dict [ ( " MessageType " , String " Listen ) " ; ( " ClientVersionString " , String " ocaml - usbmux ) " ; ( " ProgName " , String " ocaml - usbmux ) ] " |> make ) make let connect_message ~ device_id ~ device_port = Plist ( ( . Dict [ ( " MessageType " , String " Connect ) " ; ( " ClientVersionString " , String " ocaml - usbmux ) " ; ( " ProgName " , String " ocaml - usbmux ) " ; ( " DeviceID " , Integer device_id ) device_id ; ( " PortNumber " , Integer ( byte_swap_16 device_port ) device_port ) device_port ] device_port ) device_port |> make ) make let msg_length msg = String . length msg + header_length let listen_msg_len = msg_length listen_message let read_header i_chan = i_chan |> Lwt_io . atomic begin fun ic -> Lwt_io . LE ( . read_int32 ic >>= fun raw_count -> read_int32 ic >>= fun raw_version -> read_int32 ic >>= fun raw_request -> read_int32 ic >|= fun raw_tag -> Int32 ( . to_int raw_count , to_int raw_version , to_int raw_request , to_int raw_tag ) raw_tag ) raw_tag end let write_header ( ? version = Plist ) Plist ( ? request = 8 ) 8 ( ? tag = 1 ) 1 ~ total_len o_chan = o_chan |> Lwt_io . atomic begin fun oc -> ( [ total_len ; if version = Plist then 1 else 0 ; request ; tag ] tag |> List . map ~ f : Int32 . of_int ) |> Lwt_list . iter_s ( Lwt_io . LE . write_int32 oc ) oc end let parse_reply raw_reply = let handle = Plist . parse_dict raw_reply in U ( . match member " MessageType " handle |> to_string with | " Result " -> ( match member " Number " handle |> to_int with | 0 -> Result Success | 2 -> Result Device_requested_not_connected | 3 -> Result Port_requested_not_available | 5 -> Result Malformed_request | n -> raise ( Unknown_reply ( P . sprintf " Unknown result code : % d " n ) n ) n ) n | " Attached " -> Event ( Attached { serial_number = member " SerialNumber " handle |> to_string ; connection_speed = member " ConnectionSpeed " handle |> to_int ; connection_type = member " ConnectionType " handle |> to_string ; product_id = member " ProductID " handle |> to_int ; location_id = member " LocationID " handle |> to_int ; device_id = member " DeviceID " handle |> to_int } ) ; | " Detached " -> Event ( Detached ( member " DeviceID " handle |> to_int ) to_int ) to_int | otherwise -> raise ( Unknown_reply otherwise ) otherwise ) otherwise let create_listener ? event_cb ( ) = Lwt_io . with_connection usbmuxd_address begin fun ( mux_ic , mux_oc ) mux_oc -> write_header ~ total_len : listen_msg_len mux_oc >> ( ( String . length listen_message ) listen_message |> Lwt_io . write_from_string_exactly mux_oc listen_message 0 ) 0 >> read_header mux_ic >>= fun ( msg_len , _ , _ , _ ) _ -> let buffer = Bytes . create ( msg_len - header_length ) header_length in let rec start_listening ( ) = read_header mux_ic >>= fun ( msg_len , _ , _ , _ ) _ -> let buffer = Bytes . create ( msg_len - header_length ) header_length in Lwt_io . read_into_exactly mux_ic buffer 0 ( msg_len - header_length ) header_length >> match event_cb with | None -> start_listening ( ) | Some g -> g ( parse_reply buffer ) buffer >>= start_listening in Lwt_io . read_into_exactly mux_ic buffer 0 ( msg_len - header_length ) header_length >> match event_cb with | None -> start_listening ( ) | Some g -> g ( parse_reply buffer ) buffer >>= start_listening end end |
module Relay = struct type action = Shutdown | Reload type tunnel = { udid : string ; name : string option ; forwarding : forward list ; } [ @@ deriving of_yojson ] of_yojson and forward = { local_port : int ; device_port : int ; } type exn += Client_closed | Mapping_file_error of string let relay_lock = Lwt_mutex . create ( ) let ( running_servers , mapping_file , relay_timeout , lazy_exceptions , tunnels_created , tunnel_timeouts , unix_exn_exit_program ) unix_exn_exit_program = Hashtbl . create 24 , ref " " , ref None , ref 0 , ref 0 , ref 0 , ref false let status_server port = P . sprintf " http :// 127 . 0 . 0 . 1 :% d " port |> Uri . of_string let relay_pid ( ) = let open_pid_file = open_in pid_file in let target_pid = input_line open_pid_file |> int_of_string in close_in open_pid_file ; target_pid let close_chans ( ic , oc ) oc ( ) = Lwt_io . close ic >> Lwt_io . close oc let timeout_task ~ after_timeout n = let t = fst ( Lwt . task ( ) ) in let timeout = ( fun ( ) -> Lwt . cancel t ; after_timeout ( ) |> Lwt . ignore_result ) ignore_result |> Lwt_timeout . create n in Lwt_timeout . start timeout ; Lwt . on_cancel t ( fun ( ) -> Lwt_timeout . stop timeout ) timeout ; t let timeout_stream ~ after_timeout ~ read_timeout stream = ( fun ( ) -> Lwt . pick [ Lwt_stream . get stream ; timeout_task ~ after_timeout read_timeout ] read_timeout ) read_timeout |> Lwt_stream . from let echo ic oc = Lwt_io . read_chars ic |> fun hook_in -> Lwt_stream . peek hook_in >>= function | None -> Lwt . fail Client_closed | _ -> hook_in |> ( match ! relay_timeout with | None -> id | Some read_timeout -> timeout_stream ~ after_timeout ( : close_chans ( ic , oc ) oc ) oc ~ read_timeout ) read_timeout |> Lwt_io . write_chars oc let load_mappings file_name = Lwt_io . lines_of_file file_name |> Lwt_stream . to_list >|= fun lines -> lines |> List . map ~ f : String . trim |> List . filter ~ f ( : fun line -> if line <> " " && line [ . 0 ] 0 <> ' # ' then true else false ) false |> String . concat ~ sep " :\ n " |> fun data -> Yojson ( . ( try Safe . from_string data with Json_error s -> raise ( Mapping_file_error s ) s ) s |> fun should_be_array -> ( try Safe . Util . to_list should_be_array with | Safe . Util . Type_error ( e , _ ) _ -> let msg = P . sprintf " Error : % s HINT : Be sure mapping file consists of \ a single JSON array of objects , see man page for examples " e in raise ( Mapping_file_error msg ) msg ) msg |> List . map ~ f ( : fun record -> ( lazy record , tunnel_of_yojson record ) record ) record |> List . map ~ f ( : function | ( _ , Result . Ok tunnel ) tunnel -> tunnel | ( need_it , Result . Error r ) r -> let error_msg = ( ( Lazy . force need_it ) need_it |> Safe . pretty_to_string ) pretty_to_string |> P . sprintf " Check this needed field : % s , Original Json : % s " r in raise ( Mapping_file_error error_msg ) error_msg ) error_msg |> fun tunnels -> let t = Hashtbl . create ( List . length tunnels ) tunnels in tunnels |> List . iter ~ f ( : fun tunnel -> Hashtbl . add t ~ key : tunnel . udid ~ data : tunnel ) tunnel ; t ) t let do_tunnel ( udid , ( device_id , tunnels ) tunnels ) tunnels = begin tunnels . forwarding |> Lwt_list . map_p ( fun { local_port ; device_port } device_port -> let open Protocol in let server_address = Unix ( . ADDR_INET ( inet_addr_loopback , local_port ) local_port ) local_port in Lwt_io . establish_server server_address begin fun ( tcp_ic , tcp_oc ) tcp_oc -> Lwt_io . with_connection usbmuxd_address begin fun ( mux_ic , mux_oc ) mux_oc -> let msg = connect_message ~ device_id ~ device_port in write_header ~ total_len ( : msg_length msg ) msg mux_oc >> Lwt_io . write_from_string_exactly mux_oc msg 0 ( String . length msg ) msg >> read_header mux_ic >>= fun ( msg_len , _ , _ , _ ) _ -> let buffer = Bytes . create ( msg_len - header_length ) header_length in Lwt_io . read_into_exactly mux_ic buffer 0 ( msg_len - header_length ) header_length >> match parse_reply buffer with | Result Success -> tunnels_created := ! tunnels_created + 1 ; P . sprintf " Tunneling . Udid : % s Local Port : % d Device Port : % d \ Device_id : % d " udid local_port device_port device_id |> Logging . log ` tunnel ; Lwt . catch ( fun ( ) -> echo tcp_ic mux_oc <&> echo mux_ic tcp_oc >> Lwt . return ( P . sprintf " Finished Tunneling . Udid : % s Port : % d Device Port : % d \ Device_id : % d " udid local_port device_port device_id |> Logging . log ` tunnel ) tunnel ) tunnel ( function | Client_closed -> Logging . log ` tunnel " Client closed with an exception " |> close_chans ( mux_ic , mux_oc ) mux_oc >>= close_chans ( tcp_ic , tcp_oc ) tcp_oc | otherwise -> Lwt . fail otherwise ) otherwise | Result Device_requested_not_connected -> P . sprintf " Tunneling : Device requested was not connected . \ Udid : % s Device_id : % d " udid device_id |> Logging . log ` misc |> Lwt . return | Result Port_requested_not_available -> P . sprintf " Tunneling . Port requested , % d , wasn ' t available . \ Udid : % s Port : % d Device_id : % d " device_port udid local_port device_id |> Logging . log ` misc |> Lwt . return | _ -> Lwt . return_unit end >>= close_chans ( tcp_ic , tcp_oc ) tcp_oc |> Lwt . ignore_result end |> Lwt . return ) return >>= fun servers -> ( fun ( ) -> Lwt . return ( Hashtbl . add running_servers ~ key : device_id ~ data : servers ) servers ) servers |> Lwt_mutex . with_lock relay_lock end |> Lwt . ignore_result let complete_shutdown ( ) = running_servers |> Hashtbl . iter ~ f ( : fun ~ key : _ ~ data -> List . iter ~ f : Lwt_io . shutdown_server data ) data ; P . sprintf " Completed shutting down % d servers " ( Hashtbl . length running_servers ) running_servers |> Logging . log ` misc ; Hashtbl . reset running_servers let ( ) = Logging ( . Unix ( . Lwt . async_exception_hook := function | Lwt . Canceled -> tunnel_timeouts := ! tunnel_timeouts + 1 ; log ` misc " A tunnel connection timed out " | Unix_error ( ENOTCONN , _ , _ ) _ -> log ` misc " Connection refused " | Unix_error ( EADDRINUSE , _ , _ ) _ -> log ` misc " Check if already running tunneling relay , probably are " | CamlinternalLazy . Undefined -> lazy_exceptions := ! lazy_exceptions + 1 ; ( " Safe to ignore ) ignore OCaml lazy value exception from TCP tunneling " |> log ` misc | Unix_error ( Unix_errore , _ , _ ) _ -> error_message e |> P . sprintf " Unix based error : % s " |> log ` misc ; if not ! unix_exn_exit_program then exit 9 | exn -> " Please report , this is an unhandled async exception ( A bug ) bug " |> log ( ` exn exn ) exn ; exit 1 ) ) let device_alist_of_hashtable ~ device_mapping ~ devices = devices |> Hashtbl . fold ~ init [ ] : ~ f ( : fun ~ key : device_id ~ data : udid_value accum -> try ( udid_value , ( device_id , Hashtbl . find device_mapping udid_value ) udid_value ) udid_value :: accum with Not_found -> P . sprintf " Device with udid : % s expected but wasn ' t connected " udid_value |> Logging . log ` misc ; accum ) accum let start_status_server ~ device_mapping ~ devices ~ port init = let device_list = ref init in let start_time = Unix . gettimeofday ( ) in let callback _ _ _ = let uptime = Unix . gettimeofday ( ) . - start_time in let body = let tunnels_data = List . map ~ f ( : fun ( udid , ( device_id , { name ; forwarding ; _ } _ ) _ ) _ -> ( ` Assoc [ ( " Nickname " , ` String ( match name with None -> " < Unnamed " > | Some s -> s ) s ) s ; ( " Usbmuxd assigned iDevice ID " , ` Int device_id ) device_id ; ( " iDevice UDID " , ` String udid ) udid ; ( " Tunnels " , ( ` List ( forwarding |> List . map ~ f ( : fun tunnel -> ( ` Assoc [ ( " Local Port " , ` Int tunnel . local_port ) local_port ; ( " Device Port " , ` Int tunnel . device_port ) device_port ] device_port : B . json ) json ) json ) json ) json ) json ] json : B . json ) json ) json ! device_list in ` Assoc [ ( " uptime " , ` Float uptime ) uptime ; ( " async_exceptions_count " , ` Int ! lazy_exceptions ) lazy_exceptions ; ( " tunnels_created_count " , ` Int ! tunnels_created ) tunnels_created ; ( " tunnel_timeouts " , ` Int ! tunnel_timeouts ) tunnel_timeouts ; ( " mappings_file " , ` String ! mapping_file ) mapping_file ; ( " status_data " , ` List tunnels_data ) tunnels_data ] |> B . to_string in Cohttp_lwt_unix . Server . respond_string ~ status ` : OK ~ body ( ) in let server = Cohttp_lwt_unix . Server . make ~ callback ( ) in Lwt . async begin fun ( ) -> let shutdown_and_prune d = try ( Hashtbl . find running_servers d ) d |> List . iter ~ f : Lwt_io . shutdown_server ; Hashtbl . remove running_servers d with Not_found -> ( ) in let spin_up_tunnel device_udid new_id = try let ( _ , tunnels ) tunnels = List . assoc device_udid ! device_list in ( device_udid , ( new_id , tunnels ) tunnels ) tunnels |> do_tunnel with Not_found -> P . sprintf " relay can ' t create tunnel for device udid : % s " device_udid |> Logging . log ` misc in Protocol ( . create_listener ~ event_cb : begin function | Event Attached { serial_number = s ; connection_speed = _ ; connection_type = _ ; product_id = _ ; location_id = _ ; device_id = d ; } -> P . sprintf " Device % d with serial number : % s connected " d s |> Logging . log ` plugged_inout ; if not ( Hashtbl . mem devices d ) d then ( Hashtbl . add devices ~ key : d ~ data : s ; device_list := device_alist_of_hashtable ~ device_mapping ~ devices ; spin_up_tunnel s d |> Lwt . return ) return else Lwt . return ( ) | Event Detached d -> P . sprintf " Device % d disconnected " d |> Logging . log ` plugged_inout ; ( shutdown_and_prune d ; Hashtbl . remove devices d ; device_list := device_alist_of_hashtable ~ device_mapping ~ devices ) devices |> Lwt . return | _ -> Lwt . return_unit end ( ) ) end ; ( fun ( ) -> Cohttp_lwt_unix . Server . create ~ mode ( ` : TCP ( ` Port port ) port ) port server ) server |> Lwt . async let rec make_tunnels ( ? ignore_unix_exn = false ) false ( ? log_opts ( =! Logging . logging_opts ) logging_opts ) logging_opts ? stats_server ? tunnel_timeout ~ device_map = ( fun ( ) -> if Hashtbl . length running_servers <> 0 then Hashtbl . length running_servers |> Lwt_io . printlf " Exited with % d still running ; this is a bug . " else Lwt . return_unit ) return_unit |> Lwt_main . at_exit ; unix_exn_exit_program := ignore_unix_exn ; Logging . logging_opts := log_opts ; Lwt_io . set_default_buffer_size 32768 ; relay_timeout := tunnel_timeout ; ( mapping_file := device_map ) device_map |> handle_signals ; load_mappings ! mapping_file >>= fun device_mapping -> let devices = Hashtbl . create 24 in try % lwt Lwt . pick [ Lwt_unix . timeout 1 . 0 ; Protocol ( . create_listener ~ event_cb : begin function | Event Attached { serial_number = s ; connection_speed = _ ; connection_type = _ ; product_id = _ ; location_id = _ ; device_id = d ; } -> Hashtbl . add devices ~ key : d ~ data : s |> Lwt . return | Event Detached d -> Hashtbl . remove devices d |> Lwt . return | _ -> Lwt . return_unit end ( ) ) ] with Lwt_unix . Timeout -> let device_alist = device_alist_of_hashtable ~ device_mapping ~ devices in begin match stats_server with | None -> Logging . log ` misc " Did not create a status server " | Some port -> start_status_server ~ device_mapping ~ devices ~ port device_alist ; end ; let rec forever ( ) = fst ( Lwt . wait ( ) ) >>= forever in device_alist |> Lwt_list . iter_p ( Lwt_preemptive . detach do_tunnel ) do_tunnel >> forever ( ) and do_restart ( ) = if Sys . file_exists ! mapping_file then begin complete_shutdown ( ) ; Logging . log ` misc " Restarting relay with reloaded mappings " ; make_tunnels ~ ignore_unix_exn :! unix_exn_exit_program ~ log_opts :! Logging . logging_opts ? stats_server : None ? tunnel_timeout : None ~ device_map :! mapping_file |> Lwt . ignore_result end else P . sprintf " Original mapping file % s does not exist \ anymore , not reloading " ! mapping_file |> Logging . log ` misc and handle_signals ( ) = Sys ( [ . signal sigpipe Signal_ignore ; signal sigusr1 ( Signal_handle ( fun _ -> do_restart ( ) ) ) ; signal sigusr2 ( Signal_handle begin fun _ -> let relay_count = Hashtbl . length running_servers in complete_shutdown ( ) ; P . sprintf " Shutdown % d relays , exiting now " relay_count |> Logging . log ` misc ; exit 0 end ) end ; signal sigterm ( Signal_handle ( fun _ -> complete_shutdown ( ) ; exit 0 ) 0 ) 0 ] ) |> List . iter ~ f : ignore let perform action = Unix ( . try let target_pid = relay_pid ( ) in Sys ( . match action with Reload -> sigusr1 | Shutdown -> sigusr2 ) sigusr2 |> kill target_pid ; exit 0 with Unix_error ( Unix_errorEPERM , _ , _ ) _ -> ( match action with Reload -> " Couldn ' t reload mapping , permissions error " | Shutdown -> " Couldn ' t shutdown cleanly , \ permissions error ) " |> Logging . log ` misc ; exit 2 | Unix_error ( Unix_errorESRCH , _ , _ ) _ -> P . sprintf " Are you sure relay was running already ? \ Pid in % s did not match running relay " pid_file |> Logging . log ` misc ; exit 3 ) let status ~ port = Cohttp_lwt_unix . Client . get ( status_server port ) port >>= fun ( _ , body ) body -> Cohttp_lwt_body . to_string body >|= Yojson . Basic . from_string end |
type t = { id : Common . id ; bio : string mc_option ; birthday : Common . calendar_us_date mc_option ; email : string mc_option ; first_name : string mc_option ; gender : string mc_option ; is_verified : bool mc_option ; last_name : string mc_option ; link : Common . uri mc_option ; locale : string mc_option ; name : string ; name_format : string mc_option ; third_party_id : Common . id mc_option ; username : string mc_option ; verified : bool mc_option ; website : Common . uri mc_option ; |
module Home = struct end end end type t = { id : Common . id ; name : string ; category : string mc_option ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] end | Application [ @ conv . as " application " ] | Event [ @ conv . as " event " ] end end let err type ' = let msg = Printf . sprintf " Expected object , found % s " type ' in ` Error ( ` Primitive_decoding_failure msg , j , trace ) in let t_of_json_exn ? trace j = match t_of_json ? trace j with | ` Ok t -> t | ` Error e -> raise ( Common . Meta_conv_error e ) let json_of_t t = Json . Object ( t |> List . map ( fun ( k , v ) -> string_of_int k , MessageTag . json_of_t v ) ) end end module Comments after : string ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] type page_navigation = { next : Common . uri mc_option ; previous : Common . uri mc_option ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] type t = { data : data list ; paging : page_navigation mc_option ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] end end end end after : string ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] type page_navigation = { next : Common . uri mc_option ; previous : Common . uri mc_option ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] type t = { data : data list ; paging : page_navigation mc_option ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] end after : string ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] type page_navigation = { next : Common . uri mc_option ; previous : Common . uri mc_option ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] type t = { data : data list ; paging : page_navigation mc_option ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] end | Event [ @ conv . as " event " ] | Note [ @ conv . as " note " ] end end module StructuredLocation = struct type t = { country : string mc_option ; city : string mc_option ; longitude : float ; zip : string mc_option ; state : string mc_option ; street : string mc_option ; located_in : Common . id mc_option ; latitude : float ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] end type t = | Simple of string | Structured of StructuredLocation . t let t_of_json ? trace = function | Json . String s -> ` Ok ( Simple ( s ) ) | Json . Number n -> ` Ok ( Simple ( n ) ) | Json . Array _ -> ` Ok ( Simple ( " " ) ) | Json . Bool b -> ` Ok ( Simple ( string_of_bool b ) ) | Json . Null -> ` Ok ( Simple ( " " ) ) | o -> ( match StructuredLocation . t_of_json ? trace o with | ` Ok t -> ` Ok ( Structured ( t ) ) | ` Error e -> ` Error e ) let t_of_json_exn ? trace = function | Json . String s -> Simple ( s ) | Json . Number n -> Simple ( n ) | Json . Array _ -> Simple ( " " ) | Json . Bool b -> Simple ( string_of_bool b ) | Json . Null -> Simple ( " " ) | o -> Structured ( StructuredLocation . t_of_json_exn ? trace o ) let json_of_t = function | Simple l -> Json . String ( l ) | Structured l -> ( StructuredLocation . json_of_t l ) end end module Post = struct type t = { created_time : Common . calendar_iso8601 ; from : Profile . t ; id : Common . id ; message : string mc_option ; updated_time : Common . calendar_iso8601 ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] end module ReadResponse : Common . PagedResponse with type data = Post . t = struct type data = Post . t [ @@ deriving conv { json } ] after : string ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] type page_navigation = { next : Common . uri mc_option ; previous : Common . uri mc_option ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] type t = { data : data list ; paging : page_navigation mc_option ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] end end |
module Feed = struct module ReadResponse : Common . PagedResponse with type data = Home . Post . t = struct type data = Home . Post . t [ @@ deriving conv { json } ] type cursors = { after : string ; before : string ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] type page_navigation = { next : Common . uri mc_option ; previous : Common . uri mc_option ; cursors : cursors mc_option ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] type t = { data : data list ; paging : page_navigation mc_option ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] end } end end end |
module Posts = struct let read_permissions = [ " read_stream " ; ] module ReadResponse : Common . PagedResponse with type data = Home . Post . t = struct type data = Home . Post . t [ @@ deriving conv { json } ] type cursors = { after : string ; before : string ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] type page_navigation = { next : Common . uri mc_option ; previous : Common . uri mc_option ; cursors : cursors mc_option ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] type t = { data : data list ; paging : page_navigation mc_option ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] end end |
module Friends = struct let read_permissions = [ " user_friends " ] module ReadResponse : Common . PagedResponse with type data = t = struct type data = t [ @@ deriving conv { json } ] type cursors = { after : string ; before : string ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] type page_navigation = { next : Common . uri mc_option ; previous : Common . uri mc_option ; cursors : cursors mc_option ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] type t = { data : data list ; paging : page_navigation mc_option ; } [ @@ conv . ignore_unknown_fields ] [ @@ deriving conv { json } ] end end |
let section = Lwt_log . Section . make " ocsigen : ext : userconf " |
let err_500 = Ocsigen_extensions . Ext_stop_site ( Ocsigen_cookie_map . empty , ` Internal_server_error ) Internal_server_error |
let handle_parsing_error { Ocsigen_extensions . request_info ; _ } _ = function | Ocsigen_extensions . Error_in_config_file s -> Lwt_log . ign_error_f ~ section " Syntax error in userconf configuration file for url % s : % s " ( Uri . to_string ( Ocsigen_request . uri request_info ) request_info ) request_info s ; Lwt . return err_500 | Ocsigen_extensions . Error_in_user_config_file s -> Lwt_log . ign_error_f ~ section " Unauthorized option in user configuration for url % s : % s " ( Uri . to_string ( Ocsigen_request . uri request_info ) request_info ) request_info s ; Lwt . return err_500 | e -> Lwt . fail e |
let subresult new_req user_parse_site conf previous_err req req_state = Ocsigen_extensions . Ext_sub_result ( fun cookies_to_set _rs -> Lwt . catch ( fun ( ) -> user_parse_site conf cookies_to_set ( Ocsigen_extensions . Req_not_found ( previous_err , new_req ) new_req ) new_req >>= fun ( answer , cookies ) cookies -> let rec aux ( ( answer , cts ) cts as r ) r = match answer with | Ocsigen_extensions . Ext_sub_result sr -> sr cookies_to_set req_state >>= aux | Ocsigen_extensions . Ext_continue_with ( { Ocsigen_extensions . request_config ; _ } _ , cookies , err ) err -> Lwt . return ( Ocsigen_extensions . Ext_continue_with ( { req with Ocsigen_extensions . request_config } request_config , cookies , err ) , cts ) | Ocsigen_extensions . Ext_found_continue_with r -> Lwt . return ( Ocsigen_extensions . Ext_found_continue_with ( fun ( ) -> r ( ) >|= fun ( r , { Ocsigen_extensions . request_config ; _ } _ ) _ -> r , { req with Ocsigen_extensions . request_config } request_config ) request_config , cts ) | _ -> Lwt . return r in aux ( answer , cookies ) cookies ) cookies ( fun e -> handle_parsing_error req e >>= fun answer -> Lwt . return ( answer , Ocsigen_cookie_map . empty ) empty ) empty ) empty |
let conf_to_xml conf = try [ Xml . parse_file conf ] conf with | Sys_error _ -> raise NoConfFile | Xml . Error ( s , loc ) loc -> let begin_char , end_char = Xml . range loc and line = Xml . line loc in raise ( Ocsigen_extensions . Error_in_config_file ( Printf . sprintf " % s , line % d , characters % d -% d " ( Xml . error_msg s ) s line begin_char end_char ) end_char ) end_char |
let gen hostpattern sitepath ( regexp , conf , url , prefix , localpath ) localpath = function | Ocsigen_extensions . Req_found _ -> Lwt . return Ocsigen_extensions . Ext_do_nothing | Ocsigen_extensions . Req_not_found ( previous_err , ( { Ocsigen_extensions . request_info ; request_config } request_config as req ) req ) req as req_state -> ( let path = Ocsigen_request . sub_path_string request_info in match Ocsigen_lib . Netstring_pcre . string_match regexp path 0 with | None -> Lwt . return ( Ocsigen_extensions . Ext_next previous_err ) previous_err | Some _ -> ( try Lwt_log . ign_info ~ section " Using user configuration " ; let conf0 = Ocsigen_extensions . replace_user_dir regexp conf path in let uri = Uri . of_string ( Ocsigen_lib . Netstring_pcre . global_replace regexp url path ) path and prefix = Ocsigen_lib . Netstring_pcre . global_replace regexp prefix path and userconf_options = { Ocsigen_extensions . localfiles_root = Ocsigen_extensions . replace_user_dir regexp localpath path } and conf = conf_to_xml conf0 in let user_parse_host = Ocsigen_extensions . parse_config_item ( Some userconf_options ) userconf_options hostpattern request_config in let user_parse_site = Ocsigen_extensions . make_parse_config ( sitepath @ [ prefix ] prefix ) prefix user_parse_host and req = { req with Ocsigen_extensions . request_info = Ocsigen_request . update ~ uri request_info } in Lwt . return ( subresult req user_parse_site conf previous_err req req_state ) req_state with | Ocsigen_extensions . NoSuchUser | NoConfFile | Unix . Unix_error ( Unix . EACCES , _ , _ ) _ | Unix . Unix_error ( Unix . ENOENT , _ , _ ) _ -> Lwt . return ( Ocsigen_extensions . Ext_next previous_err ) previous_err | e -> handle_parsing_error req e ) e ) e |
let parse_config _ hostpattern _ path _ _ config_elem = let regexp = ref None in let conf = ref None in let url = ref None in let prefix = ref None in let localpath = ref None in Ocsigen_extensions ( . Configuration . process_element ~ in_tag " : host " ~ other_elements ( : fun t _ _ -> raise ( Bad_config_tag_for_extension t ) t ) t ~ elements : [ Configuration . element ~ name " : userconf " ~ attributes : [ Configuration . attribute ~ name " : regexp " ~ obligatory : true ( fun s -> let s = Ocsigen_lib . Netstring_pcre . regexp ( " " ^ ^ s ^ ) " " $ in regexp := Some s ) s ; Configuration . attribute ~ name " : conf " ~ obligatory : true ( fun s -> let s = Ocsigen_extensions . parse_user_dir s in conf := Some s ) s ; Configuration . attribute ~ name " : url " ~ obligatory : true ( fun s -> url := Some s ) s ; Configuration . attribute ~ name " : prefix " ~ obligatory : true ( fun s -> prefix := Some s ) s ; Configuration . attribute ~ name " : localpath " ~ obligatory : true ( fun s -> let s = Ocsigen_extensions . parse_user_dir s in localpath := Some s ) s ] ( ) ] config_elem ) config_elem ; let info = match ! regexp , ! conf , ! url , ! prefix , ! localpath with | Some r , Some t , Some u , Some p , Some p ' -> r , t , u , p , p ' | _ -> Ocsigen_extensions . badconfig " Missing attributes for < userconf " > in gen hostpattern path info |
let ( ) = Ocsigen_extensions . register ~ name " : userconf " ~ fun_site : parse_config ( ) |
let ( ) |> x f = f x ; ; |
let allocate how_many str_len = let l = ref [ ] in for _i = 1 to how_many do let s = Bytes . create str_len in l := s ( ::! l ) ; done ; ! l |
let allocate_a_lot ( ) = allocate 499 99991 |
let allocate_many_small ( ) = allocate 99991 499 |
module LuaBookDir = struct let readdir ls = let handle : Unix . dir_handle = let w = Lua . touserdata ls 1 in match w with | Some ` Userdata h -> h | _ -> failwith " Dir handle expected " ! in try Lua . pushstring ls ( Unix . readdir handle ) ; 1 with End_of_file -> 0 let dir_gc ls = let handle : Unix . dir_handle = let w = Lua . touserdata ls 1 in match w with | Some ` Userdata h -> h | _ -> failwith " Dir handle expected " ! in Unix . closedir handle ; 0 let ocaml_handle_gc h = Unix . closedir h let opendir ls = let path = LuaL . checkstring ls 1 in let handle = try Unix . opendir path with Unix . Unix_error ( err , _ , _ ) -> LuaL . error ls " cannot open % s : % s " path ( Unix . error_message err ) in Lua . newuserdata ls handle ; LuaL . getmetatable ls " LuaBook . dir " ; Lua . setmetatable ls ( - 2 ) |> ignore ; 1 let allocate_ocaml_data ls = let data1 = allocate_many_small ( ) in let data2 = allocate_a_lot ( ) in Lua . newuserdata ls data1 ; Lua . newuserdata ls data2 ; 1 let gc_compact _ls = Printf . printf " Calling Gc . compact 2 times from Lua . . . " ; %! Gc . compact ( ) ; Gc . compact ( ) ; Printf . printf " done !\ n " ; %! 0 let luaopen_dir ls = LuaL . newmetatable ls " LuaBook . dir " |> ignore ; Lua . pushstring ls " __gc " ; Lua . pushocamlfunction ls ( Lua . make_gc_function dir_gc ) ; Lua . settable ls ( - 3 ) |> ignore ; Lua . pushocamlfunction ls opendir ; Lua . setglobal ls " opendir " ; Lua . pushocamlfunction ls readdir ; Lua . setglobal ls " readdir " ; Lua . pushocamlfunction ls gc_compact ; Lua . setglobal ls " gc_compact " ; Lua . pushocamlfunction ls allocate_ocaml_data ; Lua . setglobal ls " allocate_ocaml_data " ; end ; ; |
let closure ( ) = let l1 = LuaL . newstate ( ) in LuaL . openlibs l1 ; LuaBookDir . luaopen_dir l1 ; LuaL . loadbuffer l1 " handle = opendir ( " " ) \/\ d = readdir ( handle ) end match Lua . pcall l1 0 0 0 with | Lua . LUA_OK -> ( ) | _err -> begin Printf . printf " % s \ n " %! ( Lua . tostring l1 ( - 1 ) |> Option . value ~ default " " ) ; : Lua . pop l1 1 ; failwith " FATAL ERROR " end ; ; |
let print_timings start_space start_wtime start_ptime = let end_ptime = Unix . times ( ) in let self_u = end_ptime . Unix . tms_utime . - start_ptime . Unix . tms_utime in let self_s = end_ptime . Unix . tms_stime . - start_ptime . Unix . tms_stime in let self = self_u . + self_s in let child_u = end_ptime . Unix . tms_cutime . - start_ptime . Unix . tms_cutime in let child_s = end_ptime . Unix . tms_cstime . - start_ptime . Unix . tms_cstime in let child = child_u . + child_s in let run_time = self . + child in let real_time = Unix . time ( ) . - start_wtime in let real_time_sec = int_of_float real_time in let real_time_min = real_time_sec / 60 in let real_time_sec = real_time_sec mod 60 in let real_time_hrs = real_time_min / 60 in let real_time_min = real_time_min mod 60 in let end_space = Gc . quick_stat ( ) in Printf . printf " Run time : % f sec \ n " %! run_time ; Printf . printf " Self : % f sec \ n " %! self ; Printf . printf " sys : % f sec \ n " %! self_u ; Printf . printf " user : % f sec \ n " %! self_s ; Printf . printf " Children : % f sec \ n " %! child ; Printf . printf " sys : % f sec \ n " %! child_u ; Printf . printf " user : % f sec \ n " %! child_s ; Printf . printf " GC : minor : % d \ n " %! ( end_space . Gc . minor_collections - start_space . Gc . minor_collections ) ; Printf . printf " major : % d \ n " %! ( end_space . Gc . major_collections - start_space . Gc . major_collections ) ; Printf . printf " compactions : % d \ n " %! ( end_space . Gc . compactions - start_space . Gc . compactions ) ; Printf . printf " Allocated : . % 1f words \ n " %! ( end_space . Gc . minor_words . + end_space . Gc . major_words . - start_space . Gc . minor_words . - start_space . Gc . major_words . - end_space . Gc . promoted_words . + start_space . Gc . promoted_words ) ; Printf . printf " Wall clock : . % 0f sec ( % 02d :% 02d :% 02d ) \ n " %! real_time real_time_hrs real_time_min real_time_sec ; if real_time > 0 . then Printf . printf " Load : . % 2f %%\ n " %! ( run_time . * 100 . 0 . / real_time ) ; ; |
let run func args = Gc . compact ( ) ; let start_space = Gc . quick_stat ( ) in let start_wtime = Unix . time ( ) in let start_ptime = Unix . times ( ) in let ret = try func args with e -> print_timings start_space start_wtime start_ptime ; raise e in print_timings start_space start_wtime start_ptime ; ret ; ; |
let test_duration = 60 . 0 . * 10 . 0 ; ; |
let time_start = Unix . gettimeofday ( ) ; ; |
let main ( ) = while Unix . gettimeofday ( ) < time_start . + test_duration do closure ( ) |> ignore ; Printf . printf " Calling Gc . compact from OCaml . . . " ; %! Gc . compact ( ) ; Printf . printf " done !\ n " ; %! done ; Gc . compact ( ) ; ; ; |
type upgrades = ( Int32 . t * Protocol_hash . t ) list |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.