text
stringlengths
0
601k
let pp_protocol_error ppf = function | ` Other_error -> Format . pp_print_string ppf " other error " | ` Bad_request -> Format . pp_print_string ppf " bad request " | ` Configuration_unsupported -> Format . pp_print_string ppf " configuration unsupported " | ` Device_ineligible -> Format . pp_print_string ppf " device ineligible " | ` Timeout -> Format . pp_print_string ppf " timeout reached " | ` Unrecognized n -> Format . fprintf ppf " unrecognized % d " n
type error = [ | ` Protocol of protocol_error | ` Json_decoding of string * string * string | ` Base64_decoding of string * string * string | ` Binary_decoding of string * string * string | ` Version_mismatch of string * string | ` Typ_mismatch of string * string | ` Challenge_mismatch of string * string | ` Unknown_key_handle of string | ` Signature_verification of string | ` Origin_mismatch of string * string ]
let pp_error ppf = function | ` Protocol p -> pp_protocol_error ppf p | ` Json_decoding ( name , err , value ) -> Format . fprintf ppf " json decoding of % s failed with % S ( input % S ) " name err value | ` Base64_decoding ( name , err , value ) -> Format . fprintf ppf " base64 decoding of % s failed with % S ( input % S ) " name err value | ` Binary_decoding ( name , err , value ) -> Format . fprintf ppf " binary decoding of % s failed with % S ( input % a ) " name err Cstruct . hexdump_pp ( Cstruct . of_string value ) | ` Version_mismatch ( expected , received ) -> Format . fprintf ppf " version mismatch , expected % S , received % S " expected received | ` Typ_mismatch ( expected , received ) -> Format . fprintf ppf " typ mismatch , expected % S , received % S " expected received | ` Challenge_mismatch ( expected , received ) -> Format . fprintf ppf " challenge mismatch , expected % S , received % S " expected received | ` Unknown_key_handle received -> Format . fprintf ppf " unknown key handle % S " received | ` Signature_verification msg -> Format . fprintf ppf " signature verification failed % s " msg | ` Origin_mismatch ( expected , received ) -> Format . fprintf ppf " origin mismatch , expected % S , received % S " expected received
let b64_enc = Base64 . ( encode_string ~ pad : false ~ alphabet : uri_safe_alphabet )
let b64_dec thing s = Result . map_error ( function ` Msg m -> ` Base64_decoding ( thing , m , s ) ) Base64 . ( decode ~ pad : false ~ alphabet : uri_safe_alphabet s )
type register_request = { version : string ; challenge : string ;
type registered_key = { version : string ; keyHandle : string ;
type u2f_register_request = { appId : string ; registerRequests : register_request list ; registeredKeys : registered_key list ;
let challenge ( ) = let random = Cstruct . to_string ( Mirage_crypto_rng . generate 32 ) in b64_enc random
let register_request ( ? key_handles = [ ] ) { version ; application_id } = let challenge = challenge ( ) in let reg_req = { appId = application_id ; registerRequests = [ { version ; challenge } ] ; registeredKeys = List . map ( fun keyHandle -> { version ; keyHandle } ) key_handles } in challenge , Yojson . Safe . to_string ( u2f_register_request_to_yojson reg_req )
let res_typ_to_string = function | ` Sign -> " navigator . id . getAssertion " | ` Register -> " navigator . id . finishEnrollment "
let res_typ = function | " navigator . id . getAssertion " -> Ok ` Sign | " navigator . id . finishEnrollment " -> Ok ` Register | x -> Error ( ` Msg ( " unknown type " ^ x ) )
type clientData = { challenge : string ; origin : string ; typ : string ;
let error_code_of_int = function | 0 -> Ok ( ) | 1 -> Error ` Other_error | 2 -> Error ` Bad_request | 3 -> Error ` Configuration_unsupported | 4 -> Error ` Device_ineligible | 5 -> Error ` Timeout | n -> Error ( ` Unrecognized n )
type u2f_register_response = { clientData : string ; errorCode : int ; registrationData : string ; version : string ;
let ( let * ) = Result . bind
let guard p e = if p then Ok ( ) else Error e
let seq_len cs = let * ( ) = guard ( Cstruct . get_uint8 cs 0 = 0x30 ) ( ` Msg " Certificate is not an ASN . 1 sequence " ) in let first_len = Cstruct . get_uint8 cs 1 in if first_len > 0x80 then let len_bytes = first_len - 0x80 in let * ( ) = guard ( Cstruct . length cs > len_bytes + 2 ) ( ` Msg " Certificate with too few data " ) in let rec read_more acc off = if off = len_bytes then Ok ( acc + 2 + len_bytes ) else let v = acc * 256 + Cstruct . get_uint8 cs ( off + 2 ) in read_more v ( off + 1 ) in read_more 0 0 else Ok ( first_len + 2 )
let decode_reg_data data = let cs = Cstruct . of_string data in let * ( ) = guard ( Cstruct . length cs >= 67 ) ( ` Msg " registration data too small ( < 67 ) " ) in let * ( ) = guard ( Cstruct . get_uint8 cs 0 = 0x05 ) ( ` Msg " registration data first byte must be 0x05 " ) in let pubkey , rest = Cstruct . ( split ( shift cs 1 ) 65 ) in let kh_len = Cstruct . get_uint8 rest 0 in let * ( ) = guard ( Cstruct . length rest > kh_len ) ( ` Msg ( " registration data too small ( < kh_len ) " ) ) in let kh , rest = Cstruct . ( split ( shift rest 1 ) kh_len ) in let * clen = seq_len rest in let * ( ) = guard ( Cstruct . length rest > clen ) ( ` Msg ( " registration data too small ( < clen ) " ) ) in let cert_data , signature = Cstruct . split rest clen in let * cert = X509 . Certificate . decode_der cert_data in match Mirage_crypto_ec . P256 . Dsa . pub_of_cstruct pubkey with | Ok key -> Ok ( key , kh , cert , signature ) | Error err -> let err = Format . asprintf " % a " Mirage_crypto_ec . pp_error err in Error ( ` Msg err )
let verify_sig pub ~ signature data = match X509 . Public_key . verify ` SHA256 ~ signature pub ( ` Message data ) with | Error ` Msg m -> Error ( ` Signature_verification m ) | Ok ( ) -> Ok ( )
let verify_reg_sig cert app client_data kh key signature = let h s = Mirage_crypto . Hash . SHA256 . digest ( Cstruct . of_string s ) in let data = Cstruct . concat [ Cstruct . create 1 ; h app ; h client_data ; kh ; Mirage_crypto_ec . P256 . Dsa . pub_to_cstruct key ] in verify_sig ( X509 . Certificate . public_key cert ) ~ signature data
let verify_auth_sig key app presence counter client_data signature = let data = let h s = Mirage_crypto . Hash . SHA256 . digest ( Cstruct . of_string s ) in let p_c = let b = Cstruct . create 5 in if presence then Cstruct . set_uint8 b 0 1 ; Cstruct . BE . set_uint32 b 1 counter ; b in Cstruct . concat [ h app ; p_c ; h client_data ] in verify_sig ( ` P256 key ) ~ signature data
let of_json_or_err thing p json = Result . map_error ( fun msg -> ` Json_decoding ( thing , msg , Yojson . Safe . to_string json ) ) ( p json )
let of_json thing p s = let * json = try Ok ( Yojson . Safe . from_string s ) with Yojson . Json_error msg -> Error ( ` Json_decoding ( thing , msg , s ) ) in of_json_or_err thing p json
let register_response ( t : t ) challenge data = let * reg_resp = of_json " RegisterResponse " u2f_register_response_of_yojson data in let * ( ) = Result . map_error ( fun p -> ` Protocol p ) ( error_code_of_int reg_resp . errorCode ) in let * ( ) = guard ( String . equal t . version reg_resp . version ) ( ` Version_mismatch ( t . version , reg_resp . version ) ) in let * client_data_json = b64_dec " clientData " reg_resp . clientData in let * reg_data = b64_dec " registrationData " reg_resp . registrationData in let * key , key_handle , certificate , signature = Result . map_error ( function ` Msg m -> ` Binary_decoding ( " registrationData " , m , reg_data ) ) ( decode_reg_data reg_data ) in let * client_data = of_json " clientData " clientData_of_yojson client_data_json in let * ( ) = guard ( res_typ client_data . typ = Ok ` Register ) ( ` Typ_mismatch ( res_typ_to_string ` Register , client_data . typ ) ) in let * ( ) = guard ( String . equal challenge client_data . challenge ) ( ` Challenge_mismatch ( challenge , client_data . challenge ) ) in let * ( ) = verify_reg_sig certificate t . application_id client_data_json key_handle key signature in Ok ( key , b64_enc ( Cstruct . to_string key_handle ) , certificate )
type u2f_authentication_request = { appId : string ; challenge : string ; registeredKeys : registered_key list ;
let authentication_request { version ; application_id } key_handles = let challenge = challenge ( ) in let ar = { appId = application_id ; challenge ; registeredKeys = List . map ( fun keyHandle -> { version ; keyHandle } ) key_handles } in challenge , Yojson . Safe . to_string ( u2f_authentication_request_to_yojson ar )
type u2f_authentication_response = { clientData : string ; errorCode : int ; keyHandle : string ; signatureData : string ;
let decode_sigdata data = let cs = Cstruct . of_string data in let * ( ) = guard ( Cstruct . length cs > 5 ) ( ` Msg " sigData too small " ) in let user_presence = Cstruct . get_uint8 cs 0 = 1 in let counter = Cstruct . BE . get_uint32 cs 1 in let signature = Cstruct . shift cs 5 in Ok ( user_presence , counter , signature )
let authentication_response ( t : t ) key_handle_keys challenge data = let * sig_resp = of_json " AuthenticationResponse " u2f_authentication_response_of_yojson data in let * ( ) = Result . map_error ( fun p -> ` Protocol p ) ( error_code_of_int sig_resp . errorCode ) in let * client_data_json = b64_dec " clientData " sig_resp . clientData in let * sigdata = b64_dec " signatureData " sig_resp . signatureData in let * user_present , counter , signature = Result . map_error ( function ` Msg m -> ` Binary_decoding ( " signatureData " , m , sigdata ) ) ( decode_sigdata sigdata ) in let * client_data = of_json " clientData " clientData_of_yojson client_data_json in let * ( ) = guard ( res_typ client_data . typ = Ok ` Sign ) ( ` Typ_mismatch ( res_typ_to_string ` Sign , client_data . typ ) ) in let * ( ) = guard ( String . equal challenge client_data . challenge ) ( ` Challenge_mismatch ( challenge , client_data . challenge ) ) in let * ( ) = guard ( String . equal t . application_id client_data . origin ) ( ` Origin_mismatch ( t . application_id , client_data . origin ) ) in let * pubkey = List . fold_left ( fun acc ( _ , pubkey ) -> match acc with | Ok key -> Ok key | Error _ -> let * ( ) = verify_auth_sig pubkey t . application_id user_present counter client_data_json signature in Ok pubkey ) ( Error ( ` Unknown_key_handle sig_resp . keyHandle ) ) ( List . filter ( fun ( kh , _ ) -> String . equal kh sig_resp . keyHandle ) key_handle_keys ) in Ok ( ( sig_resp . keyHandle , pubkey ) , user_present , counter )
let users = Hashtbl . create 7
module KhPubHashtbl = Hashtbl . Make ( struct type t = U2f . key_handle * Mirage_crypto_ec . P256 . Dsa . pub let cs_of_pub = Mirage_crypto_ec . P256 . Dsa . pub_to_cstruct let equal ( kh , pub ) ( kh ' , pub ' ) = String . equal kh kh ' && Cstruct . equal ( cs_of_pub pub ) ( cs_of_pub pub ' ) let hash ( kh , pub ) = Hashtbl . hash ( kh , Cstruct . to_string ( cs_of_pub pub ) ) end )
let counters = KhPubHashtbl . create 7
let check_counter kh_pub counter = let r = match KhPubHashtbl . find_opt counters kh_pub with | Some counter ' -> Int32 . unsigned_compare counter counter ' > 0 | None -> true in if r then KhPubHashtbl . replace counters kh_pub counter ; r
let retrieve_form request = Dream . body request >|= fun body -> let form = Dream__pure . Formats . from_form_urlencoded body in List . stable_sort ( fun ( key , _ ) ( key ' , _ ) -> String . compare key key ' ) form
let to_string err = Format . asprintf " % a " U2f . pp_error err
let add_routes t = let main req = let authenticated_as = Dream . session " authenticated_as " req in let flash = Flash_message . get_flash req |> List . map snd in Dream . html ( Template . overview flash authenticated_as users ) in let register req = let user = match Dream . session " authenticated_as " req with | None -> Base64 . ( encode_string ~ pad : false ~ alphabet : uri_safe_alphabet ( Cstruct . to_string ( Mirage_crypto_rng . generate 8 ) ) ) | Some username -> username in let key_handles = match Hashtbl . find_opt users user with | None -> [ ] | Some keys -> List . map ( fun ( _ , kh , _ ) -> kh ) keys in let challenge , rr = U2f . register_request ~ key_handles t in Dream . put_session " challenge " challenge req >>= fun ( ) -> Dream . html ( Template . register_view rr user ) in let register_finish req = retrieve_form req >>= fun data -> let token = List . assoc " token " data in let user = List . assoc " username " data in match Dream . session " challenge " req with | None -> Logs . warn ( fun m -> m " no challenge found " ) ; Dream . respond ~ status ` : Bad_Request " Bad request . " | Some challenge -> match U2f . register_response t challenge token with | Error e -> Logs . warn ( fun m -> m " error % a " U2f . pp_error e ) ; let err = to_string e in Flash_message . put_flash " " ( " Registration failed " ^ err ) req ; Dream . redirect req " " / | Ok ( key , kh , cert ) -> match Dream . session " authenticated_as " req , Hashtbl . find_opt users user with | _ , None -> Logs . app ( fun m -> m " registered % s " user ) ; Hashtbl . replace users user [ ( key , kh , cert ) ] ; Dream . invalidate_session req >>= fun ( ) -> Flash_message . put_flash " " ( Printf . sprintf " Successfully registered as % s ! < a href " =\/ authenticate /% s " [ \> authenticate ] </ a " > user user ) req ; Dream . redirect req " " / | Some session_user , Some keys -> if String . equal user session_user then begin Logs . app ( fun m -> m " registered % s " user ) ; Hashtbl . replace users user ( ( key , kh , cert ) :: keys ) ; Dream . invalidate_session req >>= fun ( ) -> Flash_message . put_flash " " ( Printf . sprintf " Successfully registered as % s ! < a href " =\/ authenticate /% s " [ \> authenticate ] </ a " > user user ) req ; Dream . redirect req " " / end else Dream . respond ~ status ` : Forbidden " Forbidden . " | None , Some _keys -> Dream . respond ~ status ` : Forbidden " Forbidden . " in let authenticate req = let user = Dream . param " user " req in match Hashtbl . find_opt users user with | None -> Logs . warn ( fun m -> m " no user found " ) ; Dream . respond ~ status ` : Bad_Request " Bad request . " | Some keys -> let khs = List . map ( fun ( _ , kh , _ ) -> kh ) keys in let challenge , ar = U2f . authentication_request t khs in Dream . put_session " challenge " challenge req >>= fun ( ) -> Dream . put_session " challenge_user " user req >>= fun ( ) -> Dream . html ( Template . authenticate_view ar user ) in let authenticate_finish req = retrieve_form req >>= fun data -> match Dream . session " challenge_user " req with | None -> Dream . respond ~ status ` : Internal_Server_Error " Internal server error . " | Some user -> match Dream . session " challenge " req with | None -> Logs . warn ( fun m -> m " no challenge found " ) ; Dream . respond ~ status ` : Bad_Request " Bad request . " | Some challenge -> match Hashtbl . find_opt users user with | None -> Logs . warn ( fun m -> m " no user found , using empty " ) ; Dream . respond ~ status ` : Bad_Request " Bad request . " | Some keys -> let kh_keys = List . map ( fun ( key , kh , _ ) -> kh , key ) keys in let token = List . assoc " token " data in match U2f . authentication_response t kh_keys challenge token with | Ok ( key_handle_pubkey , _user_present , counter ) -> if check_counter key_handle_pubkey counter then begin Flash_message . put_flash " " " Successfully authenticated " req ; Dream . put_session " user " user req >>= fun ( ) -> Dream . put_session " authenticated_as " user req >>= fun ( ) -> Dream . redirect req " " / end else begin Logs . warn ( fun m -> m " key handle % S for user % S : counter not strictly increasing ! \ Got % ld , expected >% ld . U2f device compromised " ? ( fst key_handle_pubkey ) user counter ( KhPubHashtbl . find counters key_handle_pubkey ) ) ; Flash_message . put_flash " " " Authentication failure : key compromised " ? req ; Dream . redirect req " " / end | Error e -> Logs . warn ( fun m -> m " error % a " U2f . pp_error e ) ; let err = to_string e in Flash_message . put_flash " " ( " Authentication failure : " ^ err ) req ; Dream . redirect req " " / in let logout req = Dream . invalidate_session req >>= fun ( ) -> Dream . redirect req " " / in let u2f_api _req = Dream . respond ~ headers [ ( " : Content - type " , " application / javascript " ) ] [ % blob " u2f - api - 1 . 1 . js " ] in Dream . router [ Dream . get " " / main ; Dream . get " / register " register ; Dream . post " / register_finish " register_finish ; Dream . get " / authenticate /: user " authenticate ; Dream . post " / authenticate_finish " authenticate_finish ; Dream . post " / logout " logout ; Dream . get " / static / u2f - api - 1 . 1 . js " u2f_api ; ]
let setup_app level port host application_id https = let u2f = U2f . create application_id in let level = match level with None -> None | Some Logs . Debug -> Some ` Debug | Some Info -> Some ` Info | Some Warning -> Some ` Warning | Some Error -> Some ` Error | Some App -> None in Dream . initialize_log ? level ( ) ; Dream . run ~ port ~ interface : host ~ https @@ Dream . logger @@ Dream . memory_sessions @@ Flash_message . flash_messages @@ add_routes u2f @@ Dream . not_found
let port = let doc = " port " in Arg . ( value & opt int 4000 & info [ " p " ; " port " ] ~ doc )
let host = let doc = " host " in Arg . ( value & opt string " 0 . 0 . 0 . 0 " & info [ " h " ; " host " ] ~ doc )
let application_id = let doc = " the u2f application id - usually protocol :// host ( : port ) " in Arg . ( value & opt string " https :// u2f - demo . robur . coop " & info [ " application - id " ] ~ doc )
let tls = let doc = " tls " in Arg . ( value & flag & info [ " tls " ] ~ doc )
let ( ) = let term = Term . ( pure setup_app $ Logs_cli . level ( ) $ port $ host $ application_id $ tls ) in let info = Term . info " U2f app " ~ doc " : U2f app " ~ man [ ] : in match Term . eval ( term , info ) with | ` Ok ( ) -> exit 0 | ` Error _ -> exit 1 | _ -> exit 0
let is_spec attr = attr . attr_name . txt = " gospel "
let rec get_spec_attr = function | [ ] -> ( None , [ ] ) | h :: t when is_spec h -> ( Some h , t ) | h :: t -> let elt , rest = get_spec_attr t in ( elt , h :: rest )
let get_spec_content attr = match attr . attr_payload with | PStr [ { pstr_desc = Pstr_eval ( { pexp_desc = Pexp_constant ( Pconst_string ( spec , _ , _ ) ) ; _ } , _ ) ; _ ; } ; ] -> ( spec , attr . attr_loc ) | _ -> assert false
let get_inner_spec attr = match attr . attr_payload with | PStr [ { pstr_desc = Pstr_eval ( _ , attrs ) ; _ } ] -> get_spec_attr attrs | _ -> assert false
let set_position ( lexbuf : Lexing . lexbuf ) ( position : Lexing . position ) = lexbuf . lex_curr_p <- { position with pos_fname = lexbuf . lex_curr_p . pos_fname } ; lexbuf . lex_abs_pos <- position . pos_cnum
let set_filename ( lexbuf : Lexing . lexbuf ) ( fname : string ) = lexbuf . lex_curr_p <- { lexbuf . lex_curr_p with pos_fname = fname }
let parse_gospel ~ filename parse attr = let spec , _ = get_spec_content attr in let lb = Lexing . from_string spec in set_position lb attr . attr_loc . loc_start ; set_filename lb filename ; try ( spec , parse Ulexer . token lb ) with Uparser . Error -> let loc = { loc_start = lb . lex_start_p ; loc_end = lb . lex_curr_p ; loc_ghost = false } in W . error ~ loc W . Syntax_error
let type_declaration ~ filename t = let spec_attr , other_attrs = get_spec_attr t . ptype_attributes in let parse attr = let ty_text , spec = parse_gospel ~ filename Uparser . type_spec attr in { spec with ty_text ; ty_loc = attr . attr_loc } in let spec = Option . map parse spec_attr in { tname = t . ptype_name ; tparams = t . ptype_params ; tcstrs = t . ptype_cstrs ; tkind = t . ptype_kind ; tprivate = t . ptype_private ; tmanifest = t . ptype_manifest ; tattributes = other_attrs ; tspec = spec ; tloc = t . ptype_loc ; }
let val_description ~ filename v = let spec_attr , other_attrs = get_spec_attr v . pval_attributes in let parse attr = let sp_text , spec = parse_gospel ~ filename Uparser . val_spec attr in { spec with sp_text ; sp_loc = attr . attr_loc } in let spec = Option . map parse spec_attr in { vname = v . pval_name ; vtype = v . pval_type ; vprim = v . pval_prim ; vattributes = other_attrs ; vspec = spec ; vloc = v . pval_loc ; }
let ghost_spec ~ filename attr = let spec , loc = get_spec_content attr in let lb = Lexing . from_string spec in let sigs = try Parse . interface lb with _ -> W . error ~ loc W . Syntax_error in match sigs with | [ { psig_desc = Psig_type ( r , [ t ] ) ; _ } ] -> let type_ = type_declaration ~ filename t in if type_ . tspec = None then let tspec = get_inner_spec attr |> fst |> Option . map ( parse_gospel ~ filename Uparser . type_spec ) |> Option . map ( fun ( ty_text , spec ) -> { spec with ty_text ; ty_loc = attr . attr_loc } ) in Sig_ghost_type ( r , [ { type_ with tspec ; tloc = attr . attr_loc } ] ) else Sig_ghost_type ( r , [ type_ ] ) | [ { psig_desc = Psig_value vd ; _ } ] -> let val_ = val_description ~ filename vd in if val_ . vspec = None then let vspec = get_inner_spec attr |> fst |> Option . map ( parse_gospel ~ filename Uparser . val_spec ) |> Option . map ( fun ( sp_text , spec ) -> { spec with sp_text ; sp_loc = attr . attr_loc } ) in Sig_ghost_val { val_ with vspec ; vloc = attr . attr_loc } else Sig_ghost_val val_ | [ { psig_desc = Psig_open od ; _ } ] -> Sig_ghost_open { od with popen_loc = attr . attr_loc } | _ -> assert false
let floating_spec ~ filename a = try let fun_text , fun_ = parse_gospel ~ filename Uparser . func a in let fun_ = { fun_ with fun_text } in if fun_ . fun_spec = None then let fun_spec = get_inner_spec a |> fst |> Option . map ( parse_gospel ~ filename Uparser . func_spec ) |> Option . map ( fun ( fun_text , ( spec : fun_spec ) ) -> { spec with fun_text ; fun_loc = a . attr_loc } ) in Sig_function { fun_ with fun_spec } else Sig_function fun_ with W . Error ( _ , W . Syntax_error ) -> ( try let ax_text , axiom = parse_gospel ~ filename Uparser . axiom a in Sig_axiom { axiom with ax_text ; ax_loc = a . attr_loc } with W . Error ( _ , W . Syntax_error ) -> ghost_spec ~ filename a )
let with_constraint c = let no_spec_type_decl t = { tname = t . ptype_name ; tparams = t . ptype_params ; tcstrs = t . ptype_cstrs ; tkind = t . ptype_kind ; tprivate = t . ptype_private ; tmanifest = t . ptype_manifest ; tattributes = t . ptype_attributes ; tspec = None ; tloc = t . ptype_loc ; } in match c with | Pwith_type ( l , t ) -> Wtype ( l , no_spec_type_decl t ) | Pwith_module ( l1 , l2 ) -> Wmodule ( l1 , l2 ) | Pwith_typesubst ( l , t ) -> Wtypesubst ( l , no_spec_type_decl t ) | Pwith_modsubst ( l1 , l2 ) -> Wmodsubst ( l1 , l2 ) | Pwith_modtype ( l1 , l2 ) -> Wmodtype ( l1 , l2 ) | Pwith_modtypesubst ( l1 , l2 ) -> Wmodtypesubst ( l1 , l2 )
let rec signature_item_desc ~ filename = function | Psig_value v -> Sig_val ( val_description ~ filename v ) | Psig_type ( r , tl ) -> Sig_type ( r , List . map ( type_declaration ~ filename ) tl ) | Psig_attribute a -> if not ( is_spec a ) then Sig_attribute a else floating_spec ~ filename a | Psig_module m -> Sig_module ( module_declaration ~ filename m ) | Psig_recmodule d -> Sig_recmodule ( List . map ( module_declaration ~ filename ) d ) | Psig_modtype d -> Sig_modtype ( module_type_declaration ~ filename d ) | Psig_typext t -> Sig_typext t | Psig_exception e -> Sig_exception e | Psig_open o -> Sig_open o | Psig_include i -> Sig_include i | Psig_class c -> Sig_class c | Psig_class_type c -> Sig_class_type c | Psig_extension ( e , a ) -> Sig_extension ( e , a ) | Psig_typesubst s -> Sig_typesubst ( List . map ( type_declaration ~ filename ) s ) | Psig_modsubst s -> Sig_modsubst s | Psig_modtypesubst s -> Sig_modtypesubst ( module_type_declaration ~ filename s ) List . map ( fun { psig_desc ; psig_loc } -> { sdesc = signature_item_desc ~ filename psig_desc ; sloc = psig_loc } ) sigs | Pmty_ident id -> Mod_ident id | Pmty_signature s -> Mod_signature ( signature ~ filename s ) | Pmty_functor ( fp , mt ) -> Mod_functor ( functor_parameter ~ filename fp , module_type ~ filename mt ) | Pmty_with ( m , c ) -> Mod_with ( module_type ~ filename m , List . map with_constraint c ) | Pmty_typeof m -> Mod_typeof m | Pmty_extension e -> Mod_extension e | Pmty_alias a -> Mod_alias a | Unit -> Unit | Named ( s , m ) -> Named ( s , module_type ~ filename m ) { mdesc = module_type_desc ~ filename m . pmty_desc ; mloc = m . pmty_loc ; mattributes = m . pmty_attributes ; } { mdname = m . pmd_name ; mdtype = module_type ~ filename m . pmd_type ; mdattributes = m . pmd_attributes ; mdloc = m . pmd_loc ; } { mtdname = m . pmtd_name ; mtdtype = Option . map ( module_type ~ filename ) m . pmtd_type ; mtdattributes = m . pmtd_attributes ; mtdloc = m . pmtd_loc ; }
let err_no_pred = " U + 0000 has no predecessor "
let err_no_succ = " U + 10FFFF has no successor "
let err_not_sv i = format_int " % X " i ^ " is not an Unicode scalar value "
let err_not_latin1 u = " U " + ^ format_int " % 04X " u ^ " is not a latin1 character "
let succ u = if u = lo_bound then hi_bound else if u = max then invalid_arg err_no_succ else u + 1
let pred u = if u = hi_bound then lo_bound else if u = min then invalid_arg err_no_pred else u - 1
let is_valid i = ( min <= i && i <= lo_bound ) || ( hi_bound <= i && i <= max )
let of_int i = if is_valid i then i else invalid_arg ( err_not_sv i )
let is_char u = u < 256
let of_char c = Char . code c
let to_char u = if u > 255 then invalid_arg ( err_not_latin1 u ) else Char . unsafe_chr u
let equal : int -> int -> bool = ( = )
let compare : int -> int -> int = Stdlib . compare
let log_err s = Printf . printf " % s : % s \ n " %! ( Filename . basename Sys . executable_name ) s
let is_white = function ' ' | ' \ t ' . . ' \ r ' -> true | _ -> false
let is_digit = function ' 0 ' . . ' 9 ' -> true | _ -> false
let hex_digit_value c = let c = Char . code c in if c <= 0x39 then c - 48 else if c <= 0x46 then c - 55 else c - 87
let str_starts s pre = let plen = String . length pre in let slen = String . length s in if plen > slen then false else try for i = 0 to plen - 1 do if pre . [ i ] <> s . [ i ] then raise Exit ; done ; true with Exit -> false
let str_is_ascii s = let max = String . length s - 1 in let rec loop s i = if i > max then true else if Char . code s . [ i ] > 0x7F then false else loop s ( i + 1 ) in loop s 0
let esc_non_ascii s = let b = Buffer . create 255 in let add_byte = function | c when Char . code c > 0x7F -> Buffer . add_string b ( strf " \\ x % 02X " ( Char . code c ) ) | c -> Buffer . add_char b c in String . iter add_byte s ; Buffer . contents b
let uchars_to_utf_bytes utf uchars = let b = Buffer . create 255 in let add_utf = match utf with | ` UTF_8 -> Uutf . Buffer . add_utf_8 | ` UTF_16BE -> Uutf . Buffer . add_utf_16be | ` UTF_16LE -> Uutf . Buffer . add_utf_16le in List . iter ( add_utf b ) uchars ; Buffer . contents b
let uchars_to_utf_bytes_esc utf uchars = let utf = uchars_to_utf_bytes utf uchars in let b = Buffer . create 255 in let add_byte c = Buffer . add_string b ( strf " \\ x % 02X " ( Char . code c ) ) in String . iter add_byte utf ; Buffer . contents b
let uchars_to_cps uchars = let to_str u = strf " U +% 04X " ( Uchar . to_int u ) in String . concat " " ( List . map to_str uchars )
let uchars_to_named_cps uchars = let to_str u = strf " % s ( U +% 04X ) " ( Uucp . Name . name u ) ( Uchar . to_int u ) in String . concat " " ( List . map to_str uchars )
let uchar_of_utf utf s = let fold = match utf with | ` UTF_8 -> Uutf . String . fold_utf_8 | ` UTF_16BE -> Uutf . String . fold_utf_16be | ` UTF_16LE -> Uutf . String . fold_utf_16le in match fold ( fun acc _ decode -> decode :: acc ) [ ] s with | [ ` Uchar u ] -> Some u | _ -> None
let try_uchar_of_utfs s = let rec try_decs s = function | [ ] -> None | enc :: encs -> match uchar_of_utf enc s with | None -> try_decs s encs | Some _ as u -> u in try_decs s [ ` UTF_8 ; ` UTF_16BE ; ` UTF_16LE ]
let parse_decimal_esc s = let max = String . length s - 1 in let rec loop s i acc = match i = max with | true -> if s . [ max ] = ' ; ' && Uchar . is_valid acc then Some ( Uchar . of_int acc ) else None | false -> if not ( is_digit s . [ i ] ) then None else loop s ( i + 1 ) ( acc * 10 + ( Char . code s . [ i ] - 48 ) ) in loop s 0 0
let parse_hex_esc s ~ finish = let max = String . length s - 1 in let parse_hex s start = let rec loop s i acc = if i > max then acc , max else if not ( is_hex_digit s . [ i ] ) then acc , i - 1 else loop s ( i + 1 ) ( acc * 16 + hex_digit_value s . [ i ] ) in loop s start 0 in let hex , last = parse_hex s 0 in let to_uchar hex = if Uchar . is_valid hex then Some ( Uchar . of_int hex ) else None in match finish with | ` Empty -> if last = max then to_uchar hex else None | ` Char c -> if last = max - 1 && s . [ max ] = c then to_uchar hex else None | ` Maybe_surrogate -> if last = max then to_uchar hex else match 0xD800 <= hex && hex <= 0xDBFF && last <= max - 3 && s . [ last + 1 ] = ' ' \\ && s . [ last + 2 ] = ' u ' with | false -> None | true -> let lo , last ' = parse_hex s ( last + 3 ) in match last ' = max && 0xDC00 <= lo && lo <= 0xDFFF with | false -> None | true -> Some ( Uchar . of_int @@ ( ( ( hex land 0x3FF ) lsl 10 ) lor ( lo land 0x3FF ) ) + 0x10000 )
let uchar_of_uchar_esc s = let prefixes = [ " U " ; + " u " ; + " U " ; " u " ; " \\ u { " ; " \\ U { " ; " \\ u " ; " \\ U " ; " &# x " ; " " &# ] in match try Some ( List . find ( str_starts s ) prefixes ) with Not_found -> None with | None -> None | Some pre -> let pre_len = String . length pre in let s = String . sub s pre_len ( String . length s - pre_len ) in match pre with | " " &# -> parse_decimal_esc s | " &# x " -> parse_hex_esc s ~ finish ( ` : Char ' ; ' ) | " \\ u " -> parse_hex_esc s ~ finish ` : Maybe_surrogate | " \\ u { " | " \\ U { " -> parse_hex_esc s ~ finish ( ` : Char ' } ' ) | _ -> parse_hex_esc s ~ finish ` : Empty
let uchar_of_utf_8_bytes_esc s = let b = Buffer . create 255 in let max = String . length s - 1 in let parse_hex_byte s i = match i + 1 <= max && is_hex_digit s . [ i ] && is_hex_digit s . [ i + 1 ] with | false -> None | true -> Some ( 16 * ( hex_digit_value s . [ i ] ) + ( hex_digit_value s . [ i + 1 ] ) ) in let rec loop s i = if i > max then uchar_of_utf ` UTF_8 ( Buffer . contents b ) else if is_white s . [ i ] then loop s ( i + 1 ) else if i + 1 > max then None else let i = match s . [ i ] with | ( ' 0 ' | ' ' ) \\ when s . [ i + 1 ] = ' x ' -> i + 2 | ' x ' -> i + 1 | _ -> i in match parse_hex_byte s i with | None -> None | Some byte -> Buffer . add_char b ( Char . chr byte ) ; loop s ( i + 2 ) in loop s 0
let guess_spec s = match str_is_ascii s with match uchar_of_uchar_esc s with | Some _ as u -> u | None -> uchar_of_utf_8_bytes_esc s
let parse_spec spec_fmt s = match spec_fmt with
let unicode_version ( ) = Printf . printf " % s \ n " %! Uucp . unicode_version
type out_fmt = { ascii : bool ; no_labels : bool ; raw_bytes : bool ; }
let str ( pp , key ) ( out_fmt : out_fmt ) u = strf " % a " pp ( key u )
let str_bool key ( out_fmt : out_fmt ) u = strf " % b " ( key u )
let str_int key ( out_fmt : out_fmt ) u = strf " % d " ( key u )
let str_uchar ( out_fmt : out_fmt ) u = uchars_to_cps [ u ]
let str_str key ( out_fmt : out_fmt ) u = key u
let str_utf utf out_fmt u = match out_fmt . raw_bytes with
let str_cps out_fmt uchars = let cps = uchars_to_cps uchars in match out_fmt . ascii with | true -> cps | false -> let utf_8 = uchars_to_utf_bytes ` UTF_8 uchars in strf " % s ( % s ) " utf_8 cps
let str_case_map map ( out_fmt : out_fmt ) u = let uchars = match map u with ` Self -> [ u ] | ` Uchars uchars -> uchars in str_cps out_fmt uchars
let str_decomposition_mapping ( out_fmt : out_fmt ) u = let uchars = match Uunf . decomp u with | [ ] || -> [ u ] | a -> let to_uchar i u = match i = 0 with | true -> Uunf . d_uchar u | false -> Uchar . of_int u in Array . ( to_list @@ mapi to_uchar a ) in str_cps out_fmt uchars
let str_name_alias key ( out_fmt : out_fmt ) u = let str_alias ( t , n ) = strf " % s ( % a ) " n Uucp . Name . pp_alias_tag t in String . concat " , " ( List . map str_alias ( key u ) )